-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
elementwise_grad_kernel_impl.h
1480 lines (1378 loc) · 52.3 KB
/
elementwise_grad_kernel_impl.h
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) 2022 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. */
#pragma once
#include "glog/logging.h"
#include "paddle/phi/common/amp_type_traits.h"
#include "paddle/phi/common/complex.h"
#include "paddle/phi/common/float16.h"
#include "paddle/phi/core/dense_tensor.h"
#include "paddle/phi/core/tensor_utils.h"
#include "paddle/phi/kernels/expand_kernel.h"
#include "paddle/phi/kernels/full_kernel.h"
#include "paddle/phi/kernels/funcs/broadcast_function.h"
#include "paddle/phi/kernels/funcs/eigen/common.h"
#include "paddle/phi/kernels/funcs/elementwise_functor.h"
#include "paddle/phi/kernels/funcs/elementwise_utils.h"
namespace phi {
template <typename T, typename Context, typename GradFunc>
void AddGradImpl(const Context& dev_ctx,
const DenseTensor& x,
const DenseTensor& y,
const DenseTensor& out_grad,
int axis,
DenseTensor* x_grad,
DenseTensor* y_grad,
GradFunc grad_func) {
phi::funcs::ElementwiseGradPreProcess(out_grad, x_grad);
auto* out = &out_grad;
// Special case when y_grad is not needed and x_grad doesn't reduce
if (x_grad != nullptr && y_grad == nullptr &&
x_grad->dims() == out_grad.dims()) {
VLOG(4) << "Special case when y_grad is not needed and x_grad doesn't "
"reduce";
phi::Copy(dev_ctx, out_grad, dev_ctx.GetPlace(), false, x_grad);
} else if (x_grad == nullptr && y_grad != nullptr &&
y_grad->dims() == out_grad.dims()) {
VLOG(4) << "Special case when x_grad is not needed and y_grad doesn't "
"reduce";
phi::Copy(dev_ctx, out_grad, dev_ctx.GetPlace(), false, y_grad);
} else {
grad_func(dev_ctx, x, y, *out, out_grad, x_grad, y_grad, axis);
}
}
template <typename T, typename Context>
void AddDoubleGradImpl(const Context& dev_ctx,
const DenseTensor& y,
const paddle::optional<DenseTensor>& ddx,
const paddle::optional<DenseTensor>& ddy,
const DenseTensor& dout,
int axis,
DenseTensor* ddout) {
// ddOut = ddx + ddy
if (ddout) {
auto* ddx_tensor = ddx.get_ptr();
auto* ddy_tensor = ddy.get_ptr();
auto out_shape = dout.dims();
dev_ctx.template Alloc<T>(ddout);
if (ddx_tensor == nullptr && ddy_tensor == nullptr) {
VLOG(4) << "Special case when ddx and ddy are not needed \n";
ddout = nullptr;
} else if (ddx_tensor == nullptr && ddy_tensor != nullptr) {
if (ddy_tensor->dims() != out_shape) {
VLOG(4) << "Special case when ddx is not needed and ddy needs to "
"broadcast\n";
std::vector<const DenseTensor*> ins = {ddy_tensor};
std::vector<DenseTensor*> outs = {ddout};
ExpandKernel<T, Context>(dev_ctx,
*ddy_tensor,
IntArray{phi::vectorize<int64_t>(out_shape)},
ddout);
} else {
VLOG(4) << "Special case when ddx is not needed and ddy doesn't need "
"to broadcast\n";
phi::Copy(dev_ctx, *ddy_tensor, dev_ctx.GetPlace(), false, ddout);
}
} else if (ddx_tensor != nullptr && ddy_tensor == nullptr) {
if (ddx_tensor->dims() != out_shape) {
VLOG(4) << "Special case when ddy is not needed and ddx need to "
"broadcast\n";
std::vector<const DenseTensor*> ins = {ddx_tensor};
std::vector<DenseTensor*> outs = {ddout};
ExpandKernel<T, Context>(dev_ctx,
*ddx_tensor,
IntArray{phi::vectorize<int64_t>(out_shape)},
ddout);
} else {
VLOG(4) << "Special case when ddx is not needed and ddy doesn't need "
"to broadcast\n";
phi::Copy(dev_ctx, *ddx_tensor, dev_ctx.GetPlace(), false, ddout);
}
} else {
auto ddx_dims = ddx_tensor->dims();
auto ddy_dims = ddy_tensor->dims();
if (ddx_dims.size() >= ddy_dims.size()) {
funcs::ElementwiseCompute<funcs::AddFunctor<T>, T>(
dev_ctx,
*ddx_tensor,
*ddy_tensor,
funcs::AddFunctor<T>(),
ddout,
axis);
} else {
funcs::ElementwiseCompute<funcs::InverseAddFunctor<T>, T>(
dev_ctx,
*ddx_tensor,
*ddy_tensor,
funcs::InverseAddFunctor<T>(),
ddout,
axis);
}
}
}
}
template <typename T, typename Context>
void SubtractDoubleGradImpl(const Context& dev_ctx,
const DenseTensor& y,
const paddle::optional<DenseTensor>& ddx,
const paddle::optional<DenseTensor>& ddy,
const DenseTensor& dout,
int axis,
DenseTensor* ddout) {
// DDOut = ddx - ddy
if (ddout) {
DenseTensor ddx_safe, ddy_safe;
funcs::GetDoubleGradSafeTensor<Context, T>(
dev_ctx, dout, ddx.get_ptr(), &ddx_safe);
funcs::GetDoubleGradSafeTensor<Context, T>(
dev_ctx, y, ddy.get_ptr(), &ddy_safe);
dev_ctx.template Alloc<T>(ddout);
funcs::ElementwiseCompute<funcs::SubtractFunctor<T>, T>(
dev_ctx, ddx_safe, ddy_safe, funcs::SubtractFunctor<T>(), ddout, axis);
}
}
/*
******************************
Divide Grad
******************************
*/
template <typename T>
struct DivGradDX {
HOSTDEVICE T operator()(T x UNUSED, T y, T out UNUSED, T dout) const {
return dout / y;
}
};
template <typename T>
struct DivGradDX<phi::dtype::complex<T>> {
HOSTDEVICE phi::dtype::complex<T> operator()(
phi::dtype::complex<T> x UNUSED,
phi::dtype::complex<T> y,
phi::dtype::complex<T> out UNUSED,
phi::dtype::complex<T> dout) const {
phi::dtype::complex<T> y_conj(y.real, -y.imag);
return dout / y_conj;
}
};
template <typename T>
struct DivGradDY {
HOSTDEVICE T operator()(T x UNUSED, T y, T out, T dout) const {
return -dout * out / y;
}
};
template <typename T>
struct DivGradDY<phi::dtype::complex<T>> {
HOSTDEVICE phi::dtype::complex<T> operator()(
phi::dtype::complex<T> x UNUSED,
phi::dtype::complex<T> y,
phi::dtype::complex<T> out,
phi::dtype::complex<T> dout) const {
phi::dtype::complex<T> out_div_y_conj((out / y).real, -(out / y).imag);
return -dout * out_div_y_conj;
}
};
template <typename T>
struct DivDoubleDY {
HOSTDEVICE T operator()(const T& x,
const T& y,
const T& out,
const T& dout) const {
return (y * out - x) * dout;
}
};
template <typename T>
struct DivDoubleDY_Only_DDY {
HOSTDEVICE T operator()(const T& x,
const T& y,
const T& out,
const T& dout) const {
return y * out * dout;
}
};
template <typename T>
struct DivDoubleDY_Only_DDX {
HOSTDEVICE T operator()(const T& x,
const T& y,
const T& out,
const T& dout) const {
return -x * dout;
}
};
// ddOut = ddX / Y - Out * ddY / Y = (ddX - Out * ddY) / Y
template <typename T>
struct DivDoubleDDOut {
HOSTDEVICE T operator()(const T& ddx,
const T& ddy,
const T& y,
const T& out) const {
return (ddx - out * ddy) / y;
}
};
template <typename T>
struct DivDoubleDDOut_Only_DDY {
HOSTDEVICE T operator()(const T& ddx,
const T& ddy,
const T& y,
const T& out) const {
return -out * ddy / y;
}
};
template <typename T, typename DDout_OP, typename OutType = T>
void ComputeDDoutWithoutBroadcast(const CPUContext& dev_ctx UNUSED,
const phi::DenseTensor& ddx,
const phi::DenseTensor& ddy,
const phi::DenseTensor& y,
const phi::DenseTensor& out,
phi::DenseTensor* ddout,
DDout_OP dout_op) {
auto out_numel = out.numel();
auto* ddx_data = ddx.data<T>();
auto* ddy_data = ddy.data<T>();
auto* y_data = y.data<T>();
auto* out_data = out.data<T>();
auto* ddout_data = ddout->data<T>();
for (int i = 0; i < out_numel; i++) {
ddout_data[i] = dout_op(ddx_data[i], ddy_data[i], y_data[i], out_data[i]);
}
}
template <typename T, typename DDout_OP, typename OutType = T>
void ComputeDDoutWithBroadcast(const CPUContext& dev_ctx UNUSED,
const phi::DenseTensor& ddx,
const phi::DenseTensor& ddy,
const phi::DenseTensor& y,
const phi::DenseTensor& out,
phi::DenseTensor* ddout,
const int* x_dims_array,
const int* y_dims_array,
const int* out_dims_array,
const int max_dim,
DDout_OP dout_op) {
auto out_numel = out.numel();
auto* ddx_data = ddx.data<T>();
auto* ddy_data = ddy.data<T>();
auto* y_data = y.data<T>();
auto* out_data = out.data<T>();
auto* ddout_data = ddout->data<T>();
std::vector<int> index_array(max_dim, 0);
for (int i = 0; i < out_numel; i++) {
int x_index = phi::funcs::GetElementwiseIndex(
x_dims_array, max_dim, index_array.data());
int y_index = phi::funcs::GetElementwiseIndex(
y_dims_array, max_dim, index_array.data());
ddout_data[i] = dout_op(
ddx_data[x_index], ddy_data[y_index], y_data[y_index], out_data[i]);
phi::funcs::UpdateElementwiseIndexArray(
out_dims_array, max_dim, index_array.data());
}
}
#if defined(__NVCC__) || defined(__HIPCC__)
template <typename T, typename DDout_OP, typename OutType = T>
__global__ void ComputeDDoutWithoutBroadcastGPUKernel(const T* ddx_data,
const T* ddy_data,
const T* y_data,
const T* out_data,
T* ddout_data,
int numel,
DDout_OP dout_op) {
int tid = threadIdx.x + blockIdx.x * blockDim.x;
if (tid >= numel) return;
ddout_data[tid] =
dout_op(ddx_data[tid], ddy_data[tid], y_data[tid], out_data[tid]);
}
template <typename T, typename DDout_OP, typename OutType = T>
void ComputeDDoutWithoutBroadcast(const GPUContext& dev_ctx UNUSED,
const phi::DenseTensor& ddx,
const phi::DenseTensor& ddy,
const phi::DenseTensor& y,
const phi::DenseTensor& out,
phi::DenseTensor* ddout,
DDout_OP dout_op) {
auto out_numel = out.numel();
auto* ddx_data = ddx.data<T>();
auto* ddy_data = ddy.data<T>();
auto* y_data = y.data<T>();
auto* out_data = out.data<T>();
auto* ddout_data = ddout->data<T>();
int block = 512;
int64_t grid = (out_numel + block - 1) / block;
auto stream = reinterpret_cast<const phi::GPUContext&>(dev_ctx).stream();
ComputeDDoutWithoutBroadcastGPUKernel<T, DDout_OP, T>
<<<grid, block, 0, stream>>>(
ddx_data, ddy_data, y_data, out_data, ddout_data, out_numel, dout_op);
}
template <typename T, typename DDout_OP, typename OutType = T>
__global__ void ComputeDDoutWithBroadcastGPUKernel(const T* ddx_data,
const T* ddy_data,
const T* y_data,
const T* out_data,
T* ddout_data,
int numel,
const int* x_dims_array,
const int* y_dims_array,
const int* out_dims_array,
const int max_dim,
DDout_OP dout_op) {
int tid = threadIdx.x + blockIdx.x * blockDim.x;
if (tid >= numel) return;
int x_index = 0, y_index = 0, x_index_prod = 1, y_index_prod = 1,
out_index = tid, dim_index;
for (int64_t i = max_dim - 1; i >= 0; i--) {
if (out_index == 0) break;
dim_index = out_index % out_dims_array[i];
out_index = out_index / out_dims_array[i];
if (x_dims_array[i] > 1) {
x_index += dim_index * x_index_prod;
x_index_prod *= x_dims_array[i];
}
if (y_dims_array[i] > 1) {
y_index += dim_index * y_index_prod;
y_index_prod *= y_dims_array[i];
}
}
ddout_data[tid] = dout_op(
ddx_data[x_index], ddy_data[y_index], y_data[y_index], out_data[tid]);
}
template <typename T, typename DDout_OP, typename OutType = T>
void ComputeDDoutWithBroadcast(const GPUContext& dev_ctx UNUSED,
const phi::DenseTensor& ddx,
const phi::DenseTensor& ddy,
const phi::DenseTensor& y,
const phi::DenseTensor& out,
phi::DenseTensor* ddout,
const int* x_dims_array,
const int* y_dims_array,
const int* out_dims_array,
const int max_dim,
DDout_OP dout_op) {
auto out_numel = out.numel();
auto* ddx_data = ddx.data<T>();
auto* ddy_data = ddy.data<T>();
auto* y_data = y.data<T>();
auto* out_data = out.data<T>();
auto* ddout_data = ddout->data<T>();
DenseTensor x_dims_array_gpu;
x_dims_array_gpu.Resize({max_dim});
int* x_dims_array_gpu_data = dev_ctx.template Alloc<int>(&x_dims_array_gpu);
#if defined(__NVCC__)
cudaMemcpy(x_dims_array_gpu_data,
x_dims_array,
sizeof(int) * max_dim,
cudaMemcpyHostToDevice);
#else
hipMemcpy(x_dims_array_gpu_data,
x_dims_array,
sizeof(int) * max_dim,
hipMemcpyHostToDevice);
#endif
DenseTensor y_dims_array_gpu;
y_dims_array_gpu.Resize({max_dim});
int* y_dims_array_gpu_data = dev_ctx.template Alloc<int>(&y_dims_array_gpu);
#if defined(__NVCC__)
cudaMemcpy(y_dims_array_gpu_data,
y_dims_array,
sizeof(int) * max_dim,
cudaMemcpyHostToDevice);
#else
hipMemcpy(y_dims_array_gpu_data,
y_dims_array,
sizeof(int) * max_dim,
hipMemcpyHostToDevice);
#endif
DenseTensor out_dims_array_gpu;
out_dims_array_gpu.Resize({max_dim});
int* out_dims_array_gpu_data =
dev_ctx.template Alloc<int>(&out_dims_array_gpu);
#if defined(__NVCC__)
cudaMemcpy(out_dims_array_gpu_data,
out_dims_array,
sizeof(int) * max_dim,
cudaMemcpyHostToDevice);
#else
hipMemcpy(out_dims_array_gpu_data,
out_dims_array,
sizeof(int) * max_dim,
hipMemcpyHostToDevice);
#endif
int block = 512;
int64_t grid = (out_numel + block - 1) / block;
auto stream = reinterpret_cast<const phi::GPUContext&>(dev_ctx).stream();
ComputeDDoutWithBroadcastGPUKernel<T, DDout_OP, T>
<<<grid, block, 0, stream>>>(ddx_data,
ddy_data,
y_data,
out_data,
ddout_data,
out_numel,
x_dims_array_gpu_data,
y_dims_array_gpu_data,
out_dims_array_gpu_data,
max_dim,
dout_op);
}
#endif
template <typename DeviceContext,
typename T,
typename DDout_OP,
typename Tout = T>
void DivDoubleDDoutCompute(const DeviceContext& dev_ctx,
const phi::DenseTensor& ddx,
const phi::DenseTensor& ddy,
const phi::DenseTensor& y,
const phi::DenseTensor& out,
int axis,
phi::DenseTensor* ddout,
DDout_OP dout_op) {
auto x_dims = ddx.dims();
auto y_dims = ddy.dims();
if (x_dims == y_dims) {
ComputeDDoutWithoutBroadcast<T, DDout_OP, T>(
dev_ctx, ddx, ddy, y, out, ddout, dout_op);
} else {
int max_dim = std::max(x_dims.size(), y_dims.size());
axis = (axis == -1 ? std::abs(x_dims.size() - y_dims.size()) : axis);
std::vector<int> x_dims_array(max_dim, 0);
std::vector<int> y_dims_array(max_dim, 0);
std::vector<int> out_dims_array(max_dim, 0);
phi::funcs::GetBroadcastDimsArrays(x_dims,
y_dims,
x_dims_array.data(),
y_dims_array.data(),
out_dims_array.data(),
max_dim,
axis);
ComputeDDoutWithBroadcast<T, DDout_OP, T>(dev_ctx,
ddx,
ddy,
y,
out,
ddout,
x_dims_array.data(),
y_dims_array.data(),
out_dims_array.data(),
max_dim,
dout_op);
}
}
template <typename T, typename Context>
void DivideDoubleGradKernel(const Context& dev_ctx,
const DenseTensor& y,
const DenseTensor& out,
const DenseTensor& grad_out,
const paddle::optional<DenseTensor>& dx,
const paddle::optional<DenseTensor>& ddx,
const paddle::optional<DenseTensor>& ddy,
int axis,
DenseTensor* dy,
DenseTensor* dout,
DenseTensor* ddout) {
auto* ddx_tensor = ddx.get_ptr();
auto* ddy_tensor = ddy.get_ptr();
auto* dx_tensor = dx.get_ptr();
DenseTensor dz_div_y;
if ((dy || dout) && (!dx_tensor || dx_tensor->dims() != out.dims())) {
dz_div_y.Resize(out.dims());
dev_ctx.template Alloc<T>(&dz_div_y);
funcs::DefaultElementwiseOperator<Context,
T,
funcs::DivideFunctor<T>,
funcs::InverseDivideFunctor<T>>(
dev_ctx, grad_out, y, &dz_div_y, axis);
dx_tensor = &dz_div_y;
}
// ddOut = ddX / Y - Out * ddY / Y = (ddX - Out * ddY) / Y
// dY = Out * dX * ddY / Y - dX * ddX / Y
// dOut = - dX * ddY
// To save memory, (1) dout can be used as 'tmp' tensor, (2) ddout can
// inplace ddx
DenseTensor tmp;
if (dout) {
dout->Resize(out.dims());
dev_ctx.template Alloc<T>(dout);
tmp = *dout;
} else {
tmp.Resize(out.dims());
dev_ctx.template Alloc<T>(&tmp);
}
if (dy) {
dy->Resize(y.dims());
dev_ctx.template Alloc<T>(dy);
if (!ddx_tensor && !ddy_tensor) {
FullLikeKernel<T, Context>(
dev_ctx, y, Scalar(static_cast<T>(0.0)), y.dtype(), dy);
} else {
// pre-compute 'dX / Y' into 'tmp' for 'ddout' and/or 'dy'
funcs::DefaultElementwiseOperator<Context,
T,
funcs::DivideFunctor<T>,
funcs::InverseDivideFunctor<T>>(
dev_ctx, *dx_tensor, y, &tmp, axis);
if (ddx_tensor && !ddy_tensor) {
// dy = -dX * ddX / Y
phi::funcs::ElemwiseGradCompute<Context,
T,
DivGradDX<T>,
DivDoubleDY_Only_DDX<T>>(
dev_ctx,
*ddx_tensor, // ddx
y,
out, // out
tmp, // dX /Y
axis,
nullptr,
dy,
DivGradDX<T>(),
DivDoubleDY_Only_DDX<T>());
} else if (!ddx_tensor && ddy_tensor) {
// dY = Out * dX * ddY / Y
phi::funcs::ElemwiseGradCompute<Context,
T,
DivGradDX<T>,
DivDoubleDY_Only_DDY<T>>(
dev_ctx,
*dx_tensor,
*ddy_tensor, // ddy
out, // out
tmp, // dX / Y
axis,
nullptr,
dy,
DivGradDX<T>(),
DivDoubleDY_Only_DDY<T>());
} else {
// dY = Out * dX * ddY / Y - dX * ddX / Y
// NOTE(dengkaipeng): in the following ElemwiseGradCompute, for the
// first output tensor is nullptr, the branch to calculate first
// output tensor will not be activated, DivGradDx function will not
// be called and can be ignored, the first branch has little effect
// on running speed.
phi::funcs::
ElemwiseGradCompute<Context, T, DivGradDX<T>, DivDoubleDY<T>>(
dev_ctx,
*ddx_tensor, // ddx
*ddy_tensor, // ddy
out, // out
tmp, // dX / Y
axis,
nullptr,
dy,
DivGradDX<T>(),
DivDoubleDY<T>());
}
}
}
if (ddout) {
ddout->Resize(out.dims());
dev_ctx.template Alloc<T>(ddout);
// ddOut = ddX / Y - Out * ddY / Y = (ddX - Out * ddY) / Y
if (!ddx_tensor && !ddy_tensor) {
FullLikeKernel<T, Context>(
dev_ctx, out, Scalar(static_cast<T>(0.0)), out.dtype(), ddout);
} else if (ddx_tensor != nullptr && ddy_tensor == nullptr) {
// ddOut = ddX / Y
funcs::DefaultElementwiseOperator<Context,
T,
funcs::DivideFunctor<T>,
funcs::InverseDivideFunctor<T>>(
dev_ctx, *ddx_tensor, y, ddout, axis);
} else if (!ddx_tensor && ddy_tensor) {
// ddOut = - Out * ddY / Y
#if defined(__xpu__)
funcs::DefaultElementwiseOperator<Context,
T,
funcs::MultiplyFunctor<T>,
funcs::InverseMultiplyFunctor<T>>(
dev_ctx, out, *ddy_tensor, &tmp, axis);
funcs::DefaultElementwiseOperator<Context,
T,
funcs::DivideFunctor<T>,
funcs::InverseDivideFunctor<T>>(
dev_ctx, tmp, y, ddout, axis);
auto& place = *dev_ctx.eigen_device();
auto ddout_result = phi::EigenVector<T>::Flatten(*ddout);
ddout_result.device(place) = static_cast<T>(-1) * ddout_result;
#else
DivDoubleDDoutCompute<Context, T, DivDoubleDDOut_Only_DDY<T>, T>(
dev_ctx,
*dx_tensor,
*ddy_tensor,
y,
out,
axis,
ddout,
DivDoubleDDOut_Only_DDY<T>());
#endif
} else {
#if defined(__xpu__)
funcs::DefaultElementwiseOperator<Context,
T,
funcs::MultiplyFunctor<T>,
funcs::InverseMultiplyFunctor<T>>(
dev_ctx, out, *ddy_tensor, &tmp, axis);
funcs::DefaultElementwiseOperator<Context,
T,
funcs::SubtractFunctor<T>,
funcs::InverseSubtractFunctor<T>>(
dev_ctx, *ddx_tensor, tmp, &tmp, axis);
funcs::DefaultElementwiseOperator<Context,
T,
funcs::DivideFunctor<T>,
funcs::InverseDivideFunctor<T>>(
dev_ctx, tmp, y, ddout, axis);
#else
DivDoubleDDoutCompute<Context, T, DivDoubleDDOut<T>, T>(
dev_ctx,
*ddx_tensor,
*ddy_tensor,
y,
out,
axis,
ddout,
DivDoubleDDOut<T>());
#endif
}
}
if (dout) {
if (!ddy_tensor) {
FullLikeKernel<T, Context>(
dev_ctx, out, Scalar(static_cast<T>(0.0)), out.dtype(), dout);
} else {
// dOut = - dX * ddY
funcs::DefaultElementwiseOperator<Context,
T,
funcs::MultiplyFunctor<T>,
funcs::InverseMultiplyFunctor<T>>(
dev_ctx, *dx_tensor, *ddy_tensor, dout, axis);
auto& place = *dev_ctx.eigen_device();
auto dout_result = phi::EigenVector<T>::Flatten(*dout);
dout_result.device(place) = static_cast<T>(-1) * dout_result;
}
}
}
template <typename T, typename Context>
void ElementwiseFMaxGradKernel(const Context& dev_ctx,
const DenseTensor& x,
const DenseTensor& y,
const DenseTensor& out_grad,
DenseTensor* x_grad,
DenseTensor* y_grad) {
funcs::ElementwiseGradPreProcess(out_grad, x_grad);
auto out = out_grad; // Fake out, not used
auto x_dim = x.dims();
auto y_dim = y.dims();
int axis = -1;
if (x.dims() == y.dims()) {
funcs::ElemwiseGradComputeNoBroadcast<Context,
T,
funcs::FMaxGradDx<T>,
funcs::FMaxGradDy<T>>(
dev_ctx,
x_dim,
y_dim,
x,
y,
out,
out_grad,
axis,
x_grad,
y_grad,
funcs::FMaxGradDx<T>(),
funcs::FMaxGradDy<T>());
} else {
funcs::ElemwiseGradComputeWithBroadcast<T,
funcs::FMaxGradDx<T>,
funcs::FMaxGradDy<T>>(
dev_ctx,
x_dim,
y_dim,
x,
y,
out,
out_grad,
axis,
x_grad,
y_grad,
funcs::FMaxGradDx<T>(),
funcs::FMaxGradDy<T>());
}
}
template <typename T, typename Context>
void ElementwiseFMinGradKernel(const Context& dev_ctx,
const DenseTensor& x,
const DenseTensor& y,
const DenseTensor& out_grad,
DenseTensor* x_grad,
DenseTensor* y_grad) {
funcs::ElementwiseGradPreProcess(out_grad, x_grad);
auto out = out_grad; // Fake out, not used
auto x_dim = x.dims();
auto y_dim = y.dims();
int axis = -1;
if (x.dims() == y.dims()) {
funcs::ElemwiseGradComputeNoBroadcast<Context,
T,
funcs::FMinGradDx<T>,
funcs::FMinGradDy<T>>(
dev_ctx,
x_dim,
y_dim,
x,
y,
out,
out_grad,
axis,
x_grad,
y_grad,
funcs::FMinGradDx<T>(),
funcs::FMinGradDy<T>());
} else {
funcs::ElemwiseGradComputeWithBroadcast<T,
funcs::FMinGradDx<T>,
funcs::FMinGradDy<T>>(
dev_ctx,
x_dim,
y_dim,
x,
y,
out,
out_grad,
axis,
x_grad,
y_grad,
funcs::FMinGradDx<T>(),
funcs::FMinGradDy<T>());
}
}
template <typename T>
struct MulGradDX {
HOSTDEVICE T operator()(T x UNUSED, T y, T out UNUSED, T dout) const {
return dout * y;
}
};
// avoid [-Wint-in-bool-context] warning
template <>
struct MulGradDX<bool> {
HOSTDEVICE bool operator()(bool x UNUSED,
bool y,
bool out UNUSED,
bool dout) const {
return dout && y;
}
};
template <typename T>
struct MulGradDX<phi::dtype::complex<T>> {
HOSTDEVICE phi::dtype::complex<T> operator()(
phi::dtype::complex<T> x UNUSED,
phi::dtype::complex<T> y,
phi::dtype::complex<T> out UNUSED,
phi::dtype::complex<T> dout) const {
phi::dtype::complex<T> y_conj(y.real, -y.imag);
return dout * y_conj;
}
};
/*
******************************
Multiply Grad
******************************
*/
template <typename T>
struct MulGradDY {
HOSTDEVICE T operator()(T x, T y UNUSED, T out UNUSED, T dout) const {
return dout * x;
}
};
// avoid [-Wint-in-bool-context] warning
template <>
struct MulGradDY<bool> {
HOSTDEVICE bool operator()(bool x,
bool y UNUSED,
bool out UNUSED,
bool dout) const {
return dout && x;
}
};
template <typename T>
struct MulGradDY<phi::dtype::complex<T>> {
HOSTDEVICE phi::dtype::complex<T> operator()(
phi::dtype::complex<T> x,
phi::dtype::complex<T> y UNUSED,
phi::dtype::complex<T> out UNUSED,
phi::dtype::complex<T> dout) const {
phi::dtype::complex<T> x_conj(x.real, -x.imag);
return dout * x_conj;
}
};
template <typename T, typename Context>
void MultiplyDoubleGradKernel(const Context& dev_ctx,
const DenseTensor& x,
const DenseTensor& y,
const DenseTensor& dout,
const paddle::optional<DenseTensor>& ddx,
const paddle::optional<DenseTensor>& ddy,
int axis,
DenseTensor* dx,
DenseTensor* dy,
DenseTensor* ddout) {
if (ddout) dev_ctx.template Alloc<T>(ddout);
DenseTensor ddx_safe, ddy_safe;
funcs::GetDoubleGradSafeTensor<Context, T>(
dev_ctx, x, ddx.get_ptr(), &ddx_safe);
funcs::GetDoubleGradSafeTensor<Context, T>(
dev_ctx, y, ddy.get_ptr(), &ddy_safe);
// dx = dout * ddy
// dy = dout * ddx
// ddout = ddx * y + x * ddy
// change computation sequence to save memory, so ddout can inplace ddx and
// dx can be used as 'tmp' tensor
// (1) dx = x * ddy
// (2) dy = dout * ddx
// (3) ddout = ddx * y
// (4) ddout = ddout + dx
// (5) dx = dout * ddy
if (ddout) {
auto& place = *dev_ctx.eigen_device();
// size(ddout) > size(ddx) or we don't have ddx, ddout can't use memory of
// ddx using inplace
bool without_ddx = (ddx.get_ptr() == nullptr);
if (!without_ddx) {
without_ddx = (ddout->numel() > ddx.get_ptr()->numel());
}
if (without_ddx) {
phi::funcs::ElemwiseGradCompute<Context, T, MulGradDX<T>, MulGradDY<T>>(
dev_ctx,
ddx_safe,
ddy_safe,
dout,
dout,
axis,
dx,
dy,
MulGradDX<T>(),
MulGradDY<T>());
DenseTensor ddout_tmp;
ddout_tmp.Resize(ddout->dims());
dev_ctx.template Alloc<T>(&ddout_tmp);
funcs::DefaultElementwiseOperator<Context,
T,
funcs::MultiplyFunctor<T>,
funcs::InverseMultiplyFunctor<T>>(
dev_ctx, y, ddx_safe, ddout, axis);
funcs::DefaultElementwiseOperator<Context,
T,
funcs::MultiplyFunctor<T>,
funcs::InverseMultiplyFunctor<T>>(
dev_ctx, ddy_safe, x, &ddout_tmp, axis);
auto ddout_t = phi::EigenVector<T>::Flatten(*ddout);
auto ddout_tmp_t = phi::EigenVector<T>::Flatten(ddout_tmp);
ddout_t.device(place) = ddout_t + ddout_tmp_t;
} else {
// use dx to save memory, other than alloc tmp tensor
if (dx) {
DenseTensor* ddout_tmp = dx;
funcs::DefaultElementwiseOperator<Context,
T,
funcs::MultiplyFunctor<T>,
funcs::InverseMultiplyFunctor<T>>(
dev_ctx, x, ddy_safe, ddout_tmp, axis);
// NOTE: in the following ElemwiseGradCompute, for the
// first output tensor is nullptr, the branch to calculate first
// output tensor will not be activated, DivGradDx function will not
// be called and can be ignored, the first branch has little effect
// on running speed.
phi::funcs::ElemwiseGradCompute<Context, T, MulGradDX<T>, MulGradDY<T>>(
dev_ctx,
ddx_safe,
ddy_safe,
dout,
dout,
axis,
nullptr,
dy,
MulGradDX<T>(),
MulGradDY<T>());
funcs::DefaultElementwiseOperator<Context,
T,
funcs::MultiplyFunctor<T>,
funcs::InverseMultiplyFunctor<T>>(
dev_ctx, ddx_safe, y, ddout, axis);
auto ddout_t = phi::EigenVector<T>::Flatten(*ddout);
auto ddout_tmp_t = phi::EigenVector<T>::Flatten(*ddout_tmp);
ddout_t.device(place) = ddout_t + ddout_tmp_t;
funcs::DefaultElementwiseOperator<Context,
T,
funcs::MultiplyFunctor<T>,
funcs::InverseMultiplyFunctor<T>>(
dev_ctx, dout, ddy_safe, dx, axis);
} else if ((!dx) && dy) {
DenseTensor tmp_a(ddout->dtype());
tmp_a.Resize(ddout->dims());
dev_ctx.template Alloc<T>(&tmp_a);
funcs::DefaultElementwiseOperator<Context,
T,
funcs::MultiplyFunctor<T>,
funcs::InverseMultiplyFunctor<T>>(
dev_ctx, x, ddy_safe, &tmp_a, axis);
auto ddout_t1 = phi::EigenVector<T>::Flatten(tmp_a);
funcs::DefaultElementwiseOperator<Context,
T,
funcs::MultiplyFunctor<T>,
funcs::InverseMultiplyFunctor<T>>(
dev_ctx, ddx_safe, y, ddout, axis);
auto ddout_t2 = phi::EigenVector<T>::Flatten(*ddout);
ddout_t2.device(place) = ddout_t2 + ddout_t1;
// NOTE: in the following ElemwiseGradCompute, for the
// first output tensor is nullptr, the branch to calculate first
// output tensor will not be activated, DivGradDx function will not
// be called and can be ignored, the first branch has little effect
// on running speed.
phi::funcs::ElemwiseGradCompute<Context, T, MulGradDX<T>, MulGradDY<T>>(
dev_ctx,
ddx_safe,
ddy_safe,
dout,
dout,
axis,
nullptr,