-
Notifications
You must be signed in to change notification settings - Fork 74k
/
training_ops.cc
4670 lines (4218 loc) · 201 KB
/
training_ops.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 2016 The TensorFlow 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.
==============================================================================*/
#define EIGEN_USE_THREADS
// clang-format off
#include "tensorflow/core/lib/bfloat16/bfloat16.h"
// clang-format on
#include "tensorflow/core/kernels/training_ops.h"
#include <algorithm> // NOLINT
#include "tensorflow/core/framework/bounds_check.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/kernels/training_op_helpers.h"
#include "tensorflow/core/kernels/variable_ops.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/util/util.h"
#ifdef TENSORFLOW_USE_SYCL
#include "tensorflow/core/common_runtime/sycl/sycl_util.h"
#endif // TENSORFLOW_USE_SYCL
namespace tensorflow {
using CPUDevice = Eigen::ThreadPoolDevice;
using GPUDevice = Eigen::GpuDevice;
using SYCLDevice = Eigen::SyclDevice;
using Index = Eigen::Index;
namespace {
template <class T>
inline T sgn(const T x) {
T zero(0);
T one(1);
return (x == zero ? zero : (x < zero ? -one : one));
}
} // namespace
namespace functor {
template <typename T>
struct ApplyGradientDescent<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstFlat grad) {
var.device(d) -= grad * lr();
}
};
#ifdef TENSORFLOW_USE_SYCL
template <typename T>
struct ApplyGradientDescentSYCL {
void operator()(const SYCLDevice& d, typename TTypes<T>::Flat var, T lr,
typename TTypes<T>::ConstFlat grad) {
var.device(d) -= grad * lr;
}
};
#endif
template <typename T>
struct ApplyAdadelta<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::Flat accum,
typename TTypes<T>::Flat accum_update,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstScalar rho,
typename TTypes<T>::ConstScalar epsilon,
typename TTypes<T>::ConstFlat grad) {
accum.device(d) =
accum * rho() + grad.square() * (static_cast<T>(1) - rho());
const auto update =
(accum_update + epsilon()).sqrt() * (accum + epsilon()).rsqrt() * grad;
var.device(d) -= update * lr();
accum_update.device(d) =
accum_update * rho() + update.square() * (static_cast<T>(1) - rho());
}
};
template <typename T>
struct ApplyProximalGradientDescent<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstScalar l1,
typename TTypes<T>::ConstScalar l2,
typename TTypes<T>::ConstFlat grad) {
// Note that here is Fobos update, for details please refer:
// http://papers.nips.cc/paper/3793-efficient-learning-using-forward-backward-splitting.pdf
// TODO(xbing): merge the logic for ProximalGradientDescent and
// ProximalAdagrad.
auto prox_var = var;
// compute v = w - lr * grad.
prox_var.device(d) -= grad * lr();
if (l1() > 0) {
// compute sign(v) * max(|v| - lr * l1, 0)
var.device(d) =
prox_var.sign() *
(prox_var.abs() - var.constant(lr() * l1())).cwiseMax(T(0.0)) /
(var.constant(1.0) + var.constant(l2() * lr()));
} else {
var.device(d) =
prox_var / (var.constant(1.0) + var.constant(l2() * lr()));
}
}
};
template <typename T>
struct ApplyAdagradDA<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::Flat gradient_accum,
typename TTypes<T>::Flat gradient_squared_accum,
typename TTypes<T>::ConstScalar lr, int64 global_step,
typename TTypes<T>::ConstScalar l1,
typename TTypes<T>::ConstScalar l2,
typename TTypes<T>::ConstFlat grad) {
// Accumulate gradient, and gradient_squared
gradient_accum.device(d) += grad;
gradient_squared_accum.device(d) += grad.square();
// AdagradDA update:
// Let g to be gradient accumulator, gg to be gradient squared accumulator,
// T be the global step, lr is the learning rate, and k the initial
// gradient squared accumulator value.
// w = \dfrac{sign(-g)*lr*|g - l1*T|_{+}}{l2*T*lr + \sqrt{k+gg})}
if (l1() > 0) {
var.device(d) =
lr() * var.constant(-1.0) * gradient_accum.sign() *
(gradient_accum.abs() -
var.constant(static_cast<float>(global_step)) * var.constant(l1()))
.cwiseMax(T(0.0)) /
(var.constant(l2()) *
var.constant(static_cast<float>(global_step) * lr()) +
gradient_squared_accum.sqrt());
} else {
var.device(d) =
lr() * gradient_accum * var.constant(-1.0) /
(var.constant(l2()) *
var.constant(static_cast<float>(global_step) * lr()) +
gradient_squared_accum.sqrt());
}
}
};
template <typename T>
struct ApplyAdagrad<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::Flat accum,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstFlat grad, bool update_slots) {
if (update_slots) {
accum.device(d) += grad.square();
}
var.device(d) -= grad * lr() * accum.rsqrt();
}
};
template <typename T>
struct ApplyAdagradV2<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::Flat accum,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstScalar epsilon,
typename TTypes<T>::ConstFlat grad, bool update_slots) {
if (update_slots) {
accum.device(d) += grad.square();
}
var.device(d) -= grad * lr() / (accum.sqrt() + epsilon());
}
};
template <typename T>
struct ApplyProximalAdagrad<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::Flat accum,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstScalar l1,
typename TTypes<T>::ConstScalar l2,
typename TTypes<T>::ConstFlat grad) {
// Fobos update per paper with Adagrad learning rate.
accum.device(d) += grad.square();
// Adagrad learning rate.
auto learning_rate = accum.constant(lr()) * accum.rsqrt();
auto prox_var = var;
// compute v = w - lr * grad.
prox_var.device(d) -= grad * learning_rate;
if (l1() > 0) {
// compute sign(v) * max(|v| - lr * l1, 0)
var.device(d) = prox_var.sign() *
(prox_var.abs() - learning_rate * prox_var.constant(l1()))
.cwiseMax(T(0.0)) /
(var.constant(1.0) + var.constant(l2()) * learning_rate);
} else {
var.device(d) =
prox_var / (var.constant(1.0) + var.constant(l2()) * learning_rate);
}
}
};
template <typename T>
struct ApplyFtrlV2<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::Flat accum,
typename TTypes<T>::Flat linear,
typename TTypes<T>::ConstFlat grad,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstScalar l1,
typename TTypes<T>::ConstScalar l2,
typename TTypes<T>::ConstScalar l2_shrinkage,
typename TTypes<T>::ConstScalar lr_power) {
auto grad_with_shrinkage = grad + static_cast<T>(2) * l2_shrinkage() * var;
auto new_accum = accum + grad * grad;
// special case for which lr_power=-0.5.
if (lr_power() == static_cast<T>(-0.5)) {
linear.device(d) +=
grad_with_shrinkage - (new_accum.sqrt() - accum.sqrt()) / lr() * var;
} else {
linear.device(d) +=
grad_with_shrinkage -
(new_accum.pow(-lr_power()) - accum.pow(-lr_power())) / lr() * var;
}
auto x = (linear.constant(l1()) * linear.sign() - linear);
if (lr_power() == static_cast<T>(-0.5)) {
auto y = new_accum.sqrt() / new_accum.constant(lr()) +
linear.constant(static_cast<T>(2) * l2());
auto pre_shrink = x / y;
var.device(d) = (linear.abs() > linear.constant(l1()))
.select(pre_shrink, var.constant(static_cast<T>(0)));
} else {
auto y = new_accum.pow(-lr_power()) / new_accum.constant(lr()) +
linear.constant(static_cast<T>(2) * l2());
auto pre_shrink = x / y;
var.device(d) = (linear.abs() > linear.constant(l1()))
.select(pre_shrink, var.constant(static_cast<T>(0)));
}
accum.device(d) += grad * grad;
}
};
template <typename T>
struct ApplyFtrl<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::Flat accum,
typename TTypes<T>::Flat linear,
typename TTypes<T>::ConstFlat grad,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstScalar l1,
typename TTypes<T>::ConstScalar l2,
typename TTypes<T>::ConstScalar lr_power) {
auto new_accum = accum + grad.square();
// special case for which lr_power=-0.5.
if (lr_power() == static_cast<T>(-0.5)) {
linear.device(d) += grad - (new_accum.sqrt() - accum.sqrt()) / lr() * var;
} else {
linear.device(d) +=
grad -
(new_accum.pow(-lr_power()) - accum.pow(-lr_power())) / lr() * var;
}
auto x = (linear.constant(l1()) * linear.sign() - linear);
if (lr_power() == static_cast<T>(-0.5)) {
auto y = new_accum.sqrt() / new_accum.constant(lr()) +
linear.constant(static_cast<T>(2) * l2());
auto pre_shrink = x / y;
var.device(d) = (linear.abs() > linear.constant(l1()))
.select(pre_shrink, var.constant(static_cast<T>(0)));
} else {
auto y = new_accum.pow(-lr_power()) / new_accum.constant(lr()) +
linear.constant(static_cast<T>(2) * l2());
auto pre_shrink = x / y;
var.device(d) = (linear.abs() > linear.constant(l1()))
.select(pre_shrink, var.constant(static_cast<T>(0)));
}
accum.device(d) += grad.square();
}
};
template <typename T>
struct ApplyMomentum<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::Flat accum,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstFlat grad,
typename TTypes<T>::ConstScalar momentum, bool use_nesterov) {
accum.device(d) = accum * momentum() + grad;
if (use_nesterov) {
var.device(d) -= grad * lr() + accum * momentum() * lr();
} else {
var.device(d) -= accum * lr();
}
}
};
template <typename T>
struct ApplyKerasMomentum<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::Flat accum,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstFlat grad,
typename TTypes<T>::ConstScalar momentum, bool use_nesterov) {
accum.device(d) = accum * momentum() - grad * lr();
if (use_nesterov) {
var.device(d) += (accum * momentum() - grad * lr());
} else {
var.device(d) += accum;
}
}
};
template <typename T, typename Tindex>
struct SparseApplyKerasMomentum<CPUDevice, T, Tindex> {
Tindex operator()(const CPUDevice& d, typename TTypes<T>::Matrix var,
typename TTypes<T>::Matrix accum,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstMatrix grad,
typename TTypes<Tindex>::ConstFlat indices,
typename TTypes<T>::ConstScalar momentum,
bool use_nesterov) {
const Tindex N = static_cast<Tindex>(indices.size());
const Tindex first_dim_size = static_cast<Tindex>(var.dimension(0));
for (Tindex i = 0; i < N; i++) {
const Tindex index = internal::SubtleMustCopy(indices(i));
if (!FastBoundsCheck(index, first_dim_size)) return i;
auto a = accum.template chip<0>(index);
auto g = grad.template chip<0>(i);
auto v = var.template chip<0>(index);
a = a * a.constant(momentum()) - g * g.constant(lr());
if (use_nesterov) {
v += a * a.constant(momentum()) - g * g.constant(lr());
} else {
v += a;
}
}
return -1;
}
};
template <typename Device, typename T>
struct ApplyAdamNonCuda {
void operator()(const Device& d, typename TTypes<T>::Flat var,
typename TTypes<T>::Flat m, typename TTypes<T>::Flat v,
typename TTypes<T>::ConstScalar beta1_power,
typename TTypes<T>::ConstScalar beta2_power,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstScalar beta1,
typename TTypes<T>::ConstScalar beta2,
typename TTypes<T>::ConstScalar epsilon,
typename TTypes<T>::ConstFlat grad, bool use_nesterov) {
// Get params length and check if they can be vectorized by packet size.
Index length = var.size();
Index packet_size = Eigen::internal::packet_traits<T>::size;
if (length % packet_size == 0) {
length = length / packet_size;
} else {
packet_size = 1;
}
T* var_ptr = var.data();
T* m_ptr = m.data();
T* v_ptr = v.data();
const T* g_ptr = grad.data();
const T alpha = lr() * Eigen::numext::sqrt(T(1) - beta2_power()) /
(T(1) - beta1_power());
// beta1 == μ
// beta2 == ν
// v == n
// var == θ
auto shard = [this, var_ptr, m_ptr, v_ptr, g_ptr, alpha, beta1, beta2,
epsilon, use_nesterov, packet_size](int begin, int end) {
int t_size = (end - begin) * packet_size;
begin = begin * packet_size;
auto var = typename TTypes<T>::UnalignedTensor(var_ptr + begin, t_size);
auto m = typename TTypes<T>::UnalignedTensor(m_ptr + begin, t_size);
auto v = typename TTypes<T>::UnalignedTensor(v_ptr + begin, t_size);
auto g = typename TTypes<T>::UnalignedConstTensor(g_ptr + begin, t_size);
if (use_nesterov) {
m += (g - m) * (T(1) - beta1());
v += (g.square() - v) * (T(1) - beta2());
var -= ((g * (T(1) - beta1()) + beta1() * m) * alpha) /
(v.sqrt() + epsilon());
} else {
m += (g - m) * (T(1) - beta1());
v += (g.square() - v) * (T(1) - beta2());
var -= (m * alpha) / (v.sqrt() + epsilon());
}
};
// Input data: var, v, m, grad.
// Output data: var, v, m.
const int input_bytes = length * packet_size * sizeof(T) * 4;
const int output_bytes = length * packet_size * sizeof(T) * 3;
const int compute_cycles =
// Consider Sub as Add
(Eigen::TensorOpCost::AddCost<int>() * 5 +
Eigen::TensorOpCost::MulCost<int>() * 2 +
Eigen::TensorOpCost::AddCost<T>() * 10 +
Eigen::TensorOpCost::MulCost<T>() * 6 +
Eigen::TensorOpCost::DivCost<T>()) *
length;
const Eigen::TensorOpCost cost(input_bytes, output_bytes, compute_cycles);
// Eigen device must update 3 variables with 3 different expressions,
// which is bad for cache locality on CPU. Here use ParallelFor instead of
// "regular" tensor expressions to get better performance.
d.parallelFor(length, cost, shard);
}
};
#ifdef TENSORFLOW_USE_SYCL
template <typename T>
struct ApplyAdamSYCL {
void operator()(const SYCLDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::Flat m, typename TTypes<T>::Flat v,
T beta1_power, T beta2_power, T lr, T beta1, T beta2,
T epsilon, typename TTypes<T>::ConstFlat grad) {
const T alpha =
lr * Eigen::numext::sqrt(T(1) - beta2_power) / (T(1) - beta1_power);
m.device(d) += (grad - m) * (T(1) - beta1);
v.device(d) += (grad.square() - v) * (T(1) - beta2);
var.device(d) -= (m * alpha) / (v.sqrt() + epsilon);
}
};
#endif // TENSORFLOW_USE_SYCL
template <typename T>
struct ApplyAdam<CPUDevice, T> : ApplyAdamNonCuda<CPUDevice, T> {};
template <typename T>
struct ApplyAdamWithAmsgrad<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::Flat m, typename TTypes<T>::Flat v,
typename TTypes<T>::Flat vhat,
typename TTypes<T>::ConstScalar beta1_power,
typename TTypes<T>::ConstScalar beta2_power,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstScalar beta1,
typename TTypes<T>::ConstScalar beta2,
typename TTypes<T>::ConstScalar epsilon,
typename TTypes<T>::ConstFlat grad) {
const T alpha = lr() * Eigen::numext::sqrt(T(1) - beta2_power()) /
(T(1) - beta1_power());
m.device(d) += (grad - m) * (T(1) - beta1());
v.device(d) += (grad.square() - v) * (T(1) - beta2());
vhat.device(d) = vhat.cwiseMax(v);
var.device(d) -= (m * alpha) / (vhat.sqrt() + epsilon());
}
};
template <typename Device, typename T>
struct ApplyAdaMaxNonCuda {
void operator()(const Device& d, typename TTypes<T>::Flat var,
typename TTypes<T>::Flat m, typename TTypes<T>::Flat v,
typename TTypes<T>::ConstScalar beta1_power,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstScalar beta1,
typename TTypes<T>::ConstScalar beta2,
typename TTypes<T>::ConstScalar epsilon,
typename TTypes<T>::ConstFlat grad) {
m.device(d) += (grad - m) * (T(1) - beta1());
// Here v is u in section 7.1
v.device(d) = (beta2() * v).cwiseMax(grad.abs());
// var is θ in section 7.1
var.device(d) -= lr() / (T(1) - beta1_power()) * (m / (v + epsilon()));
}
};
template <typename T>
struct ApplyAdaMax<CPUDevice, T> : ApplyAdaMaxNonCuda<CPUDevice, T> {};
template <typename T>
struct ApplyRMSProp<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::Flat ms, typename TTypes<T>::Flat mom,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstScalar rho,
typename TTypes<T>::ConstScalar momentum,
typename TTypes<T>::ConstScalar epsilon,
typename TTypes<T>::ConstFlat grad) {
ms.device(d) += (grad.square() - ms) * (static_cast<T>(1) - rho());
mom.device(d) =
mom * momentum() + (grad * lr()) / ((ms + epsilon()).sqrt());
var.device(d) -= mom;
}
};
template <typename T>
struct ApplyCenteredRMSProp<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::Flat mg, typename TTypes<T>::Flat ms,
typename TTypes<T>::Flat mom,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstScalar rho,
typename TTypes<T>::ConstScalar momentum,
typename TTypes<T>::ConstScalar epsilon,
typename TTypes<T>::ConstFlat grad) {
ms.device(d) += (grad.square() - ms) * (static_cast<T>(1) - rho());
mg.device(d) += (grad - mg) * (static_cast<T>(1) - rho());
auto denom = (ms - mg.square()) + epsilon();
mom.device(d) = mom * momentum() + (grad * lr()) / denom.sqrt();
var.device(d) -= mom;
}
};
template <typename T>
struct ApplyAddSign<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::Flat m,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstScalar alpha,
typename TTypes<T>::ConstScalar sign_decay,
typename TTypes<T>::ConstScalar beta,
typename TTypes<T>::ConstFlat grad) {
m.device(d) = m * beta() + grad * (static_cast<T>(1) - beta());
auto sign_gm = grad.sign() * m.sign();
var.device(d) -= lr() * (alpha() + sign_decay() * sign_gm) * grad;
}
};
template <typename T>
struct ApplyPowerSign<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat var,
typename TTypes<T>::Flat m,
typename TTypes<T>::ConstScalar lr,
typename TTypes<T>::ConstScalar logbase,
typename TTypes<T>::ConstScalar sign_decay,
typename TTypes<T>::ConstScalar beta,
typename TTypes<T>::ConstFlat grad) {
m.device(d) = m * beta() + grad * (static_cast<T>(1) - beta());
auto sign_gm = grad.sign() * m.sign();
auto grad_scale = (logbase() * sign_decay() * sign_gm).exp();
var.device(d) -= lr() * grad_scale * grad;
}
};
} // namespace functor
template <typename Device, typename T>
class ApplyGradientDescentOp : public OpKernel {
public:
explicit ApplyGradientDescentOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("use_locking", &use_exclusive_lock_));
}
void Compute(OpKernelContext* ctx) override {
const bool sparse = false;
auto locks = MaybeLockVariableInputMutexesInOrder<Device, T>(
ctx, use_exclusive_lock_, sparse, {0});
Tensor var;
OP_REQUIRES_OK(ctx, GetInputTensorFromVariable<Device, T>(
ctx, 0, use_exclusive_lock_, sparse, &var));
OP_REQUIRES(
ctx, var.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", requested_input(0)));
const Tensor& alpha = ctx->input(1);
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(alpha.shape()),
errors::InvalidArgument("alpha is not a scalar: ",
alpha.shape().DebugString()));
const Tensor& delta = ctx->input(2);
OP_REQUIRES(
ctx, var.shape().IsSameSize(delta.shape()),
errors::InvalidArgument("var and delta do not have the same shape",
var.shape().DebugString(), " ",
delta.shape().DebugString()));
const Device& device = ctx->template eigen_device<Device>();
functor::ApplyGradientDescent<Device, T>()(
device, var.flat<T>(), alpha.scalar<T>(), delta.flat<T>());
MaybeForwardRefInputToRefOutput(ctx, 0, 0);
}
private:
bool use_exclusive_lock_;
};
#ifdef TENSORFLOW_USE_SYCL
template <typename T>
class ApplyGradientDescentOp<SYCLDevice, T> : public OpKernel {
public:
explicit ApplyGradientDescentOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("use_locking", &use_exclusive_lock_));
}
void Compute(OpKernelContext* ctx) override {
const bool sparse = false;
auto locks = MaybeLockVariableInputMutexesInOrder<SYCLDevice, T>(
ctx, use_exclusive_lock_, sparse, {0});
Tensor var;
OP_REQUIRES_OK(ctx, GetInputTensorFromVariable<SYCLDevice, T>(
ctx, 0, use_exclusive_lock_, sparse, &var));
OP_REQUIRES(
ctx, var.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", requested_input(0)));
const Tensor& alpha_dev = ctx->input(1);
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(alpha_dev.shape()),
errors::InvalidArgument("alpha is not a scalar: ",
alpha_dev.shape().DebugString()));
const Tensor& delta = ctx->input(2);
OP_REQUIRES(
ctx, var.shape().IsSameSize(delta.shape()),
errors::InvalidArgument("var and delta do not have the same shape",
var.shape().DebugString(), " ",
delta.shape().DebugString()));
auto device = ctx->eigen_sycl_device();
auto size = sizeof(T);
T alpha = T(0);
auto src_ptr = GetBase(&alpha_dev);
device.memcpyDeviceToHost(&alpha, static_cast<const T*>(src_ptr), size);
functor::ApplyGradientDescentSYCL<T>()(device, var.flat<T>(), alpha,
delta.flat<T>());
MaybeForwardRefInputToRefOutput(ctx, 0, 0);
}
private:
bool use_exclusive_lock_;
};
#endif // TENSORFLOW_USE_SYCL
#define REGISTER_KERNELS(D, T) \
REGISTER_KERNEL_BUILDER( \
Name("ApplyGradientDescent").Device(DEVICE_##D).TypeConstraint<T>("T"), \
ApplyGradientDescentOp<D##Device, T>); \
REGISTER_KERNEL_BUILDER(Name("ResourceApplyGradientDescent") \
.Device(DEVICE_##D) \
.HostMemory("var") \
.TypeConstraint<T>("T"), \
ApplyGradientDescentOp<D##Device, T>);
#define REGISTER_CPU_KERNELS(T) REGISTER_KERNELS(CPU, T);
TF_CALL_half(REGISTER_CPU_KERNELS);
TF_CALL_bfloat16(REGISTER_CPU_KERNELS);
TF_CALL_float(REGISTER_CPU_KERNELS);
TF_CALL_double(REGISTER_CPU_KERNELS);
TF_CALL_complex64(REGISTER_CPU_KERNELS);
TF_CALL_complex128(REGISTER_CPU_KERNELS);
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
// Forward declarations of the functor specializations for GPU.
namespace functor {
#define DECLARE_GPU_SPEC(T) \
template <> \
void ApplyGradientDescent<GPUDevice, T>::operator()( \
const GPUDevice& d, typename TTypes<T>::Flat var, \
typename TTypes<T>::ConstScalar alpha, \
typename TTypes<T>::ConstFlat delta); \
extern template struct ApplyGradientDescent<GPUDevice, T>;
DECLARE_GPU_SPEC(Eigen::half);
DECLARE_GPU_SPEC(float);
DECLARE_GPU_SPEC(double);
#if !defined(TENSORFLOW_USE_NVCC) && \
!defined(TENSORFLOW_USE_ROCM) // TODO(b/143684500): Eigen to support
// complex sqrt
DECLARE_GPU_SPEC(complex64);
DECLARE_GPU_SPEC(complex128);
#endif
#undef DECLARE_GPU_SPEC
} // namespace functor
REGISTER_KERNELS(GPU, Eigen::half);
REGISTER_KERNELS(GPU, float);
REGISTER_KERNELS(GPU, double);
#if !defined(TENSORFLOW_USE_NVCC) && \
!defined(TENSORFLOW_USE_ROCM) // TODO(b/143684500): Eigen to support
// complex sqrt
REGISTER_KERNELS(GPU, complex64);
REGISTER_KERNELS(GPU, complex128);
#endif
#endif
#ifdef TENSORFLOW_USE_SYCL
#define REGISTER_SYCL_KERNELS(T) REGISTER_KERNELS(SYCL, T);
TF_CALL_float(REGISTER_SYCL_KERNELS);
TF_CALL_double(REGISTER_SYCL_KERNELS);
#undef REGISTER_SYCL_KERNELS
#endif // TENSORFLOW_USE_SYCL
#undef REGISTER_CPU_KERNELS
#undef REGISTER_KERNELS
template <typename Device, typename T>
class ApplyAdadeltaOp : public OpKernel {
public:
explicit ApplyAdadeltaOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("use_locking", &use_exclusive_lock_));
}
void Compute(OpKernelContext* ctx) override {
Var* resource;
const bool sparse = false;
mutex* mu = GetTrainingVariableMutex<Device, T>(ctx, 0, sparse, &resource);
core::ScopedUnref scoped_unref(resource);
if (use_exclusive_lock_ && mu != nullptr) {
mutex_lock l1(*mu);
// Don't try to acquire a lock on the second ref as they share the same
// mutex.
//
// mutex_lock l2(*ctx->input_ref_mutex(1));
DoValidate(ctx);
if (!ctx->status().ok()) return;
DoCompute(ctx);
} else {
DoValidate(ctx);
if (!ctx->status().ok()) return;
DoCompute(ctx);
}
MaybeForwardRefInputToRefOutput(ctx, 0, 0);
}
private:
bool use_exclusive_lock_;
void DoValidate(OpKernelContext* ctx) {
Tensor var;
const bool sparse = false;
OP_REQUIRES_OK(ctx, GetInputTensorFromVariable<Device, T>(
ctx, 0, use_exclusive_lock_, sparse, &var));
Tensor accum;
OP_REQUIRES_OK(ctx, GetInputTensorFromVariable<Device, T>(
ctx, 1, use_exclusive_lock_, sparse, &accum));
Tensor accum_update;
OP_REQUIRES_OK(
ctx, GetInputTensorFromVariable<Device, T>(ctx, 2, use_exclusive_lock_,
sparse, &accum_update));
OP_REQUIRES(
ctx, var.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", requested_input(0)));
OP_REQUIRES(
ctx, accum.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", requested_input(1)));
OP_REQUIRES(
ctx, accum_update.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", requested_input(2)));
const Tensor& lr = ctx->input(3);
const Tensor& rho = ctx->input(4);
const Tensor& epsilon = ctx->input(5);
const Tensor& grad = ctx->input(6);
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr.shape()),
errors::InvalidArgument("lr is not a scalar: ",
lr.shape().DebugString()));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(rho.shape()),
errors::InvalidArgument("rho is not a scalar: ",
rho.shape().DebugString()));
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(epsilon.shape()),
errors::InvalidArgument("epsilon is not a scalar: ",
epsilon.shape().DebugString()));
OP_REQUIRES(
ctx, var.shape().IsSameSize(accum.shape()),
errors::InvalidArgument("var and accum do not have the same shape",
var.shape().DebugString(), " ",
accum.shape().DebugString()));
OP_REQUIRES(
ctx, var.shape().IsSameSize(grad.shape()),
errors::InvalidArgument("var and grad do not have the same shape",
var.shape().DebugString(), " ",
grad.shape().DebugString()));
}
void DoCompute(OpKernelContext* ctx) {
const Device& device = ctx->template eigen_device<Device>();
Tensor var;
const bool sparse = false;
OP_REQUIRES_OK(ctx, GetInputTensorFromVariable<Device, T>(
ctx, 0, use_exclusive_lock_, sparse, &var));
Tensor accum;
OP_REQUIRES_OK(ctx, GetInputTensorFromVariable<Device, T>(
ctx, 1, use_exclusive_lock_, sparse, &accum));
Tensor accum_update;
OP_REQUIRES_OK(
ctx, GetInputTensorFromVariable<Device, T>(ctx, 2, use_exclusive_lock_,
sparse, &accum_update));
const Tensor& lr = ctx->input(3);
const Tensor& rho = ctx->input(4);
const Tensor& epsilon = ctx->input(5);
const Tensor& grad = ctx->input(6);
functor::ApplyAdadelta<Device, T>()(
device, var.flat<T>(), accum.flat<T>(), accum_update.flat<T>(),
lr.scalar<T>(), rho.scalar<T>(), epsilon.scalar<T>(), grad.flat<T>());
}
};
#define REGISTER_KERNELS(D, T) \
REGISTER_KERNEL_BUILDER( \
Name("ApplyAdadelta").Device(DEVICE_##D).TypeConstraint<T>("T"), \
ApplyAdadeltaOp<D##Device, T>); \
REGISTER_KERNEL_BUILDER(Name("ResourceApplyAdadelta") \
.Device(DEVICE_##D) \
.HostMemory("var") \
.HostMemory("accum") \
.HostMemory("accum_update") \
.TypeConstraint<T>("T"), \
ApplyAdadeltaOp<D##Device, T>);
#define REGISTER_CPU_KERNELS(T) REGISTER_KERNELS(CPU, T);
TF_CALL_half(REGISTER_CPU_KERNELS);
TF_CALL_bfloat16(REGISTER_CPU_KERNELS);
TF_CALL_float(REGISTER_CPU_KERNELS);
TF_CALL_double(REGISTER_CPU_KERNELS);
TF_CALL_complex64(REGISTER_CPU_KERNELS);
TF_CALL_complex128(REGISTER_CPU_KERNELS);
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
// Forward declarations of the functor specializations for GPU.
namespace functor {
#define DECLARE_GPU_SPEC(T) \
template <> \
void ApplyAdadelta<GPUDevice, T>::operator()( \
const GPUDevice& d, typename TTypes<T>::Flat var, \
typename TTypes<T>::Flat accum, typename TTypes<T>::Flat accum_update, \
typename TTypes<T>::ConstScalar lr, typename TTypes<T>::ConstScalar rho, \
typename TTypes<T>::ConstScalar epsilon, \
typename TTypes<T>::ConstFlat grad); \
extern template struct ApplyAdadelta<GPUDevice, T>;
DECLARE_GPU_SPEC(Eigen::half);
DECLARE_GPU_SPEC(float);
DECLARE_GPU_SPEC(double);
#if !defined(TENSORFLOW_USE_NVCC) && \
!defined(TENSORFLOW_USE_ROCM) // TODO(b/143684500): Eigen to support
// complex sqrt
DECLARE_GPU_SPEC(complex64);
DECLARE_GPU_SPEC(complex128);
#endif
#undef DECLARE_GPU_SPEC
} // namespace functor
REGISTER_KERNELS(GPU, Eigen::half);
REGISTER_KERNELS(GPU, float);
REGISTER_KERNELS(GPU, double);
#if !defined(TENSORFLOW_USE_NVCC) && \
!defined(TENSORFLOW_USE_ROCM) // TODO(b/143684500): Eigen to support
// complex sqrt
REGISTER_KERNELS(GPU, complex64);
REGISTER_KERNELS(GPU, complex128);
#endif
#endif
#undef REGISTER_CPU_KERNELS
#undef REGISTER_KERNELS
// Note, this op works on cpu only.
template <typename T, typename Tindex>
class SparseApplyAdadeltaOp : public OpKernel {
public:
explicit SparseApplyAdadeltaOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("use_locking", &use_exclusive_lock_));
}
void Compute(OpKernelContext* ctx) override {
Var* var;
const bool sparse = true;
mutex* mu = GetTrainingVariableMutex<CPUDevice, T>(ctx, 0, sparse, &var);
core::ScopedUnref scoped_unref(var);
// mu_accum is actually the same mutex as mu_var since currently we use a
// global mutex.
//
// mutex* mu_accum = ctx->input_ref_mutex(1);
if (use_exclusive_lock_ && mu != nullptr) {
mutex_lock ml(*mu);
DoCompute(ctx);
} else {
DoCompute(ctx);
}
}
void DoCompute(OpKernelContext* ctx) {
Tensor var;
const bool sparse = true;
OP_REQUIRES_OK(ctx, GetInputTensorFromVariable<CPUDevice, T>(
ctx, 0, use_exclusive_lock_, sparse, &var));
Tensor accum_grad;
OP_REQUIRES_OK(ctx, GetInputTensorFromVariable<CPUDevice, T>(
ctx, 1, use_exclusive_lock_, sparse, &accum_grad));
Tensor accum_update;
OP_REQUIRES_OK(ctx,
GetInputTensorFromVariable<CPUDevice, T>(
ctx, 2, use_exclusive_lock_, sparse, &accum_update));
OP_REQUIRES(
ctx, var.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", requested_input(0)));
OP_REQUIRES(
ctx, accum_grad.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", requested_input(1)));
OP_REQUIRES(
ctx, accum_update.IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", requested_input(2)));
OP_REQUIRES(
ctx, var.shape().IsSameSize(accum_grad.shape()),
errors::InvalidArgument("var and accum_grad do not have the same shape",
var.shape().DebugString(), " ",
accum_grad.shape().DebugString()));
OP_REQUIRES(ctx, var.shape().IsSameSize(accum_update.shape()),
errors::InvalidArgument(
"var and accum_update do not have the same shape",
var.shape().DebugString(), " ",
accum_update.shape().DebugString()));
OP_REQUIRES(ctx, TensorShapeUtils::IsVectorOrHigher(var.shape()),
errors::InvalidArgument("var must be at least 1 dimensional"));
const Tensor& lr = ctx->input(3);
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr.shape()),
errors::InvalidArgument("lr is not a scalar: ",
lr.shape().DebugString()));
const Tensor& rho = ctx->input(4);
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(rho.shape()),
errors::InvalidArgument("rho is not a scalar: ",
rho.shape().DebugString()));
const Tensor& epsilon = ctx->input(5);
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(epsilon.shape()),
errors::InvalidArgument("epsilon is not a scalar: ",
epsilon.shape().DebugString()));
const Tensor& grad = ctx->input(6);
const Tensor& indices = ctx->input(7);
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(indices.shape()),
errors::InvalidArgument("indices must be one-dimensional"));
for (int d = 1; d < var.dims(); d++) {
OP_REQUIRES(ctx, var.dim_size(d) == grad.dim_size(d),
errors::InvalidArgument(strings::StrCat(
"var and grad must match in dimension ", d)));
}
const Tindex N = indices.dim_size(0);
OP_REQUIRES(
ctx, grad.dim_size(0) == N,
errors::InvalidArgument(
"grad must be the same size as indices in the first dimension."));
if (N > 0) {
const Tindex first_dim_size = var.dim_size(0);
// Validate all the indices are in range
auto indices_vec = indices.vec<Tindex>();
for (Tindex i = 0; i < N; i++) {
const Tindex index = indices_vec(i);
OP_REQUIRES(ctx, index >= 0 && index < first_dim_size,
errors::InvalidArgument(
strings::StrCat("Index ", index, " at offset ", i,
" in indices is out of range")));
}
auto var_flat = var.flat_outer_dims<T>();
auto accum_grad_flat = accum_grad.flat_outer_dims<T>();
auto accum_update_flat = accum_update.flat_outer_dims<T>();
auto grad_flat = grad.flat_outer_dims<T>();
const T lr_scalar = lr.scalar<T>()();
const T rho_scalar = rho.scalar<T>()();
const T epsilon_scalar = epsilon.scalar<T>()();
for (Tindex i = 0; i < N; i++) {
const Tindex index = indices_vec(i);
auto accum_ = accum_grad_flat.template chip<0>(index);
auto accum_update_ = accum_update_flat.template chip<0>(index);
auto grad_ = grad_flat.template chip<0>(i);
accum_ = accum_ * accum_.constant(rho_scalar) +
grad_.square() * grad_.constant(T(1) - rho_scalar);
const auto update =
(accum_update_ + accum_update_.constant(epsilon_scalar)).sqrt() *
(accum_ + accum_.constant(epsilon_scalar)).rsqrt() * grad_;
auto v = var_flat.template chip<0>(index);
v -= update * update.constant(lr_scalar);
accum_update_ =
accum_update_ * accum_update_.constant(rho_scalar) +
update.square() * update.constant(static_cast<T>(1) - rho_scalar);
}
}
MaybeForwardRefInputToRefOutput(ctx, 0, 0);
}