-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdyana_operations.hpp
1478 lines (1314 loc) · 49.5 KB
/
dyana_operations.hpp
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
//
// Created by YAN Yuchen on 11/13/2018.
//
#ifndef DYANA_OPERATIONS_HPP
#define DYANA_OPERATIONS_HPP
#include <dynet/dynet.h>
#include <dynet/expr.h>
#include "dyana_common.hpp"
namespace dyana {
/**
* \ingroup normoperations
* \brief Weight normalization
* \details Performs weight normalization :
*
* \f$
* \begin{split}
* \hat{w} &= g\frac{w}{\Vert w\Vert}\\
* \end{split}
* \f$
*
* Reference : [Salimans, Kingma 2016](https://arxiv.org/abs/1602.07868)
*
* \param w Input expression (weight parameter)
* \param g Gain (scalar expression, usually also a parameter)
* \return An expression of the same dimension as `w`
*/
inline tensor weight_norm(const tensor &w, const tensor &g) { return dynet::weight_norm(w, g); }
inline tensor operator+(const tensor &x, const tensor &y) { return dynet::operator+(x, y); }
inline tensor operator+(const tensor &x, float y) { return dynet::operator+(x, y); }
inline tensor operator+(const tensor &x, double y) { return dynet::operator+(x, (float)y); }
inline tensor operator+(const float x, const tensor &y) { return dynet::operator+(x, y); }
inline tensor operator+(const double x, const tensor &y) { return dynet::operator+((double)x, y); }
inline tensor operator+(const tensor &x, const parameter &y) { return x + dyana::tensor(y); }
inline tensor operator+(const parameter &x, const tensor &y) { return dyana::tensor(x) + y; }
inline tensor operator-(const tensor &x, const tensor &y) { return dynet::operator-(x, y); }
inline tensor operator-(const tensor &x, float y) { return dynet::operator-(x, y); }
inline tensor operator-(const tensor &x, double y) { return dynet::operator-(x, (float)y); }
inline tensor operator-(float x, const tensor &y) { return dynet::operator-(x, y); }
inline tensor operator-(double x, const tensor &y) { return dynet::operator-((float)x, y); }
inline tensor operator-(const tensor &x) { return dynet::operator-(x); }
inline tensor operator-(const tensor &x, const parameter &y) { return x - dyana::tensor(y); }
inline tensor operator-(const parameter &x, const tensor &y) { return dyana::tensor(x) - y; }
inline tensor operator*(const tensor &x, const tensor &y) { return dynet::operator*(x, y); }
inline tensor operator*(const tensor &x, float y) { return dynet::operator*(x, y); }
inline tensor operator*(const tensor &x, double y) { return dynet::operator*(x, (float)y); }
inline tensor operator*(float x, const tensor &y) { return dynet::operator*(x, y); }
inline tensor operator*(double x, const tensor &y) { return dynet::operator*((float)x, y); }
inline tensor operator*(const tensor &x, const parameter &y) { return x * dyana::tensor(y); }
inline tensor operator*(const parameter &x, const tensor &y) { return dyana::tensor(x) * y; }
inline tensor operator/(const tensor &x, const tensor& y) { return dynet::operator/(x, y); }
inline tensor operator/(const tensor &x, float y) { return dynet::operator/(x, y); }
inline tensor operator/(const tensor &x, double y) { return dynet::operator/(x, (float)y); }
inline tensor operator/(const parameter &x, float y) { return dyana::tensor(x) / y; }
inline tensor operator/(const parameter &x, double y) { return dyana::tensor(x) / (float)y; }
inline tensor operator/(const tensor &x, const parameter &y) { return x / dyana::tensor(y); }
inline tensor operator/(const parameter &x, const tensor &y) { return dyana::tensor(x) / y; }
inline tensor zeros(const Dim &d) { return dynet::zeros(_cg(), d); }
inline tensor ones(const Dim &d) { return dynet::ones(_cg(), d); }
/**
* \ingroup inputoperations
* \brief Create a random normal vector
* \details Create a vector distributed according to normal distribution with specified mean and standard deviation.
*
* \param d The dimensions of the input
* \param mean The mean of the distribution (default: 0.0)
* \param stddev The standard deviation of the distribution (default: 1.0)
*
* \return A "d" dimensioned normally distributed vector
*/
inline tensor random_normal(const Dim& d, float mean = 0, float stddev = 1) { return dynet::random_normal(_cg(), d, mean, stddev);}
/**
* \ingroup inputoperations
* \brief Create a random uniform vector
* \details Create a vector distributed according to uniform distribution with boundaries left and right.
*
* \param d The dimensions of the input
* \param left The left boundary
* \param right The right boundary
*
* \return A "d" dimensioned uniform distributed vector
*/
inline tensor random_uniform(const Dim& d, float left, float right) { return dynet::random_uniform(_cg(), d, left, right); }
/**
* \ingroup arithmeticoperations
* \brief Affine transform
* \details This performs an affine transform over an arbitrary (odd) number of expressions
* held in the input initializer list xs.
* The first expression is the "bias," which is added to the expression as-is.
* The remaining expressions are multiplied together in pairs, then added.
* A very common usage case is the calculation of the score for a neural network
* layer (e.g. b + Wz) where b is the bias, W is the weight matrix, and z is the
* input. In this case xs[0] = b, xs[1] = W, and xs[2] = z.
*
* \param xs An initializer list containing an odd number of expressions
*
* \return An expression equal to: xs[0] + xs[1]*xs[2] + xs[3]*xs[4] + ...
*/
inline tensor affine_transform(const std::initializer_list<tensor> &xs) {
return dynet::affine_transform(tensor::vector_cast_to_base(xs));
}
inline tensor affine_transform(const std::vector<tensor> &xs) {
return dynet::affine_transform(tensor::vector_cast_to_base(xs));
}
/**
* \ingroup arithmeticoperations
* \brief Sum
* \details This performs an elementwise sum over all the expressions in xs
*
* \param xs An initializer list containing expressions
*
* \return An expression where the ith element is equal to xs[0][i] + xs[1][i] + ...
*/
inline tensor sum(const std::vector<tensor> &xs) { return dynet::sum(tensor::vector_cast_to_base(xs)); }
/**
* \ingroup arithmeticoperations
* \brief Sum all elements
* \details Sum all the elements in an expression.
*
* \param x The input expression
*
* \return The sum of all of its elements
*/
inline tensor sum_elems(const tensor &x) { return dynet::sum_elems(x); }
/**
* \ingroup arithmeticoperations
* \brief Compute moment over all elements
* \details Compute the moment of order \f$r\f$, \f$\frac 1 n\sum_{i=1}^nx_i^r\f$ over all the elements in each batch of the expression
*
* \param x The input mini-batched expression
* \param r Order of the moment
*
* \return A scalar expression (with a potential batch dimension)
*/
inline tensor moment_elems(const tensor &x, unsigned r) { return dynet::moment_elems(x, r); }
/**
* \ingroup arithmeticoperations
* \brief Compute mean over all elements
* \details Computes \f$\frac 1 n\sum_{i=1}^nx_i\f$ over all the elements in each batch of the expression
*
* \param x The input mini-batched expression
*
* \return A scalar expression (with a potential batch dimension)
*/
inline tensor mean_elems(const tensor &x) { return dynet::mean_elems(x); }
/**
* \ingroup arithmeticoperations
* \brief Compute Standard deviation over all elements
* \details Computes \f$\frac 1 n\sum_{i=1}^n(x_i -\mu)^2\f$ where \f$\mu=\frac 1 n\sum_{i=1}^nx_i\f$ over all the elements in each batch of the expression
*
* \param x The input mini-batched expression
*
* \return A scalar expression (with a potential batch dimension)
*/
inline tensor std_elems(const tensor &x) { return dynet::std_elems(x); }
/**
* \ingroup arithmeticoperations
* \brief Sum over minibatches
* \details Sum an expression that consists of multiple minibatches into one of
* equal dimension but with only a single minibatch. This is useful
* for summing loss functions at the end of minibatch training.
*
* \param x The input mini-batched expression
*
* \return An expression with a single batch
*/
inline tensor sum_batches(const tensor &x) { return dynet::sum_batches(x); }
/**
* \ingroup arithmeticoperations
* \brief Compute moment over minibatches
* \details Compute the moment of order \f$r\f$, \f$\frac 1 n\sum_{i=1}^nx_i^r\f$ along the batch dimension
*
* \param x The input mini-batched expression
* \param r Order of the moment
*
* \return An expression with a single batch
*/
inline tensor moment_batches(const tensor &x, unsigned r) { return dynet::moment_batches(x, r); }
/**
* \ingroup arithmeticoperations
* \brief Compute mean over minibatches
* \details Computes \f$\frac 1 n\sum_{i=1}^nx_i\f$ along the batch dimension
*
* \param x The input mini-batched expression
*
* \return An expression with a single batch
*/
inline tensor mean_batches(const tensor &x) { return dynet::mean_batches(x); }
/**
* \ingroup arithmeticoperations
* \brief Compute standard deviation over minibatches
* \details Computes \f$\frac 1 n\sum_{i=1}^n(x_i -\mu)^2\f$ where \f$\mu=\frac 1 n\sum_{i=1}^nx_i\f$ along the batch dimension
*
* \param x The input mini-batched expression
*
* \return A scalar expression (with a potential batch dimension)
*/
inline tensor std_batches(const tensor &x) { return dynet::std_batches(x); }
/**
* \ingroup arithmeticoperations
* \brief Compute sum along a specific dimension or dimensions
* \details Compute the sum along a specific dimension or dimensions
*
* \param x The input mini-batched expression
* \param d Dimensions along which to reduce
* \param b Whether to include batch dimension (default: false)
*
* \return An expression with |d| less dimensions and possibly dropped batch dimension
*/
inline tensor sum_dim(const tensor &x, const std::vector<unsigned> &dims, bool b = false) {
return dynet::sum_dim(x, dims, b);
}
// These are deprecated but kept for backward compatibility
inline tensor sum_rows(const tensor &x) { return dynet::sum_rows(x); }
inline tensor sum_cols(const tensor &x) { return dynet::sum_cols(x); }
/**
* \ingroup arithmeticoperations
* \brief Compute cumulative sum along a specific dimension
* \details Compute the cumulative sum along a specific dimension: \f$y_i=\sum_{j\leq i}x_j\f$
*
* \param x The input mini-batched expression
* \param d Dimensions along which to compute the cumulative sum
*
* \return An expression of the same shape as the input
*/
inline tensor cumsum(const tensor &x, unsigned d) { return dynet::cumsum(x, d); }
/**
* \ingroup arithmeticoperations
* \brief Compute moment along a specific dimension
* \details Compute the moment of order \f$r\f$, \f$\frac 1 n\sum_{i=1}^nx_i^r\f$ along a specific dimension
*
* \param x The input mini-batched expression
* \param d Dimensions along which to reduce
* \param r Order of the moment
* \param b Whether to include batch dimension (default: false)
* \param n If > 0, overwrite the n in the equation by this value, useful for masking (default: 0)
*
* \return An expression with |d| less dimensions and possibly dropped batch dimension
*/
inline tensor moment_dim(const tensor &x, const std::vector<unsigned> &dims, unsigned r, bool b = false,
unsigned n = 0) { return dynet::moment_dim(x, dims, r, b, n); }
/**
* \ingroup arithmeticoperations
* \brief Compute mean along a specific dimension
* \details Computes \f$\frac 1 n\sum_{i=1}^nx_i\f$ along a specific dimension
*
* \param x The input mini-batched expression
* \param d Dimensions along which to reduce
* \param b Whether to include batch dimension (default: false)
* \param n If > 0, overwrite the n in the equation by this value, useful for masking (default: 0)
*
* \return An expression with |d| less dimensions and possibly dropped batch dimension
*/
inline tensor mean_dim(const tensor &x, const std::vector<unsigned> &dims, bool b = false,
unsigned n = 0) { return dynet::mean_dim(x, dims, b, n); }
/**
* \ingroup arithmeticoperations
* \brief Compute standard deviation along an arbitrary dimension
* \details Computes \f$\frac 1 n\sum_{i=1}^n(x_i -\mu)^2\f$ where \f$\mu=\frac 1 n\sum_{i=1}^nx_i\f$ along an arbitrary dimension
*
* \param x The input mini-batched expression
* \param d Dimensions along which to reduce
* \param b Whether to include batch dimension (default: false)
* \param n If > 0, overwrite the n in the equation by this value, useful for masking (default: 0)
*
* \return An expression with |d| less dimensions and possibly dropped batch dimension
*/
inline tensor std_dim(const tensor &x, const std::vector<unsigned> &dims, bool b = false,
unsigned n = 0) { return dynet::std_dim(x, dims, b, n); }
/**
* \ingroup arithmeticoperations
* \brief Average
* \details This performs an elementwise average over all the expressions in xs
*
* \param xs An initializer list containing expressions
*
* \return An expression where the ith element is equal to (xs[0][i] + xs[1][i] + ...)/|xs|
*/
inline tensor average(const std::vector<tensor> &xs) { return dynet::average(tensor::vector_cast_to_base(xs)); }
/**
* \ingroup arithmeticoperations
* \brief Square root
* \details Elementwise square root.
*
* \param x The input expression
*
* \return An expression where the ith element is equal to \f$\sqrt(x_i)\f$
*/
inline tensor sqrt(const tensor &x) { return dynet::sqrt(x); }
/**
* \ingroup arithmeticoperations
* \brief Absolute value
* \details Elementwise absolute value.
*
* \param x The input expression
*
* \return An expression where the ith element is equal to \f$\vert x_i\vert\f$
*/
inline tensor abs(const tensor &x) { return dynet::abs(x); }
/**
* \ingroup arithmeticoperations
* \brief Gaussian error function
* \details Elementwise calculation of the Gaussian error function
*
* \param x The input expression
*
* \return An expression where the ith element is equal to erf(x_i)
*/
inline tensor erf(const tensor &x) { return dynet::erf(x); }
/**
* \ingroup arithmeticoperations
* \brief Inverse sine
* \details Elementwise calculation of the inverse sine
*
* \param x The input expression
*
* \return An expression where the ith element is equal to asin(x_i)
*/
inline tensor asin(const tensor &x) { return dynet::asin(x); }
/**
* \ingroup arithmeticoperations
* \brief Inverse cosine
* \details Elementwise calculation of the inverse cosine
*
* \param x The input expression
*
* \return An expression where the ith element is equal to acos(x_i)
*/
inline tensor acos(const tensor &x) { return dynet::acos(x); }
/**
* \ingroup arithmeticoperations
* \brief Inverse tangent
* \details Elementwise calculation of the inverse tangent
*
* \param x The input expression
*
* \return An expression where the ith element is equal to atan(x_i)
*/
inline tensor atan(const tensor &x) { return dynet::atan(x); }
/**
* \ingroup arithmeticoperations
* \brief Sine
* \details Elementwise calculation of the sine
*
* \param x The input expression
*
* \return An expression where the ith element is equal to sin(x_i)
*/
inline tensor sin(const tensor &x) { return dynet::sin(x); }
/**
* \ingroup arithmeticoperations
* \brief Cosine
* \details Elementwise calculation of the cosine
*
* \param x The input expression
*
* \return An expression where the ith element is equal to cos(x_i)
*/
inline tensor cos(const tensor &x) { return dynet::cos(x); }
/**
* \ingroup arithmeticoperations
* \brief Tangent
* \details Elementwise calculation of the tangent
*
* \param x The input expression
*
* \return An expression where the ith element is equal to tan(x_i)
*/
inline tensor tan(const tensor &x) { return dynet::tan(x); }
/**
* \ingroup arithmeticoperations
* \brief Hyperbolic sine
* \details Elementwise calculation of the hyperbolic sine
*
* \param x The input expression
*
* \return An expression where the ith element is equal to sinh(x_i)
*/
inline tensor sinh(const tensor &x) { return dynet::sinh(x); }
/**
* \ingroup arithmeticoperations
* \brief Hyperbolic cosine
* \details Elementwise calculation of the hyperbolic cosine
*
* \param x The input expression
*
* \return An expression where the ith element is equal to cosh(x_i)
*/
inline tensor cosh(const tensor &x) { return dynet::cosh(x); }
/**
* \ingroup arithmeticoperations
* \brief Hyperbolic tangent
* \details Elementwise calculation of the hyperbolic tangent
*
* \param x The input expression
*
* \return An expression where the ith element is equal to tanh(x_i)
*/
inline tensor tanh(const tensor &x) { return dynet::tanh(x); }
/**
* \ingroup arithmeticoperations
* \brief Inverse hyperbolic sine
* \details Elementwise calculation of the inverse hyperbolic sine
*
* \param x The input expression
*
* \return An expression where the ith element is equal to asinh(x_i)
*/
inline tensor asinh(const tensor &x) { return dynet::asinh(x); }
/**
* \ingroup arithmeticoperations
* \brief Inverse hyperbolic cosine
* \details Elementwise calculation of the inverse hyperbolic cosine
*
* \param x The input expression
*
* \return An expression where the ith element is equal to acosh(x_i)
*/
inline tensor acosh(const tensor &x) { return dynet::acosh(x); }
/**
* \ingroup arithmeticoperations
* \brief Inverse hyperbolic tangent
* \details Elementwise calculation of the inverse hyperbolic tangent
*
* \param x The input expression
*
* \return An expression where the ith element is equal to atanh(x_i)
*/
inline tensor atanh(const tensor &x) { return dynet::atanh(x); }
/**
* \ingroup arithmeticoperations
* \brief Natural exponent
* \details Calculate elementwise y_i = e^{x_i}
*
* \param x The input expression
*
* \return An expression where the ith element is equal to e^{x_i}
*/
inline tensor exp(const tensor &x) { return dynet::exp(x); }
/**
* \ingroup arithmeticoperations
* \brief Square
* \details Calculate elementwise y_i = x_i^2
*
* \param x The input expression
*
* \return An expression where the ith element is equal to x_i^2
*/
inline tensor square(const tensor &x) { return dynet::square(x); }
/**
* \ingroup arithmeticoperations
* \brief Cube
* \details Calculate elementwise y_i = x_i^3
*
* \param x The input expression
*
* \return An expression where the ith element is equal to x_i^3
*/
inline tensor cube(const tensor &x) { return dynet::cube(x); }
/**
* \ingroup arithmeticoperations
* \brief Log sigmoid
* \details Calculate elementwise \f$y_i = \ln(\frac{1}{1+e^{-x_i}})\f$
* This is more numerically stable than `log(logistic(x))`
*
* \param x The input expression
*
* \return An expression where the ith element is equal to \f$y_i = \ln(\frac{1}{1+e^{-x_i}})\f$
*/
inline tensor log_sigmoid(const tensor &x) { return dynet::log_sigmoid(x); }
/**
* \ingroup arithmeticoperations
* \brief Log gamma
* \details Calculate elementwise y_i = ln(gamma(x_i))
*
* \param x The input expression
*
* \return An expression where the ith element is equal to ln(gamma(x_i))
*/
inline tensor lgamma(const tensor &x) { return dynet::lgamma(x); }
/**
* \ingroup arithmeticoperations
* \brief Logarithm
* \details Calculate the elementwise natural logarithm y_i = ln(x_i)
*
* \param x The input expression
*
* \return An expression where the ith element is equal to ln(x_i)
*/
inline tensor log(const tensor &x) { return dynet::log(x); }
/**
* \ingroup arithmeticoperations
* \brief Logistic sigmoid function
* \details Calculate elementwise y_i = 1/(1+e^{-x_i})
*
* \param x The input expression
*
* \return An expression where the ith element is equal to y_i = 1/(1+e^{-x_i})
*/
inline tensor logistic(const tensor &x) { return dynet::logistic(x); }
inline tensor sigmoid(const tensor &x) { return dynet::logistic(x); }
/**
* \ingroup arithmeticoperations
* \brief Rectifier
* \details Calculate elementwise the recitifer (ReLU) function y_i = max(x_i,0)
*
* \param x The input expression
*
* \return An expression where the ith element is equal to max(x_i,0)
*/
inline tensor rectify(const tensor &x) { return dynet::rectify(x); }
/**
* \ingroup arithmeticoperations
* \brief Exponential Linear Unit
* \details Calculate elementwise the function
*
* \f$
* y_i = \left\{\begin{array}{lr}
* x_i, & \text{if } x>0\\
* \alpha\times(e^{x_i} - 1), & \text{if }x\leqslant 0\\
* \end{array}\right.
* \f$
*
* Reference: [Clevert et al., 2015](https://arxiv.org/abs/1511.07289v5)
*
* \param x The input expression
*
* \return An expression where the ith element is equal to \f$\text{ELU}(x_i, \alpha)\f$
*/
inline tensor elu(const tensor &x, float alpha = 1.f) { return dynet::elu(x, alpha); }
/**
* \ingroup arithmeticoperations
* \brief Scaled Exponential Linear Unit (SELU)
* \details Calculate elementwise the function
*
* \f$
* y_i = \lambda\times\left\{\begin{array}{lr}
* x_i, & \text{if } x>0\\
* \alpha\times(e^{x_i} - 1), & \text{if }x\leqslant 0\\
* \end{array}\right.
* \f$
*
* With
* \f$
* \begin{split}
* \lambda &=\texttt{1.0507009873554804934193349852946}\\
* \alpha &=\texttt{1.6732632423543772848170429916717}\\
* \end{split}
* \f$
*
* Reference: [Klambaouer et al., 2017](https://arxiv.org/abs/1706.02515)
*
* \param x The input expression
*
* \return An expression where the ith element is equal to \f$\text{SELU}(x_i)\f$
*/
inline tensor selu(const tensor &x) { return dynet::selu(x); }
/**
* \ingroup arithmeticoperations
* \brief SILU / SiL / Swish
* \details Calculate elementwise y_i = x_i / (1 + e^{-beta * x_i})
*
* Reference: [Hendrycks and Gimpel, 2016](https://openreview.net/pdf?id=Bk0MRI5lg),
* [Elfwing et al, 2017](https://arxiv.org/pdf/1702.03118.pdf), and
* [Ramachandran et al., 2017](https://arxiv.org/pdf/1710.05941)
*
* \param x The input expression
*
* \return An expression where the ith element is equal to y_i = x_i / (1 + e^{-beta * x_i})
*/
inline tensor silu(const tensor &x, float beta = 1.f) { return dynet::silu(x, beta); }
/**
* \ingroup arithmeticoperations
* \brief Soft Sign
* \details Calculate elementwise the softsign function y_i = x_i/(1+|x_i|)
*
* \param x The input expression
*
* \return An expression where the ith element is equal to x_i/(1+|x_i|)
*/
inline tensor softsign(const tensor &x) { return dynet::softsign(x); }
/**
* \ingroup arithmeticoperations
* \brief Power function
* \details Calculate an output where the ith element is equal to x_i^y
*
* \param x The input expression
* \param y The exponent expression(scalar expression)
*
* \return An expression where the ith element is equal to x_i^y
*/
inline tensor pow(const tensor &x, const tensor &y) { return dynet::pow(x, y); }
inline tensor gelu(const tensor& x) {
return cmult(0.5*x, (1.0+tanh(0.79788456*(x + 0.044715*cube(x)))));
}
/**
* \ingroup arithmeticoperations
* \brief Minimum
* \details Calculate an output where the ith element is min(x_i,y_i)
*
* \param x The first input expression
* \param y The second input expression
*
* \return An expression where the ith element is equal to min(x_i,y_i)
*/
inline tensor min(const tensor &x, const tensor &y) { return dynet::min(x, y); }
/**
* \ingroup arithmeticoperations
* \brief Maximum
* \details Calculate an output where the ith element is max(x_i,y_i)
*
* \param x The first input expression
* \param y The second input expression
*
* \return An expression where the ith element is equal to max(x_i,y_i)
*/
inline tensor max(const tensor &x, const tensor &y) { return dynet::max(x, y); }
/**
* \ingroup arithmeticoperations
* \brief Max
* \details This performs an elementwise max over all the expressions in xs
*
* \param xs An initializer list containing expressions
*
* \return An expression where the ith element is equal to max(xs[0][i], xs[1][i], ...)
*/
inline tensor max(const std::vector<tensor> &xs) {
if (xs.empty()) { throw std::runtime_error("cannot perform max on empty list"); }
auto extra_dim = xs[0].dim().nd;
return dynet::max_dim(dynet::concatenate(tensor::vector_cast_to_base(xs), extra_dim), extra_dim);
}
/**
* \ingroup arithmeticoperations
* \brief Dot Product
* \details Calculate the dot product sum_i x_i*y_i
*
* \param x The input expression
* \param y The input expression
*
* \return An expression equal to the dot product
*/
inline tensor dot_product(const tensor &x, const tensor &y) { return dynet::dot_product(x, y); }
/**
* \ingroup arithmeticoperations
* \brief Circular convolution
* \details Calculate the circular convolution
*
* \param x The input expression
* \param y The input expression
*
* \return An expression equal to the circular convolution
*/
inline tensor circ_conv(const tensor &u, const tensor &v) { return dynet::circ_conv(u, v); }
/**
* \ingroup arithmeticoperations
* \brief Circular correlation
* \details Calculate the circular correlation
*
* \param x The input expression
* \param y The input expression
*
* \return An expression equal to the circular correlation
*/
inline tensor circ_corr(const tensor &u, const tensor &v) { return dynet::circ_corr(u, v); }
/**
* \ingroup arithmeticoperations
* \brief Componentwise multiply
* \details Multiply two expressions component-wise, broadcasting dimensions if necessary as follows:
* - When number of dimensions differ, we add dimensions of size 1 to make the number of dimensions match
* - Now, every dimensions is required to have matching size, or one of the dimensions must equal 1 (in which case it will be broadcasted)
* - In the same way, the batch dimension must match, or equal 1 in which case it will be broadcasted
* - The resulting tensor's dimensionality is thus determined as the max of both inputs at every position
*
* \param x The first input expression
* \param y The second input expression
*
* \return An expression where the ith element is equal to x_i*y_i
*/
inline tensor cmult(const tensor &x, const tensor &y) { return dynet::cmult(x, y); }
/**
* \ingroup arithmeticoperations
* \brief Componentwise division
* \details Divide an expressions component-wise by another, broadcasting dimensions (currently only of the second expression!) if necessary as follows:
* - When number of dimensions differ, we add dimensions of size 1 to make the number of dimensions match
* - Now, every dimensions is required to have matching size, or the dim size of the right expression must equal 1 (in which case it will be broadcasted)
* - In the same way, the batch sizes must match, or the batch size of the right expression must equal 1 in which case it will be broadcasted
* - The resulting tensor's dimensionality is thus determined as the max of both inputs at every position
*
* \param x The first input expression
* \param y The second input expression
*
* \return An expression where the ith element is equal to x_i/y_i
*/
inline tensor cdiv(const tensor &x, const tensor &y) { return dynet::cdiv(x, y); }
/**
* \ingroup arithmeticoperations
* \brief Columnwise addition
* \details Add vector "bias" to each column of matrix "x"
*
* \param x An MxN matrix
* \param bias A length M vector
*
* \return An expression where bias is added to each column of x
*/
inline tensor colwise_add(const tensor &x, const tensor &bias) { return dynet::colwise_add(x, bias); }
////////////////////////////////////////////////
// Probability/loss operations //
////////////////////////////////////////////////
/**
* \ingroup lossoperations
* \brief Softmax
* \details The softmax function normalizes each column to ensure that all
* values are between 0 and 1 and add to one by applying
* \f$\frac{e^{x_i}}{\sum_j e^{x_j}}\f$.
*
* \param x A vector or matrix
* \param d dimension to normalize over (default: 0)
*
* \return A vector or matrix after calculating the softmax
*/
inline tensor softmax(const tensor &x, unsigned d = 0) { return dynet::softmax(x, d); }
/**
* \ingroup lossoperations
* \brief Log softmax
* \details The log softmax function normalizes each column to ensure that all
* values are between 0 and 1 and add to one by applying
* \f$\frac{e^{x_i}}{\sum_j e^{x_j}}\f$, then taking the log
*
* \param x A vector or matrix
*
* \return A vector or matrix after calculating the log softmax
*/
inline tensor log_softmax(const tensor &x) { return dynet::log_softmax(x); }
/**
* \ingroup lossoperations
* \brief Restricted log softmax
* \details The log softmax function calculated over only a subset of the vector elements. The
* elements to be included are set by the ``restriction`` variable. All elements not
* included in ``restriction`` are set to negative infinity.
*
* \param x A vector over which to calculate the softmax
* \param restriction The elements over which to calculate the softmax
*
* \return A vector with the log softmax over the specified elements
*/
inline tensor log_softmax(const tensor &x, const std::vector<unsigned> &restriction) {
return dynet::log_softmax(x, restriction);
}
/**
* \ingroup lossoperations
* \brief Log, sum, exp by dimension
* \details The "logsumexp" function calculated over a particular dimension
* \f$ln(\sum_i e^{xs_i})\f$, used in adding probabilities in the log domain.
*
* \param x Expression with respect to which to calculate the logsumexp.
* \param d The dimension along which to do the logsumexp.
*
* \return The result.
*/
inline tensor logsumexp_dim(const tensor &x, unsigned d) { return dynet::logsumexp_dim(x, d); }
/**
* \ingroup lossoperations
* \brief Log, sum, exp
* \details The elementwise "logsumexp" function that calculates
* \f$ln(\sum_i e^{xs_i})\f$, used in adding probabilities in the log domain.
*
* \param xs Expressions with respect to which to calculate the logsumexp.
*
* \return The result.
*/
inline tensor logsumexp(const std::vector<tensor> &xs) { return dynet::logsumexp(tensor::vector_cast_to_base(xs)); }
/**
* \ingroup lossoperations
* \brief Negative softmax log likelihood
* \details This function takes in a vector of scores ``x``, and performs a log softmax, takes
* the negative, and selects the likelihood corresponding to the element ``v``. This is
* perhaps the most standard loss function for training neural networks to predict
* one out of a set of elements.
*
* \param x A vector of scores
* \param v The element with which to calculate the loss
*
* \return The negative log likelihood of element ``v`` after taking the softmax
*/
inline tensor pickneglogsoftmax(const tensor &x, unsigned v) { return dynet::pickneglogsoftmax(x, v); }
/**
* \ingroup lossoperations
* \brief Hinge loss
* \details This expression calculates the hinge loss, formally expressed as:
* \f$ \text{hinge}(x,index,m) = \sum_{i \ne index} \max(0, m-x[index]+x[i]). \f$
*
* \param x A vector of scores
* \param index The index of the correct candidate
* \param m The margin
*
* \return The hinge loss of candidate ``index`` with respect to margin ``m``
*/
inline tensor hinge(const tensor &x, unsigned index, float m = 1.0) { return dynet::hinge(x, index, m); }
/**
* \ingroup lossoperations
* \brief Dimensionwise hinge loss
* \details This expression calculates the hinge loss over a particular dimension ``d``.
*
* \param x A matrix of scores
* \param indices The indices of the correct candidate (equal in length to the
* dimension not specified by "d")
* \param d The dimension over which to calculate the loss (0 or 1)
* \param m The margin
*
* \return A vector of hinge losses for each index in ``indices``.
*/
inline tensor hinge_dim(const tensor &x, const std::vector<unsigned> &indices, unsigned d = 0,
float m = 1.0) { return dynet::hinge_dim(x, indices, d, m); }
/**
* \ingroup lossoperations
* \brief Batched dimensionwise hinge loss
* \details The same as dimensionwise hinge loss, but for the case where ``x`` is a mini-batched tensor
* with ``indices.size()`` batch elements.
*
* \param x A mini-batch of vectors with ``indices.size()`` batch elements
* \param indices The indices of the correct candidates for each batch element
* \param d The dimension over which to calculate the loss (0 or 1)
* \param m The margin
*
* \return A vector of hinge losses for each mini-batch
*/
inline tensor hinge_dim(const tensor &x, const std::vector<std::vector<unsigned> > &indices, unsigned d = 0,
float m = 1.0) { return dynet::hinge_dim(x, indices, d, m); }
/**
* \ingroup lossoperations
* \brief Sparsemax
* \details The sparsemax function (Martins et al. 2016), which is similar to softmax,
* but induces sparse solutions where most of the vector elements are zero.
* **Note:** This function is not yet implemented on GPU.
*
* \param x A vector of scores
*
* \return The sparsemax of the scores
*/
inline tensor sparsemax(const tensor &x) { return dynet::sparsemax(x); }
/**
* \ingroup lossoperations
* \brief Sparsemax loss
* \details The sparsemax loss function (Martins et al. 2016), which is similar to
* softmax loss, but induces sparse solutions where most of the vector
* elements are zero. It has a gradient similar to the sparsemax function
* and thus is useful for optimizing when the sparsemax will be used at
* test time.
* **Note:** This function is not yet implemented on GPU.
*
* \param x A vector of scores
* \param target_support The target correct labels.
*
* \return The sparsemax loss of the labels
*/
inline tensor sparsemax_loss(const tensor &x, const std::vector<unsigned> &target_support) {
return dynet::sparsemax_loss(x, target_support);
}
/**
* \ingroup lossoperations
* \brief Constrained softmax
* \details The constrained softmax function.
* **Note:** This function is not yet implemented on GPU.
*
* \param x A vector of scores
* \param y A vector of upper bound constraints on probabilities
*
* \return The constrained softmax of the scores.
*/
inline tensor constrained_softmax(const tensor &x, const tensor &y) {
return dynet::constrained_softmax(x, y);
}
/**
* \ingroup lossoperations
* \brief Squared norm
* \details The squared L2 norm of the values of x: \f$\sum_i x_i^2\f$.
*
* \param x A vector of values
*
* \return The squared L2 norm