forked from PaddlePaddle/Paddle
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpd_op_to_kernel_pass.cc
More file actions
3733 lines (3406 loc) · 143 KB
/
pd_op_to_kernel_pass.cc
File metadata and controls
3733 lines (3406 loc) · 143 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
// Copyright (c) 2023 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 "paddle/fluid/pir/transforms/pd_op_to_kernel_pass.h"
#include <iostream>
#include <regex>
#include <string>
#include <unordered_set>
#include "paddle/common/flags.h"
#include "paddle/fluid/framework/new_executor/collect_shape_manager.h"
#include "paddle/fluid/framework/op_kernel_type.h"
#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/pir/dialect/kernel/ir/kernel_attribute.h"
#include "paddle/fluid/pir/dialect/kernel/ir/kernel_dialect.h"
#include "paddle/fluid/pir/dialect/kernel/ir/kernel_op.h"
#include "paddle/fluid/pir/dialect/kernel/ir/kernel_type.h"
#include "paddle/fluid/pir/dialect/operator/interface/op_yaml_info.h"
#include "paddle/fluid/pir/dialect/operator/interface/parse_kernel_key.h"
#include "paddle/fluid/pir/dialect/operator/ir/api_builder.h"
#include "paddle/fluid/pir/dialect/operator/ir/control_flow_op.h"
#include "paddle/fluid/pir/dialect/operator/ir/manual_op.h"
#include "paddle/fluid/pir/dialect/operator/ir/manual_pylayer_op.h"
#include "paddle/fluid/pir/dialect/operator/ir/op_attribute.h"
#include "paddle/fluid/pir/dialect/operator/ir/op_dialect.h"
#include "paddle/fluid/pir/dialect/operator/ir/op_type.h"
#include "paddle/fluid/pir/dialect/operator/ir/pd_op.h"
#include "paddle/fluid/pir/dialect/operator/ir/tensorrt_op.h"
#include "paddle/fluid/pir/dialect/operator/trait/inplace.h"
#include "paddle/fluid/pir/dialect/operator/utils/op_yaml_info_parser.h"
#include "paddle/fluid/pir/dialect/operator/utils/op_yaml_info_util.h"
#include "paddle/fluid/pir/dialect/operator/utils/utils.h"
#include "paddle/fluid/pir/utils/general_functions.h"
#include "paddle/phi/api/lib/data_transform.h"
#include "paddle/phi/api/lib/kernel_dispatch.h"
#include "paddle/phi/backends/custom/custom_device_op_list.h"
#include "paddle/phi/common/place.h"
#include "paddle/phi/common/type_traits.h"
#include "paddle/phi/core/compat/convert_utils.h"
#include "paddle/phi/core/kernel_factory.h"
#include "paddle/phi/core/tensor_array.h"
#include "paddle/pir/include/core/builtin_op.h"
#include "paddle/pir/include/dialect/control_flow/ir/cf_op.h"
#ifdef PADDLE_WITH_CINN
#include "paddle/cinn/hlir/dialect/runtime/ir/jit_kernel_op.h"
#include "paddle/cinn/hlir/framework/pir/utils.h"
#endif
#ifdef PADDLE_WITH_CUSTOM_DEVICE
#include "paddle/fluid/custom_engine/custom_engine_manager.h"
#endif
#ifdef PADDLE_WITH_DNNL
#include "paddle/fluid/pir/dialect/operator/ir/onednn_op.h"
#include "paddle/fluid/pir/dialect/operator/ir/op_onednn_dialect.h"
#include "paddle/fluid/pir/dialect/operator/trait/onednn.h"
#include "paddle/phi/core/framework/framework.pb.h"
COMMON_DECLARE_bool(use_mkldnn);
COMMON_DECLARE_bool(use_onednn);
#endif
COMMON_DECLARE_bool(print_ir);
COMMON_DECLARE_bool(enable_collect_shape);
REGISTER_FILE_SYMBOLS(pd_op_to_kernel_pass);
namespace paddle::dialect {
pir::Type ConvertOpTypeToKernelType(pir::IrContext* ctx,
pir::Type op_type,
phi::Place place) {
if (op_type.isa<DenseTensorType>()) {
return AllocatedDenseTensorType::get(
ctx, place, op_type.dyn_cast<DenseTensorType>());
} else if (op_type.isa<DenseTensorArrayType>()) {
return AllocatedDenseTensorArrayType::get(
ctx, place, op_type.dyn_cast<DenseTensorArrayType>());
} else if (op_type.isa<SparseCooTensorType>()) {
return AllocatedSparseCooTensorType::get(
ctx, place, op_type.dyn_cast<SparseCooTensorType>());
} else if (op_type.isa<SparseCsrTensorType>()) {
return AllocatedSparseCsrTensorType::get(
ctx, place, op_type.dyn_cast<SparseCsrTensorType>());
} else if (op_type.isa<SelectedRowsType>()) {
return AllocatedSelectedRowsType::get(
ctx, place, op_type.dyn_cast<SelectedRowsType>());
} else if (op_type.isa<pir::VectorType>()) {
auto vec_type = op_type.dyn_cast<pir::VectorType>();
std::vector<pir::Type> vec_target_type;
for (size_t i = 0; i < vec_type.size(); ++i) {
vec_target_type.push_back(
ConvertOpTypeToKernelType(ctx, vec_type[i], place));
}
return pir::VectorType::get(ctx, vec_target_type);
} else if (!op_type) {
return pir::Type();
}
PADDLE_THROW(common::errors::Unimplemented(
"Not support op type %s in ConvertOpTypeToKernelType.", op_type));
}
static const std::vector<pir::Type> InferMetaByValue(
pir::Operation* op,
const std::vector<pir::Value>& input_values,
pir::AttributeMap* p_attribute_map) { // NOLINT
pir::OpInfo op_info =
pir::IrContext::Instance()->GetRegisteredOpInfo(op->name());
auto infer_meta_interface =
op_info.GetInterfaceImpl<paddle::dialect::InferMetaInterface>();
std::vector<pir::Type> output_types;
if (infer_meta_interface) {
output_types = infer_meta_interface->infer_meta_by_value_(input_values,
p_attribute_map);
}
return output_types;
}
std::unordered_map<std::string, phi::DataType> Str2PhiDataType = {
{"DataType::FLOAT16", phi::DataType::FLOAT16},
{"DataType::BFLOAT16", phi::DataType::BFLOAT16},
{"DataType::FLOAT32", phi::DataType::FLOAT32},
{"DataType::FLOAT64", phi::DataType::FLOAT64},
{"DataType::INT16", phi::DataType::INT16},
{"DataType::INT32", phi::DataType::INT32},
{"DataType::INT64", phi::DataType::INT64},
{"DataType::INT8", phi::DataType::INT8},
{"DataType::BOOL", phi::DataType::BOOL},
};
const std::unordered_set<std::string> UnchangeOutputOps = {
pir::CombineOp::name(),
pir::SliceOp::name(),
pir::SplitOp::name(),
pir::ConstantTensorOp::name(),
pir::SetParameterOp::name(),
pir::ParameterOp::name(),
pir::ShadowOutputOp::name(),
FeedOp::name(),
DataOp::name(),
ArrayLengthOp::name(),
"cinn_runtime.jit_kernel"};
const std::unordered_set<std::string> SpecialLowerOps = {
pir::CombineOp::name(),
pir::ConstantTensorOp::name(),
pir::SetParameterOp::name(),
pir::ParameterOp::name(),
pir::ShadowOutputOp::name(),
pir::SliceOp::name(),
pir::SplitOp::name(),
pir::YieldOp::name(),
IfOp::name(),
WhileOp::name(),
PyLayerOp::name(),
CudaGraphOp::name(),
pir::StackCreateOp::name(),
pir::TuplePushOp::name(),
pir::TuplePopOp::name(),
HasElementsOp::name(),
AssertOp::name(),
SelectInputOp::name(),
SelectOutputOp::name(),
"cinn_runtime.jit_kernel"};
const std::unordered_map<std::string, uint32_t> NoBufferRelatedOps = {
{paddle::dialect::ReshapeOp::name(), /*xshape_idx*/ 1U},
{paddle::dialect::Reshape_Op::name(), /*xshape_idx*/ 1U},
{paddle::dialect::SqueezeOp::name(), /*xshape_idx*/ 1U},
{paddle::dialect::Squeeze_Op::name(), /*xshape_idx*/ 1U},
{paddle::dialect::UnsqueezeOp::name(), /*xshape_idx*/ 1U},
{paddle::dialect::Unsqueeze_Op::name(), /*xshape_idx*/ 1U},
{paddle::dialect::FlattenOp::name(), /*xshape_idx*/ 1U},
{paddle::dialect::Flatten_Op::name(), /*xshape_idx*/ 1U},
{paddle::dialect::BatchNormOp::name(), /*reserve_space*/ 5U},
{paddle::dialect::BatchNorm_Op::name(), /*reserve_space*/ 5U},
};
// Please keep the consistency with paddle/phi/kernels/memcpy_kernel.cc
const std::unordered_map<int, phi::Place> MemcpyOpAttr2Place = {
{0, phi::CPUPlace()},
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
{1, phi::GPUPlace()},
{2, phi::GPUPinnedPlace()},
#elif defined(PADDLE_WITH_XPU)
{3, phi::XPUPlace()},
{5, phi::XPUPinnedPlace()},
#elif defined(PADDLE_WITH_CUSTOM_DEVICE)
{4, phi::CustomPlace()}
#endif
};
static bool NeedSkipPlaceTransfer(const pir::Operation* op) {
bool need_skip = false;
if (op->isa<paddle::dialect::FetchOp>()) {
auto define_op_name = op->operand_source(0).defining_op()->name();
uint32_t index = op->operand_source(0).dyn_cast<pir::OpResult>().index();
need_skip = NoBufferRelatedOps.count(define_op_name) > 0 &&
(NoBufferRelatedOps.at(define_op_name) == index);
}
return need_skip;
}
static bool NeedFallBackCpu(const pir::Operation* op,
const std::string& kernel,
const phi::KernelKey& kernel_key) {
if (op->HasAttribute(kForceBackendAttr) &&
op->attributes()
.at(kForceBackendAttr)
.dyn_cast<pir::StrAttribute>()
.AsString() == "cpu") {
return true;
}
#if defined(PADDLE_WITH_CUSTOM_DEVICE)
if (phi::backends::custom_device::is_in_custom_black_list(kernel)) {
phi::KernelKey copy_key = kernel_key;
copy_key.set_backend(phi::Backend::CPU);
if (phi::KernelFactory::Instance().HasKernel(kernel, copy_key)) {
return true;
} else {
PADDLE_THROW(common::errors::Unimplemented(
"Can not fallback %s from custom_device to CPU, no CPU kernel found "
"for kernel key = %s.",
kernel,
copy_key));
}
}
#endif
if (UnchangeOutputOps.count(op->name()) || kernel == "" ||
phi::KernelFactory::Instance().HasKernel(kernel, kernel_key)) {
return false;
}
phi::KernelKey copy_key = kernel_key;
if (copy_key.backend() == phi::Backend::GPUDNN) {
copy_key.set_backend(phi::Backend::GPU);
if (phi::KernelFactory::Instance().HasKernel(kernel, copy_key)) {
return false;
}
}
copy_key.set_backend(phi::Backend::CPU);
if (phi::KernelFactory::Instance().HasKernel(kernel, copy_key)) {
return true;
}
return false;
}
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
static bool NeedFallBackFromGPUDNN2GPU(pir::Operation* op,
const std::string& kernel_name,
const phi::KernelKey kernel_key) {
if (op->HasAttribute(kForceBackendAttr) &&
op->attributes()
.at(kForceBackendAttr)
.dyn_cast<pir::StrAttribute>()
.AsString() == "gpu") {
return true;
}
// NOTE(phlrain): keep the same kernel select strategy with
// GetExpectKernelKey
if (op->isa<Pool2dOp>() || op->isa<Pool2dGradOp>() || op->isa<Pool3dOp>() ||
op->isa<Pool3dGradOp>()) {
if (kernel_key.backend() == phi::Backend::GPUDNN &&
(op->attributes()
.at("adaptive")
.dyn_cast<pir::BoolAttribute>()
.data() == true)) {
return true;
}
} else if ((op->isa<AffineGridOp>() || op->isa<AffineGridGradOp>()) &&
kernel_key.backend() == phi::Backend::GPUDNN) {
bool use_cudnn = true;
int version = -1;
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
version = platform::DnnVersion();
#endif
if (version >= 6000 && op->attributes()
.at("align_corners")
.dyn_cast<pir::BoolAttribute>()
.data() == true) {
use_cudnn = true;
} else {
use_cudnn = false;
}
auto shape = pir::GetShapeFromValue(op->operand_source(0));
if (shape[1] == 3) {
use_cudnn = false;
}
#if defined(PADDLE_WITH_HIP)
use_cudnn = false;
#endif
return !use_cudnn;
}
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
if (kernel_key.backend() == phi::Backend::GPUDNN) {
auto iter = phi::KernelFactory::Instance().kernels().find(kernel_name);
if (iter != phi::KernelFactory::Instance().kernels().end()) {
auto kernel_iter = iter->second.find({phi::Backend::GPUDNN,
phi::DataLayout::ALL_LAYOUT,
kernel_key.dtype()});
if (kernel_iter == iter->second.end()) {
return true;
}
}
}
#endif
return false;
}
#endif
static phi::Backend DeriveBackend(const std::string& op,
const phi::Place& place,
const OpYamlInfoParser* op_info_parser,
phi::Backend kernel_backend,
size_t input_index) {
// NOTE: Parameters are initialized on executor place defined
if ((op == pir::SetParameterOp::name() ||
op == pir::ShadowOutputOp::name()) &&
phi::is_accelerat_allocation_type(place.GetType())) {
return phi::TransToPhiBackend(place);
}
// Tensor Attribute should on cpu backend for better performance
if (op_info_parser != nullptr &&
op_info_parser->IsTensorAttribute(input_index)) {
return phi::Backend::CPU;
}
return kernel_backend;
}
static phi::Backend ChooseInputBackend(const phi::Kernel& kernel,
size_t input_index,
phi::Backend default_backend) {
if (kernel.GetKernelRegisteredType() == phi::KernelRegisteredType::FUNCTION) {
return kernel.InputAt(input_index).backend;
}
return default_backend;
}
static std::set<std::string> GetInputsByDataOp(pir::Block* block) {
std::set<std::string> data_op_names;
for (auto& op_item : *block) {
if (op_item.isa<DataOp>()) {
data_op_names.insert(op_item.attributes()
.at("name")
.dyn_cast<pir::StrAttribute>()
.AsString());
}
}
return data_op_names;
}
template <class IrType>
static phi::DenseTensorMeta parse_tensor_meta(IrType type) {
auto dtype = TransToPhiDataType(type.dtype());
return phi::DenseTensorMeta(
dtype, type.dims(), type.data_layout(), type.lod(), type.offset());
}
template <>
phi::DenseTensorMeta parse_tensor_meta<AllocatedSparseCooTensorType>(
AllocatedSparseCooTensorType type) {
auto dtype = TransToPhiDataType(type.dtype());
return phi::DenseTensorMeta(dtype, type.dims(), type.data_layout());
}
template <>
phi::DenseTensorMeta parse_tensor_meta<AllocatedSparseCsrTensorType>(
AllocatedSparseCsrTensorType type) {
auto dtype = TransToPhiDataType(type.dtype());
return phi::DenseTensorMeta(dtype, type.dims(), type.data_layout());
}
static std::vector<std::shared_ptr<phi::TensorBase>> PrepareFakeTensors(
pir::Value input) {
std::vector<std::shared_ptr<phi::TensorBase>> res;
auto in_type = input.type();
auto fake_dt = [](const AllocatedDenseTensorType& type) {
auto ptr = new phi::Allocation(nullptr, 0, type.place());
std::shared_ptr<phi::Allocation> holder(ptr);
phi::DenseTensorMeta meta =
parse_tensor_meta<AllocatedDenseTensorType>(type);
return std::make_shared<phi::DenseTensor>(holder, meta);
};
auto fake_spcoo = [](const AllocatedSparseCooTensorType& type) {
auto ptr = new phi::Allocation(nullptr, 0, type.place());
std::shared_ptr<phi::Allocation> holder(ptr);
phi::DenseTensorMeta meta =
parse_tensor_meta<AllocatedSparseCooTensorType>(type);
return std::make_shared<phi::DenseTensor>(holder, meta);
};
auto fake_spcsr = [](const AllocatedSparseCsrTensorType& type) {
auto ptr = new phi::Allocation(nullptr, 0, type.place());
std::shared_ptr<phi::Allocation> holder(ptr);
phi::DenseTensorMeta meta =
parse_tensor_meta<AllocatedSparseCsrTensorType>(type);
return std::make_shared<phi::DenseTensor>(holder, meta);
};
auto fake_sr = [](const AllocatedSelectedRowsType& type) {
auto ptr = new phi::Allocation(nullptr, 0, type.place());
std::shared_ptr<phi::Allocation> holder(ptr);
phi::DenseTensorMeta meta =
parse_tensor_meta<AllocatedSelectedRowsType>(type);
std::vector<int64_t> rows;
rows.clear();
auto sr = std::make_shared<phi::SelectedRows>(rows, 0);
phi::DenseTensor dense_tensor(holder, meta);
*(sr->mutable_value()) = dense_tensor;
return sr;
};
auto fake_tensor_array = [](const AllocatedDenseTensorArrayType& type) {
auto ptr = new phi::Allocation(nullptr, 0, type.place());
std::shared_ptr<phi::Allocation> holder(ptr);
auto dtype = TransToPhiDataType(type.dtype());
phi::DenseTensorMeta meta(dtype, {});
phi::DenseTensor dt(holder, meta);
auto tensor_array = std::make_shared<phi::TensorArray>(0);
tensor_array->set_type(dtype);
tensor_array->push_back(dt);
return tensor_array;
};
if (in_type.isa<AllocatedDenseTensorType>()) {
res.push_back(fake_dt(in_type.dyn_cast<AllocatedDenseTensorType>()));
} else if (in_type.isa<AllocatedSelectedRowsType>()) {
res.push_back(fake_sr(in_type.dyn_cast<AllocatedSelectedRowsType>()));
} else if (in_type.isa<AllocatedSparseCsrTensorType>()) {
res.push_back(fake_spcsr(in_type.dyn_cast<AllocatedSparseCsrTensorType>()));
} else if (in_type.isa<AllocatedSparseCooTensorType>()) {
res.push_back(fake_spcoo(in_type.dyn_cast<AllocatedSparseCooTensorType>()));
} else if (in_type.isa<pir::VectorType>()) {
auto inner_types = in_type.dyn_cast<pir::VectorType>().data();
for (size_t i = 0; i < inner_types.size(); ++i) {
if (inner_types[i].isa<AllocatedDenseTensorType>()) {
res.push_back(
fake_dt(inner_types[i].dyn_cast<AllocatedDenseTensorType>()));
} else if (inner_types[i].isa<AllocatedSelectedRowsType>()) {
res.push_back(
fake_sr(inner_types[i].dyn_cast<AllocatedSelectedRowsType>()));
} else if (inner_types[i].isa<AllocatedDenseTensorArrayType>()) {
res.push_back(fake_tensor_array(
inner_types[i].dyn_cast<AllocatedDenseTensorArrayType>()));
}
}
} else if (in_type.isa<AllocatedDenseTensorArrayType>()) {
res.push_back(
fake_tensor_array(in_type.dyn_cast<AllocatedDenseTensorArrayType>()));
}
return res;
}
static pir::Value AddPlaceTransferOp(pir::Value in,
pir::Type out_type,
const phi::Place& src_place,
const phi::Place& dst_place,
const phi::KernelKey& kernel_key,
pir::Block* block) {
pir::IrContext* ctx = pir::IrContext::Instance();
auto copy_kernel_key = kernel_key;
auto place2backend = [](phi::AllocationType new_place_type) {
auto new_backend = phi::Backend::GPU;
switch (new_place_type) {
case phi::AllocationType::GPU:
new_backend = phi::Backend::GPU;
break;
case phi::AllocationType::XPU:
new_backend = phi::Backend::XPU;
break;
case phi::AllocationType::CUSTOM:
new_backend = phi::Backend::CUSTOM;
break;
case phi::AllocationType::IPU:
new_backend = phi::Backend::IPU;
break;
default:
new_backend = phi::Backend::CPU;
break;
}
return new_backend;
};
std::unordered_map<std::string, pir::Attribute> op_attribute;
if ((src_place.GetType() == phi::AllocationType::CPU) &&
phi::is_accelerat_allocation_type(dst_place.GetType())) {
copy_kernel_key.set_backend(place2backend(dst_place.GetType()));
VLOG(4) << "memcpy_h2d kernel_key: " << copy_kernel_key;
op_attribute = {
{"op_name", pir::StrAttribute::get(ctx, "pd_op.memcpy_h2d")},
{"kernel_name", pir::StrAttribute::get(ctx, "memcpy_h2d")},
{"kernel_key", KernelAttribute::get(ctx, copy_kernel_key)},
{"dst_place_type", pir::Int32Attribute::get(ctx, 1)}};
} else if (phi::is_accelerat_allocation_type(src_place.GetType()) &&
(dst_place.GetType() == phi::AllocationType::CPU)) {
if (src_place.GetType() == phi::AllocationType::CUSTOM) {
paddle::experimental::detail::KernelKeyParser kernel_key_parser;
auto fake_tensors = PrepareFakeTensors(in);
for (auto& fake_tensor : fake_tensors) {
kernel_key_parser.AssignKernelKeySet(*fake_tensor);
}
auto kernel_key = kernel_key_parser.key_set.GetHighestPriorityKernelKey();
copy_kernel_key.set_backend(kernel_key.backend());
} else {
copy_kernel_key.set_backend(place2backend(src_place.GetType()));
}
VLOG(4) << "memcpy_d2h kernel_key: " << copy_kernel_key;
std::string copy_kernel_name = "memcpy_d2h";
if (in.type().isa<AllocatedDenseTensorArrayType>()) {
copy_kernel_name = "memcpy_d2h_multi_io";
}
op_attribute = {
{"op_name", pir::StrAttribute::get(ctx, "pd_op." + copy_kernel_name)},
{"kernel_name", pir::StrAttribute::get(ctx, copy_kernel_name)},
{"kernel_key", KernelAttribute::get(ctx, copy_kernel_key)},
{"dst_place_type", pir::Int32Attribute::get(ctx, 0)}};
} else {
PADDLE_THROW(common::errors::Unimplemented(
"Only support cpu to gpu and gpu to cpu, src=%s, dst=%s.",
src_place,
dst_place));
}
pir::OpInfo kernel_op_info = ctx->GetRegisteredOpInfo(PhiKernelOp::name());
pir::Operation* op =
pir::Operation::Create({in}, op_attribute, {out_type}, kernel_op_info);
op->set_attribute("origin_id", pir::Int64Attribute::get(ctx, op->id()));
auto in_op = in.defining_op();
if (in_op && in_op->HasAttribute(kAttrIsPersistable)) {
op->set_attribute(kAttrIsPersistable, in_op->attribute(kAttrIsPersistable));
}
block->push_back(op);
auto new_in = op->result(0);
return new_in;
}
#ifdef PADDLE_WITH_DNNL
static pir::Value AddOneDNN2PaddleLayoutTransferOp(
pir::Value in, const phi::DataLayout& dst_layout, pir::Block* block) {
pir::IrContext* ctx = pir::IrContext::Instance();
auto in_alloc_type = in.type().dyn_cast<AllocatedDenseTensorType>();
phi::KernelKey kernel_key;
kernel_key.set_backend(phi::Backend::CPU);
kernel_key.set_layout(phi::DataLayout::ANY);
kernel_key.set_dtype(dialect::TransToPhiDataType(in_alloc_type.dtype()));
std::unordered_map<std::string, pir::Attribute> op_attribute;
op_attribute = {
{"op_name", pir::StrAttribute::get(ctx, "pd_op.onednn_to_paddle_layout")},
{"kernel_name", pir::StrAttribute::get(ctx, "onednn_to_paddle_layout")},
{"kernel_key", KernelAttribute::get(ctx, kernel_key)},
{"dst_layout",
pir::Int32Attribute::get(ctx, static_cast<int>(dst_layout))}};
auto out_type = AllocatedDenseTensorType::get(ctx,
in_alloc_type.place(),
in_alloc_type.dtype(),
in_alloc_type.dims(),
dst_layout,
in_alloc_type.lod(),
in_alloc_type.offset());
pir::OpInfo kernel_op_info = ctx->GetRegisteredOpInfo(PhiKernelOp::name());
pir::Operation* op =
pir::Operation::Create({in}, op_attribute, {out_type}, kernel_op_info);
op->set_attribute("origin_id", pir::Int64Attribute::get(ctx, op->id()));
auto in_op = in.defining_op();
if (in_op && in_op->HasAttribute(kAttrIsPersistable)) {
op->set_attribute(kAttrIsPersistable, in_op->attribute(kAttrIsPersistable));
}
block->push_back(op);
return op->result(0);
}
#endif
static bool NeedTransformDataType(const phi::DataType& l,
const phi::DataType& r) {
return l != phi::DataType::ALL_DTYPE && r != phi::DataType::ALL_DTYPE &&
l != r;
}
static const phi::DataType GetKernelTypeforVar(
pir::Operation* op,
const std::string& var_name,
const phi::DataType& tensor_dtype,
const phi::KernelKey* expected_kernel_key) {
pir::OpInfo op_info =
pir::IrContext::Instance()->GetRegisteredOpInfo(op->name());
auto get_kernel_type_for_var =
op_info.GetInterfaceImpl<GetKernelTypeForVarInterface>();
if (get_kernel_type_for_var) {
phi::DataType kernel_dtype_for_var =
get_kernel_type_for_var->get_kernel_type_for_var_(
var_name, tensor_dtype, (*expected_kernel_key).dtype());
return kernel_dtype_for_var;
}
return (*expected_kernel_key).dtype();
}
template <class IrType>
std::tuple<phi::Backend, phi::DataLayout> parse_kernel_info(pir::Type type) {
phi::Backend backend =
paddle::experimental::ParseBackend(type.dyn_cast<IrType>().place());
phi::DataLayout layout =
paddle::experimental::ParseLayout(type.dyn_cast<IrType>().data_layout());
return {backend, layout};
}
template <class IrType1, class IrType2>
static pir::Type create_sparse_coo_tensor_type(pir::Type type,
const phi::Place& place,
pir::Type out_dtype,
pir::IrContext* ctx) {
auto input_type = type.dyn_cast<IrType1>();
return IrType2::get(ctx,
place,
out_dtype,
input_type.dims(),
input_type.non_zero_dims(),
input_type.data_layout(),
input_type.non_zero_indices(),
input_type.non_zero_elements(),
input_type.coalesced());
}
template <class IrType1, class IrType2>
static pir::Type create_sparse_csr_tensor_type(pir::Type type,
const phi::Place& place,
pir::Type out_dtype,
pir::IrContext* ctx) {
auto input_type = type.dyn_cast<IrType1>();
return IrType2::get(ctx,
place,
out_dtype,
input_type.dims(),
input_type.data_layout(),
input_type.non_zero_crows(),
input_type.non_zero_cols(),
input_type.non_zero_elements());
}
template <class IrType1, class IrType2>
static pir::Type create_type(pir::Type type,
const phi::Place& place,
pir::Type out_dtype,
pir::IrContext* ctx) {
auto input_type = type.dyn_cast<IrType1>();
return IrType2::get(ctx,
place,
out_dtype,
input_type.dims(),
input_type.data_layout(),
input_type.lod(),
input_type.offset());
}
static pir::Type BuildDtypeTransferOutputType(pir::Type type,
const phi::Place& place,
phi::DataType data_dtype,
pir::IrContext* ctx) {
if (type.isa<AllocatedDenseTensorType>()) {
auto out_dtype = TransToIrDataType(data_dtype, ctx);
return create_type<AllocatedDenseTensorType, AllocatedDenseTensorType>(
type, place, out_dtype, ctx);
} else if (type.isa<AllocatedSelectedRowsType>()) {
auto out_dtype = TransToIrDataType(data_dtype, ctx);
return create_type<AllocatedSelectedRowsType, AllocatedSelectedRowsType>(
type, place, out_dtype, ctx);
} else if (type.isa<AllocatedSparseCooTensorType>()) {
auto out_dtype = TransToIrDataType(data_dtype, ctx);
return create_sparse_coo_tensor_type<AllocatedSparseCooTensorType,
AllocatedSparseCooTensorType>(
type, place, out_dtype, ctx);
} else if (type.isa<AllocatedSparseCsrTensorType>()) {
auto out_dtype = TransToIrDataType(data_dtype, ctx);
return create_sparse_csr_tensor_type<AllocatedSparseCsrTensorType,
AllocatedSparseCsrTensorType>(
type, place, out_dtype, ctx);
} else {
PADDLE_THROW(common::errors::Unimplemented(
"BuildOutputType only support DenseTensorType, SelectedRowsType, "
"SparseCooTensorType and SparseCsrTensorType"));
}
}
static pir::Type BuildOutputType(pir::Type type,
const phi::Place& place,
pir::IrContext* ctx) {
if (type.isa<DenseTensorType>()) {
auto out_dtype = type.dyn_cast<DenseTensorType>().dtype();
return create_type<DenseTensorType, AllocatedDenseTensorType>(
type, place, out_dtype, ctx);
} else if (type.isa<SelectedRowsType>()) {
auto out_dtype = type.dyn_cast<SelectedRowsType>().dtype();
return create_type<SelectedRowsType, AllocatedSelectedRowsType>(
type, place, out_dtype, ctx);
} else if (type.isa<DenseTensorArrayType>()) {
auto array_type = type.dyn_cast<DenseTensorArrayType>();
return AllocatedDenseTensorArrayType::get(ctx,
place,
array_type.dtype(),
array_type.dims(),
array_type.data_layout());
} else if (type.isa<SparseCooTensorType>()) {
auto out_dtype = type.dyn_cast<SparseCooTensorType>().dtype();
return create_sparse_coo_tensor_type<SparseCooTensorType,
AllocatedSparseCooTensorType>(
type, place, out_dtype, ctx);
} else if (type.isa<SparseCsrTensorType>()) {
auto out_dtype = type.dyn_cast<SparseCsrTensorType>().dtype();
return create_sparse_csr_tensor_type<SparseCsrTensorType,
AllocatedSparseCsrTensorType>(
type, place, out_dtype, ctx);
} else {
PADDLE_THROW(common::errors::Unimplemented(
"BuildOutputType only support DenseTensorType, SelectedRowsType, "
"SparseCooTensorType and SparseCsrTensorType"));
}
}
#ifdef PADDLE_WITH_DNNL
template <class IrType1, class IrType2>
static pir::Type create_type(pir::Type type,
const phi::Place& place,
const phi::DataLayout& layout,
pir::Type out_dtype,
pir::IrContext* ctx) {
auto input_type = type.dyn_cast<IrType1>();
return IrType2::get(ctx,
place,
out_dtype,
input_type.dims(),
layout,
input_type.lod(),
input_type.offset());
}
static pir::Type BuildOutputType(pir::Type type,
const phi::Place& place,
const phi::DataLayout& layout,
pir::IrContext* ctx) {
if (type.isa<DenseTensorType>()) {
auto out_dtype = type.dyn_cast<DenseTensorType>().dtype();
return create_type<DenseTensorType, AllocatedDenseTensorType>(
type, place, layout, out_dtype, ctx);
} else if (type.isa<SelectedRowsType>()) {
auto out_dtype = type.dyn_cast<SelectedRowsType>().dtype();
return create_type<SelectedRowsType, AllocatedSelectedRowsType>(
type, place, layout, out_dtype, ctx);
} else if (type.isa<DenseTensorArrayType>()) {
auto array_type = type.dyn_cast<DenseTensorArrayType>();
return AllocatedDenseTensorArrayType::get(
ctx, place, array_type.dtype(), array_type.dims(), layout);
} else {
PADDLE_THROW(common::errors::Unimplemented(
"BuildOutputType only support DenseTensorType and SelectedRowsType"));
}
}
#endif
pir::Value AddDtypeTransferOp(pir::Value in,
pir::Block* block,
const phi::KernelKey& kernel_key,
const phi::Place& origin_place,
const phi::Place& out_place,
const phi::DataType& src_dtype,
const phi::DataType& dst_dtype) {
pir::IrContext* ctx = pir::IrContext::Instance();
pir::OpInfo kernel_op_info = ctx->GetRegisteredOpInfo(PhiKernelOp::name());
// Get kernelkey (backend、layout)
phi::Backend kernel_backend = phi::Backend::UNDEFINED;
phi::DataLayout kernel_layout = phi::DataLayout::UNDEFINED;
if (in.type().isa<AllocatedDenseTensorType>()) {
auto out = parse_kernel_info<AllocatedDenseTensorType>(in.type());
kernel_backend = std::get<0>(out);
kernel_layout = std::get<1>(out);
} else if (in.type().isa<AllocatedSelectedRowsType>()) {
auto out = parse_kernel_info<AllocatedSelectedRowsType>(in.type());
kernel_backend = std::get<0>(out);
kernel_layout = std::get<1>(out);
} else if (in.type().isa<AllocatedSparseCooTensorType>()) {
auto out = parse_kernel_info<AllocatedSparseCooTensorType>(in.type());
kernel_backend = std::get<0>(out);
kernel_layout = std::get<1>(out);
} else if (in.type().isa<AllocatedSparseCsrTensorType>()) {
auto out = parse_kernel_info<AllocatedSparseCsrTensorType>(in.type());
kernel_backend = std::get<0>(out);
kernel_layout = std::get<1>(out);
} else {
PADDLE_THROW(common::errors::Unimplemented(
"Get kernelkey for CastOp only support "
"DenseTensorType, SparseCooTensorType, SparseCsrTensorType, and "
"SelectedRowsType"));
}
if (kernel_backend == phi::Backend::UNDEFINED) {
kernel_backend = paddle::experimental::ParseBackend(origin_place);
}
phi::KernelKey cast_kernel_key(kernel_backend, kernel_layout, src_dtype);
// Create CastOp
std::unordered_map<std::string, pir::Attribute> op_attribute{
{"op_name", pir::StrAttribute::get(ctx, "pd_op.cast")},
{"kernel_name", pir::StrAttribute::get(ctx, "cast")},
{"kernel_key", KernelAttribute::get(ctx, cast_kernel_key)},
{"dtype", DataTypeAttribute::get(ctx, dst_dtype)}};
pir::Type output_types =
BuildDtypeTransferOutputType(in.type(), out_place, dst_dtype, ctx);
pir::Operation* op = pir::Operation::Create(
{in}, op_attribute, {output_types}, kernel_op_info);
op->set_attribute("origin_id", pir::Int64Attribute::get(ctx, op->id()));
auto in_op = in.defining_op();
if (in_op && in_op->HasAttribute(kAttrIsPersistable)) {
op->set_attribute(kAttrIsPersistable, in_op->attribute(kAttrIsPersistable));
}
block->push_back(op);
pir::Value new_in = op->result(0);
return new_in;
}
static phi::DataType GetKernelDtypeByYaml(
const pir::Operation* op,
const std::unordered_map<pir::Value, pir::Value>& map_value_pair,
const OpYamlInfoParser* op_info_parser) {
auto& attr_map = op->attributes();
auto& data_type_info = op_info_parser->OpRuntimeInfo().kernel_key_dtype;
phi::DataType kernel_data_type = phi::DataType::UNDEFINED;
for (auto slot_name : data_type_info) {
auto& input_map = op_info_parser->InputName2Id();
bool is_complex_tag = false;
if (slot_name.find("complex:") == 0) {
slot_name = slot_name.substr(8);
is_complex_tag = true;
}
auto find_it = Str2PhiDataType.find(slot_name);
if (find_it != Str2PhiDataType.end()) {
kernel_data_type = find_it->second;
} else if (input_map.count(slot_name)) {
// parse from input
int in_index = static_cast<int>(input_map.at(slot_name));
auto type = map_value_pair.at(op->operand_source(in_index)).type();
if (type.isa<AllocatedDenseTensorType>()) {
kernel_data_type = TransToPhiDataType(
type.dyn_cast<AllocatedDenseTensorType>().dtype());
} else if (type.isa<pir::VectorType>()) {
auto vec_data = type.dyn_cast<pir::VectorType>().data();
if (vec_data.empty()) {
kernel_data_type = phi::DataType::UNDEFINED;
} else {
if (vec_data[0].isa<AllocatedDenseTensorType>()) {
kernel_data_type = TransToPhiDataType(
vec_data[0].dyn_cast<AllocatedDenseTensorType>().dtype());
} else if (vec_data[0].isa<AllocatedSelectedRowsType>()) {
kernel_data_type = TransToPhiDataType(
vec_data[0].dyn_cast<AllocatedSelectedRowsType>().dtype());
} else if (vec_data[0].isa<AllocatedSparseCooTensorType>()) {
kernel_data_type = TransToPhiDataType(
vec_data[0].dyn_cast<AllocatedSparseCooTensorType>().dtype());
} else if (vec_data[0].isa<AllocatedSparseCsrTensorType>()) {
kernel_data_type = TransToPhiDataType(
vec_data[0].dyn_cast<AllocatedSparseCsrTensorType>().dtype());
} else {
PADDLE_THROW(common::errors::Unimplemented(
"Only support DenseTensorType and SelectedRowsType in vector"));
}
}
} else if (type.isa<AllocatedSelectedRowsType>()) {
kernel_data_type = TransToPhiDataType(
type.dyn_cast<AllocatedSelectedRowsType>().dtype());
} else if (type.isa<AllocatedSparseCooTensorType>()) {
kernel_data_type = TransToPhiDataType(
type.dyn_cast<AllocatedSparseCooTensorType>().dtype());
} else if (type.isa<AllocatedSparseCsrTensorType>()) {
kernel_data_type = TransToPhiDataType(
type.dyn_cast<AllocatedSparseCsrTensorType>().dtype());
} else if (type.isa<AllocatedDenseTensorArrayType>()) {
kernel_data_type = TransToPhiDataType(
type.dyn_cast<AllocatedDenseTensorArrayType>().dtype());
} else {
PADDLE_THROW(common::errors::Unimplemented(
"Only support DenseTensorType, SelectedRows, SparseCooTensorType, "
"SparseCsrTensorType and VectorType"));
}
if (is_complex_tag) {
kernel_data_type = phi::dtype::ToComplex(kernel_data_type);
}
} else {
PADDLE_ENFORCE_EQ(attr_map.count(slot_name),
true,
common::errors::PreconditionNotMet(
"[%s] MUST in attribute map", slot_name));
auto attr_type = op_info_parser->AttrTypeName(slot_name);
PADDLE_ENFORCE_EQ(attr_type,
"paddle::dialect::DataTypeAttribute",
common::errors::PreconditionNotMet(
"Type of [%s] should be DataType", slot_name));
kernel_data_type =
attr_map.at(slot_name).dyn_cast<DataTypeAttribute>().data();
}
if (kernel_data_type != phi::DataType::UNDEFINED) {
// In yaml definition, data type have an order
// like: data_type : dtype > x
// Should break when found a defined data type
break;
}
}
return kernel_data_type;
}
static phi::Backend GetKernelBackendByYaml(
const pir::Operation* op,
const std::unordered_map<pir::Value, pir::Value>& map_value_pair,
const OpYamlInfoParser* op_info_parser,
const phi::Place& place) {
auto& attr_map = op->attributes();
auto& backend_info = op_info_parser->OpRuntimeInfo().kernel_key_backend;
phi::Backend kernel_backend = phi::Backend::UNDEFINED;
for (const auto& slot_name : backend_info) {
auto& input_map = op_info_parser->InputName2Id();
if (input_map.count(slot_name)) {
// parse from input
int in_index = static_cast<int>(input_map.at(slot_name));
auto type = map_value_pair.at(op->operand_source(in_index)).type();
if (type.isa<AllocatedDenseTensorType>()) {
kernel_backend = paddle::experimental::ParseBackend(
type.dyn_cast<AllocatedDenseTensorType>().place());
} else if (type.isa<pir::VectorType>()) {
auto vec_data = type.dyn_cast<pir::VectorType>().data();
if (vec_data.empty()) {
kernel_backend = phi::Backend::UNDEFINED;
} else {
if (vec_data[0].isa<AllocatedDenseTensorType>()) {
kernel_backend = paddle::experimental::ParseBackend(
vec_data[0].dyn_cast<AllocatedDenseTensorType>().place());
} else {
PADDLE_THROW(common::errors::Unimplemented(
"Only support DenseTensorType in vector"));
}
}
} else if (type.isa<AllocatedSelectedRowsType>()) {
kernel_backend = paddle::experimental::ParseBackend(
type.dyn_cast<AllocatedSelectedRowsType>().place());
} else if (type.isa<AllocatedSparseCooTensorType>()) {
kernel_backend = paddle::experimental::ParseBackend(
type.dyn_cast<AllocatedSparseCooTensorType>().place());
} else if (type.isa<AllocatedSparseCsrTensorType>()) {
kernel_backend = paddle::experimental::ParseBackend(
type.dyn_cast<AllocatedSparseCsrTensorType>().place());
} else if (type.isa<AllocatedDenseTensorArrayType>()) {
kernel_backend = paddle::experimental::ParseBackend(
type.dyn_cast<AllocatedDenseTensorArrayType>().place());
} else {
PADDLE_THROW(common::errors::Unimplemented(
"Only support DenseTensorType, SelectedRows, SparseCooTensorType, "
"SparseCsrTensorType and VectorType"));
}
} else {