Repository navigation
Expand file tree
/
Copy pathprimitives.cpp
More file actions
6629 lines (5944 loc) · 202 KB
/
Copy pathprimitives.cpp
File metadata and controls
6629 lines (5944 loc) · 202 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright © 2023-2024 Apple Inc.
// Required for using M_2_SQRTPI in MSVC.
#define _USE_MATH_DEFINES
#include <algorithm>
#include <cassert>
#include <cmath>
#include <numeric>
#include <sstream>
#include <stdexcept>
#include "mlx/backend/common/utils.h"
#include "mlx/fft.h"
#include "mlx/linalg.h"
#include "mlx/ops.h"
#include "mlx/primitives.h"
#include "mlx/utils.h"
namespace mlx::core {
namespace {
std::tuple<array, array, int> vmap_binary_op(
const std::vector<array>& inputs,
const std::vector<int>& axes,
const Stream& stream) {
assert(inputs.size() == 2);
assert(axes.size() == 2);
if (axes[0] == -1 && axes[1] == -1) {
return {inputs[0], inputs[1], -1};
}
auto a = inputs[0];
auto b = inputs[1];
int ndim = std::max(a.ndim() + (axes[0] == -1), b.ndim() + (axes[1] == -1));
auto expand_dims = [stream, ndim](auto in) {
auto shape = in.shape();
shape.insert(shape.begin(), ndim - shape.size(), 1);
return reshape(in, shape, stream);
};
int to_ax = (ndim - a.ndim()) + axes[0];
int from_ax = (ndim - b.ndim()) + axes[1];
a = expand_dims(a);
b = expand_dims(b);
if (from_ax != to_ax) {
std::vector<int> tdims(b.ndim());
std::iota(tdims.begin(), tdims.end(), 0);
tdims.erase(tdims.begin() + from_ax);
tdims.insert(tdims.begin() + to_ax, from_ax);
b = transpose(b, tdims, stream);
}
return {a, b, to_ax};
}
std::tuple<array, array, array, int> vmap_ternary_op(
const std::vector<array>& inputs,
const std::vector<int>& axes,
const Stream& stream) {
assert(inputs.size() == 3);
assert(axes.size() == 3);
if (axes[0] == -1 && axes[1] == -1 && axes[2] == -1) {
return {inputs[0], inputs[1], inputs[2], -1};
}
auto a = inputs[0];
auto b = inputs[1];
auto c = inputs[2];
int ndim = std::max(
{a.ndim() + (axes[0] == -1),
b.ndim() + (axes[1] == -1),
c.ndim() + (axes[2] == -1)});
auto expand_dims = [stream, ndim](auto in) {
auto shape = in.shape();
shape.insert(shape.begin(), ndim - shape.size(), 1);
return reshape(in, shape, stream);
};
int to_ax = (ndim - a.ndim()) + axes[0];
int from_ax1 = (ndim - b.ndim()) + axes[1];
int from_ax2 = (ndim - c.ndim()) + axes[2];
a = expand_dims(a);
b = expand_dims(b);
c = expand_dims(c);
auto find_tdims = [](auto x, int to_ax, int from_ax) {
std::vector<int> tdims(x.ndim());
std::iota(tdims.begin(), tdims.end(), 0);
tdims.erase(tdims.begin() + from_ax);
tdims.insert(tdims.begin() + to_ax, from_ax);
return tdims;
};
if (to_ax != from_ax1) {
std::vector<int> tdims = find_tdims(b, to_ax, from_ax1);
b = transpose(b, tdims, stream);
}
if (to_ax != from_ax2) {
std::vector<int> tdims = find_tdims(c, to_ax, from_ax2);
c = transpose(c, tdims, stream);
}
return {a, b, c, to_ax};
}
// Calculate the gradient wrt to the weights of the following calculation
//
// y = gather_mm(x, w.T, lhs_indices, rhs_indices, sorted)
//
// Note the transpose above. This function returns the gradient for w.T so if w
// was used instead then one needs to transpose the returned gradient.
//
// We define it as a separate function to reuse it for gather_mm and
// gather_qmm.
array gather_mm_grad(
const array& x,
const array& dy,
const array& lhs_indices,
const array& rhs_indices,
bool sorted,
Shape batch_shape,
const Stream& s) {
int M = x.shape(-2);
int K = x.shape(-1);
int N = dy.shape(-1);
int num_segments = std::accumulate(
batch_shape.begin(), batch_shape.end(), 1, std::multiplies<int>());
batch_shape.push_back(N);
batch_shape.push_back(K);
// If the indices are sorted then it means that we can do the whole gradient
// computation via a segmented matmul. We just need to calculate the segments
// using the indices.
if (sorted) {
auto segments = zeros({num_segments}, uint32, s);
segments = scatter_add_axis(segments, rhs_indices, array(M, uint32), 0, s);
segments = cumsum(segments, 0, false, true, s);
segments = concatenate({array({0}, {1}, uint32), segments}, 0, s);
segments = as_strided(segments, {num_segments, 2}, {1, 1}, 0, s);
return reshape(
segmented_mm(
swapaxes(flatten(dy, 0, -2, s), 0, 1, s),
flatten(x, 0, -2, s),
segments,
s),
std::move(batch_shape),
s);
}
// Otherwise we need to gather matmul the dy and then scatter add it to the
// correct locations.
else {
// TODO: If the lhs indices wasn't provided, this is always a sorted matmul
// so we should add that check.
auto dw = gather_mm(
swapaxes(dy, -1, -2, s), x, std::nullopt, lhs_indices, false, s);
return reshape(
scatter_add(
zeros({num_segments, N, K}, dw.dtype(), s),
rhs_indices,
expand_dims(dw, -3, s),
0,
s),
std::move(batch_shape),
s);
}
}
bool is_transposed_matrix(const array& x) {
if (x.ndim() < 2) {
return false;
}
if (x.is_available()) {
return x.strides(-2) == 1 && x.strides(-1) == x.shape(-2) &&
x.shape(-1) > 1;
}
if (!x.has_primitive()) {
return false;
}
auto& p = x.primitive();
if (typeid(p) != typeid(Transpose)) {
return false;
}
auto axes = static_cast<Transpose*>(&p)->state();
int n = axes.size();
for (int i = 0; i < n - 2; ++i) {
if (axes[i] != i) {
return false;
}
}
return axes[n - 2] == n - 1 && axes[n - 1] == n - 2;
}
array matmul_vjp_a(
const array& cotan,
const array& a,
const array& b,
const std::vector<int>& reorder,
Stream s) {
if (is_transposed_matrix(a)) {
// (b.conj() @ cotan.T).T
return transpose(
matmul(conjugate(b, s), transpose(cotan, reorder, s), s), reorder, s);
}
// M X N * (K X N).T -> M X K
return matmul(cotan, transpose(conjugate(b, s), reorder, s), s);
}
array matmul_vjp_b(
const array& cotan,
const array& a,
const array& b,
const std::vector<int>& reorder,
Stream s) {
if (is_transposed_matrix(b)) {
// (cotan.T @ a.conj()).T
return transpose(
matmul(transpose(cotan, reorder, s), conjugate(a, s), s), reorder, s);
}
// (M X K).T * M X N -> K X N
return matmul(transpose(conjugate(a, s), reorder, s), cotan, s);
}
} // namespace
std::vector<array> Primitive::jvp(
const std::vector<array>&,
const std::vector<array>&,
const std::vector<int>&) {
std::ostringstream msg;
msg << "[Primitive::jvp] Not implemented for ";
msg << name();
msg << ".";
throw std::invalid_argument(msg.str());
}
std::vector<array> Primitive::vjp(
const std::vector<array>&,
const std::vector<array>&,
const std::vector<int>&,
const std::vector<array>&) {
std::ostringstream msg;
msg << "[Primitive::vjp] Not implemented for ";
msg << name();
msg << ".";
throw std::invalid_argument(msg.str());
}
std::pair<std::vector<array>, std::vector<int>> Primitive::vmap(
const std::vector<array>&,
const std::vector<int>&) {
std::ostringstream msg;
msg << "[Primitive::vmap] Not implemented for ";
msg << name();
msg << ".";
throw std::invalid_argument(msg.str());
}
std::vector<Shape> Primitive::output_shapes(const std::vector<array>&) {
std::ostringstream msg;
msg << "[Primitive::output_shapes] ";
msg << name();
msg << " cannot infer output shapes.";
throw std::invalid_argument(msg.str());
}
std::vector<array> Abs::vjp(
const std::vector<array>& primals,
const std::vector<array>& cotangents,
const std::vector<int>& argnums,
const std::vector<array>&) {
assert(primals.size() == 1);
assert(argnums.size() == 1);
return {multiply(cotangents[0], sign(primals[0], stream()), stream())};
}
std::vector<array> Abs::jvp(
const std::vector<array>& primals,
const std::vector<array>& tangents,
const std::vector<int>& argnums) {
assert(primals.size() == 1);
assert(argnums.size() == 1);
auto s = sign(primals[0], stream());
if (issubdtype(primals[0].dtype(), complexfloating)) {
// |z| is real-valued, so its directional derivative is real:
// d|z| = Re(conj(z) * t) / |z| = Re(conj(sign(z)) * t).
return {real(
multiply(tangents[0], conjugate(s, stream()), stream()), stream())};
}
return {multiply(tangents[0], s, stream())};
}
std::pair<std::vector<array>, std::vector<int>> Abs::vmap(
const std::vector<array>& inputs,
const std::vector<int>& axes) {
assert(inputs.size() == 1);
assert(axes.size() == 1);
return {{abs(inputs[0], stream())}, axes};
}
std::vector<array> Add::jvp(
const std::vector<array>& primals,
const std::vector<array>& tangents,
const std::vector<int>& argnums) {
return {
tangents.size() > 1 ? add(tangents[0], tangents[1], stream())
: tangents[0]};
}
std::vector<array> Add::vjp(
const std::vector<array>& primals,
const std::vector<array>& cotangents,
const std::vector<int>& argnums,
const std::vector<array>&) {
if (argnums.size() == 1) {
return cotangents;
} else {
return {cotangents[0], cotangents[0]};
}
}
std::pair<std::vector<array>, std::vector<int>> Add::vmap(
const std::vector<array>& inputs,
const std::vector<int>& axes) {
auto [a, b, to_ax] = vmap_binary_op(inputs, axes, stream());
return {{add(a, b, stream())}, {to_ax}};
}
std::vector<array> AddMM::vjp(
const std::vector<array>& primals,
const std::vector<array>& cotangents,
const std::vector<int>& argnums,
const std::vector<array>&) {
std::vector<array> vjps;
auto& cotan = cotangents[0];
std::vector<int> reorder(cotan.ndim());
std::iota(reorder.begin(), reorder.end(), 0);
std::iter_swap(reorder.end() - 1, reorder.end() - 2);
for (auto arg : argnums) {
if (arg == 0) {
auto cotan_scaled = cotan;
if (alpha_ != 1.) {
auto alpha_arr = array(alpha_, cotan.dtype());
cotan_scaled = (multiply(alpha_arr, cotan_scaled, stream()));
}
vjps.push_back(matmul_vjp_a(
cotan_scaled, primals[0], primals[1], reorder, stream()));
} else if (arg == 1) {
auto cotan_scaled = cotan;
if (alpha_ != 1.) {
auto alpha_arr = array(alpha_, cotan.dtype());
cotan_scaled = (multiply(alpha_arr, cotan_scaled, stream()));
}
vjps.push_back(matmul_vjp_b(
cotan_scaled, primals[0], primals[1], reorder, stream()));
} else {
auto cotan_scaled = cotan;
if (beta_ != 1.) {
auto beta_arr = array(beta_, cotan.dtype());
cotan_scaled = (multiply(beta_arr, cotan_scaled, stream()));
}
vjps.push_back(cotan_scaled);
}
}
return vjps;
}
std::vector<array> AddMM::jvp(
const std::vector<array>& primals,
const std::vector<array>& tangents,
const std::vector<int>& argnums) {
std::vector<array> jvp;
for (int i = 0; i < argnums.size(); ++i) {
auto arg = argnums[i];
if (arg == 0) {
if (jvp.empty()) {
jvp.push_back(matmul(tangents[i], primals[1], stream()));
} else {
jvp[0] = addmm(jvp[0], tangents[i], primals[1], 1.0f, 1.0f, stream());
}
} else if (arg == 1) {
if (jvp.empty()) {
jvp.push_back(matmul(primals[0], tangents[i], stream()));
} else {
jvp[0] = addmm(jvp[0], primals[0], tangents[i], 1.0f, 1.0f, stream());
}
} else {
if (jvp.empty()) {
jvp.push_back(tangents[i]);
} else {
jvp[0] = add(jvp[0], tangents[i], stream());
}
}
}
return jvp;
}
bool AddMM::is_equivalent(const Primitive& other) const {
const AddMM& a_other = static_cast<const AddMM&>(other);
return (alpha_ == a_other.alpha_ && beta_ == a_other.beta_);
}
std::vector<Shape> AddMM::output_shapes(const std::vector<array>& inputs) {
// inputs are {a, b, c}, output shape is a's shape with last dim from b
auto out_shape = inputs[0].shape();
out_shape.back() = inputs[1].shape(-1);
return {std::move(out_shape)};
}
std::pair<std::vector<array>, std::vector<int>> AddMM::vmap(
const std::vector<array>& inputs,
const std::vector<int>& axes) {
auto maybe_move_ax = [this](auto& arr, auto ax) {
return ax > 0 ? moveaxis(arr, ax, 0, stream()) : arr;
};
auto a = maybe_move_ax(inputs[0], axes[0]);
auto b = maybe_move_ax(inputs[1], axes[1]);
auto c = maybe_move_ax(inputs[2], axes[2]);
return {{addmm(c, a, b, alpha_, beta_, stream())}, {0}};
}
bool Arange::is_equivalent(const Primitive& other) const {
const Arange& a_other = static_cast<const Arange&>(other);
return (
start_ == a_other.start_ && stop_ == a_other.stop_ &&
step_ == a_other.step_);
}
std::vector<Shape> Arange::output_shapes(const std::vector<array>&) {
auto real_size = std::ceil((stop_ - start_) / step_);
return {{std::max(static_cast<int>(real_size), 0)}};
}
std::vector<array> ArcCos::vjp(
const std::vector<array>& primals,
const std::vector<array>& cotangents,
const std::vector<int>& argnums,
const std::vector<array>&) {
// The vjp conjugates the jvp's multiplier (a no-op for real inputs).
return {conjugate(
jvp(primals, {conjugate(cotangents[0], stream())}, argnums)[0],
stream())};
}
std::vector<array> ArcCos::jvp(
const std::vector<array>& primals,
const std::vector<array>& tangents,
const std::vector<int>& argnums) {
assert(primals.size() == 1);
assert(argnums.size() == 1);
array one = array(1., primals[0].dtype());
array t = subtract(one, square(primals[0], stream()), stream());
array denom = negative(rsqrt(t, stream()), stream());
return {multiply(tangents[0], denom, stream())};
}
std::pair<std::vector<array>, std::vector<int>> ArcCos::vmap(
const std::vector<array>& inputs,
const std::vector<int>& axes) {
assert(inputs.size() == 1);
assert(axes.size() == 1);
return {{arccos(inputs[0], stream())}, axes};
}
std::vector<array> ArcCosh::vjp(
const std::vector<array>& primals,
const std::vector<array>& cotangents,
const std::vector<int>& argnums,
const std::vector<array>&) {
// The vjp conjugates the jvp's multiplier (a no-op for real inputs).
return {conjugate(
jvp(primals, {conjugate(cotangents[0], stream())}, argnums)[0],
stream())};
}
std::vector<array> ArcCosh::jvp(
const std::vector<array>& primals,
const std::vector<array>& tangents,
const std::vector<int>& argnums) {
assert(primals.size() == 1);
assert(argnums.size() == 1);
array one = array(1., primals[0].dtype());
if (issubdtype(primals[0].dtype(), complexfloating)) {
// rsqrt(x^2 - 1) has the wrong sign for complex x with Re(x) < 0.
array d = multiply(
rsqrt(subtract(primals[0], one, stream()), stream()),
rsqrt(add(primals[0], one, stream()), stream()),
stream());
return {multiply(tangents[0], d, stream())};
}
array t = subtract(square(primals[0], stream()), one, stream());
return {multiply(tangents[0], rsqrt(t, stream()), stream())};
}
std::pair<std::vector<array>, std::vector<int>> ArcCosh::vmap(
const std::vector<array>& inputs,
const std::vector<int>& axes) {
assert(inputs.size() == 1);
assert(axes.size() == 1);
return {{arccosh(inputs[0], stream())}, axes};
}
std::vector<array> ArcSin::vjp(
const std::vector<array>& primals,
const std::vector<array>& cotangents,
const std::vector<int>& argnums,
const std::vector<array>&) {
// The vjp conjugates the jvp's multiplier (a no-op for real inputs).
return {conjugate(
jvp(primals, {conjugate(cotangents[0], stream())}, argnums)[0],
stream())};
}
std::vector<array> ArcSin::jvp(
const std::vector<array>& primals,
const std::vector<array>& tangents,
const std::vector<int>& argnums) {
assert(primals.size() == 1);
assert(argnums.size() == 1);
array one = array(1., primals[0].dtype());
array t = subtract(one, square(primals[0], stream()), stream());
return {multiply(tangents[0], rsqrt(t, stream()), stream())};
}
std::pair<std::vector<array>, std::vector<int>> ArcSin::vmap(
const std::vector<array>& inputs,
const std::vector<int>& axes) {
assert(inputs.size() == 1);
assert(axes.size() == 1);
return {{arcsin(inputs[0], stream())}, axes};
}
std::vector<array> ArcSinh::vjp(
const std::vector<array>& primals,
const std::vector<array>& cotangents,
const std::vector<int>& argnums,
const std::vector<array>&) {
// The vjp conjugates the jvp's multiplier (a no-op for real inputs).
return {conjugate(
jvp(primals, {conjugate(cotangents[0], stream())}, argnums)[0],
stream())};
}
std::vector<array> ArcSinh::jvp(
const std::vector<array>& primals,
const std::vector<array>& tangents,
const std::vector<int>& argnums) {
assert(primals.size() == 1);
assert(argnums.size() == 1);
array one = array(1., primals[0].dtype());
array t = add(square(primals[0], stream()), one, stream());
return {multiply(tangents[0], rsqrt(t, stream()), stream())};
}
std::pair<std::vector<array>, std::vector<int>> ArcSinh::vmap(
const std::vector<array>& inputs,
const std::vector<int>& axes) {
assert(inputs.size() == 1);
assert(axes.size() == 1);
return {{arcsinh(inputs[0], stream())}, axes};
}
std::vector<array> ArcTan::vjp(
const std::vector<array>& primals,
const std::vector<array>& cotangents,
const std::vector<int>& argnums,
const std::vector<array>&) {
// The vjp conjugates the jvp's multiplier (a no-op for real inputs).
return {conjugate(
jvp(primals, {conjugate(cotangents[0], stream())}, argnums)[0],
stream())};
}
std::vector<array> ArcTan::jvp(
const std::vector<array>& primals,
const std::vector<array>& tangents,
const std::vector<int>& argnums) {
assert(primals.size() == 1);
assert(argnums.size() == 1);
array one = array(1., primals[0].dtype());
array t = add(one, square(primals[0], stream()), stream());
return {divide(tangents[0], t, stream())};
}
std::pair<std::vector<array>, std::vector<int>> ArcTan::vmap(
const std::vector<array>& inputs,
const std::vector<int>& axes) {
assert(inputs.size() == 1);
assert(axes.size() == 1);
return {{arctan(inputs[0], stream())}, axes};
}
std::vector<array> ArcTan2::vjp(
const std::vector<array>& primals,
const std::vector<array>& cotangents,
const std::vector<int>& argnums,
const std::vector<array>&) {
assert(primals.size() == 2);
assert(cotangents.size() == 1);
const auto& s = stream();
const array& x1 = primals[0];
const array& x2 = primals[1];
const array& dy = cotangents[0];
std::vector<array> grads;
array dy_over_x1_x2_squared =
divide(dy, add(square(x1, s), square(x2, s), s), s);
for (auto arg : argnums) {
if (arg == 0) {
grads.emplace_back(multiply(x2, dy_over_x1_x2_squared, s));
} else {
grads.emplace_back(multiply(negative(x1, s), dy_over_x1_x2_squared, s));
}
}
return grads;
}
std::vector<array> ArcTan2::jvp(
const std::vector<array>& primals,
const std::vector<array>& tangents,
const std::vector<int>& argnums) {
assert(primals.size() == 2);
assert(tangents.size() == argnums.size());
const auto& s = stream();
const array& x1 = primals[0];
const array& x2 = primals[1];
auto numerator = [&]() {
if (argnums.size() == 2) {
return subtract(
multiply(x2, tangents[0], s), multiply(x1, tangents[1], s), s);
} else if (argnums[0] == 0) {
return multiply(x2, tangents[0], s);
} else {
return negative(multiply(x1, tangents[0], s), s);
}
}();
return {divide(numerator, add(square(x1, s), square(x2, s), s), s)};
}
std::pair<std::vector<array>, std::vector<int>> ArcTan2::vmap(
const std::vector<array>& inputs,
const std::vector<int>& axes) {
assert(inputs.size() == 2);
assert(axes.size() == 2);
auto [a, b, to_ax] = vmap_binary_op(inputs, axes, stream());
return {{arctan2(a, b, stream())}, {to_ax}};
}
std::vector<array> ArcTanh::vjp(
const std::vector<array>& primals,
const std::vector<array>& cotangents,
const std::vector<int>& argnums,
const std::vector<array>&) {
// The vjp conjugates the jvp's multiplier (a no-op for real inputs).
return {conjugate(
jvp(primals, {conjugate(cotangents[0], stream())}, argnums)[0],
stream())};
}
std::vector<array> ArcTanh::jvp(
const std::vector<array>& primals,
const std::vector<array>& tangents,
const std::vector<int>& argnums) {
assert(primals.size() == 1);
assert(argnums.size() == 1);
array one = array(1., primals[0].dtype());
array t = subtract(one, square(primals[0], stream()), stream());
return {divide(tangents[0], t, stream())};
}
std::pair<std::vector<array>, std::vector<int>> ArcTanh::vmap(
const std::vector<array>& inputs,
const std::vector<int>& axes) {
assert(inputs.size() == 1);
assert(axes.size() == 1);
return {{arctanh(inputs[0], stream())}, axes};
}
std::pair<std::vector<array>, std::vector<int>> ArgPartition::vmap(
const std::vector<array>& inputs,
const std::vector<int>& axes) {
assert(inputs.size() == 1);
assert(axes.size() == 1);
int axis_left = axes[0] >= 0 && axes[0] <= axis_;
return {{argpartition(inputs[0], kth_, axis_ + axis_left, stream())}, axes};
}
std::vector<array> ArgPartition::vjp(
const std::vector<array>& primals,
const std::vector<array>&,
const std::vector<int>&,
const std::vector<array>&) {
return {zeros_like(primals[0], stream())};
}
std::vector<array> ArgPartition::jvp(
const std::vector<array>&,
const std::vector<array>& tangents,
const std::vector<int>&) {
return {zeros_like(tangents[0], stream())};
}
bool ArgPartition::is_equivalent(const Primitive& other) const {
const ArgPartition& r_other = static_cast<const ArgPartition&>(other);
return axis_ == r_other.axis_ && kth_ == r_other.kth_;
}
bool ArgReduce::is_equivalent(const Primitive& other) const {
const ArgReduce& r_other = static_cast<const ArgReduce&>(other);
return reduce_type_ == r_other.reduce_type_ && axis_ == r_other.axis_;
}
std::pair<std::vector<array>, std::vector<int>> ArgReduce::vmap(
const std::vector<array>& inputs,
const std::vector<int>& axes) {
int reduce_ax = axis_ + (axes[0] >= 0 && axis_ >= axes[0]);
auto& in = inputs[0];
std::vector<array> out;
if (reduce_type_ == ArgReduce::ArgMin) {
out.push_back(argmin(in, reduce_ax, true, stream()));
} else {
out.push_back(argmax(in, reduce_ax, true, stream()));
}
return {out, axes};
}
std::vector<array> ArgReduce::vjp(
const std::vector<array>& primals,
const std::vector<array>&,
const std::vector<int>&,
const std::vector<array>&) {
return {zeros_like(primals[0], stream())};
}
std::vector<array> ArgReduce::jvp(
const std::vector<array>& primals,
const std::vector<array>&,
const std::vector<int>&) {
auto shape = output_shapes(primals)[0];
return {zeros(shape, uint32, stream())};
}
std::pair<std::vector<array>, std::vector<int>> ArgSort::vmap(
const std::vector<array>& inputs,
const std::vector<int>& axes) {
assert(inputs.size() == 1);
assert(axes.size() == 1);
int axis_left = axes[0] >= 0 && axes[0] <= axis_;
return {{argsort(inputs[0], axis_ + axis_left, stream())}, axes};
}
std::vector<Shape> ArgReduce::output_shapes(const std::vector<array>& inputs) {
auto out_shape = inputs[0].shape();
out_shape[axis_] = 1;
return {std::move(out_shape)};
}
bool ArgSort::is_equivalent(const Primitive& other) const {
const ArgSort& r_other = static_cast<const ArgSort&>(other);
return axis_ == r_other.axis_;
}
std::vector<array> ArgSort::vjp(
const std::vector<array>& primals,
const std::vector<array>&,
const std::vector<int>&,
const std::vector<array>&) {
return {zeros_like(primals[0], stream())};
}
std::vector<array> ArgSort::jvp(
const std::vector<array>& primals,
const std::vector<array>&,
const std::vector<int>&) {
return {zeros(primals[0].shape(), uint32, stream())};
}
std::vector<array> AsType::vjp(
const std::vector<array>& primals,
const std::vector<array>& cotangents,
const std::vector<int>& argnums,
const std::vector<array>&) {
if (cotangents[0].dtype() != dtype_) {
throw std::invalid_argument(
"[astype] Type of cotangents does not match primal output type.");
}
return {astype(cotangents[0], primals[0].dtype(), stream())};
}
std::vector<array> AsType::jvp(
const std::vector<array>& primals,
const std::vector<array>& tangents,
const std::vector<int>& argnums) {
return {astype(tangents[0], dtype_, stream())};
}
std::pair<std::vector<array>, std::vector<int>> AsType::vmap(
const std::vector<array>& inputs,
const std::vector<int>& axes) {
return {{astype(inputs[0], dtype_, stream())}, axes};
}
bool AsType::is_equivalent(const Primitive& other) const {
const AsType& a_other = static_cast<const AsType&>(other);
return dtype_ == a_other.dtype_;
}
std::vector<array> AsStrided::vjp(
const std::vector<array>& primals,
const std::vector<array>& cotangents,
const std::vector<int>& argnums,
const std::vector<array>&) {
assert(argnums.size() == 1);
// Extract the sizes and cast them to ints
int grad_size = primals[0].size();
int cotangents_size = cotangents[0].size();
// Make a flat container to hold the gradients
auto grad = zeros_like(primals[0], stream());
grad = reshape(grad, {grad_size}, stream());
// Create the indices that map output to input
auto idx = arange(grad_size, stream());
idx = as_strided(idx, shape_, strides_, offset_, stream());
idx = reshape(idx, {cotangents_size}, stream());
// Reshape the cotangentsgent for use with scatter
auto flat_cotangents = reshape(cotangents[0], {cotangents_size, 1}, stream());
// Finally accumulate the gradients and reshape them to look like the input
grad = scatter_add(grad, idx, flat_cotangents, 0, stream());
grad = reshape(grad, primals[0].shape(), stream());
return {grad};
}
std::vector<array> AsStrided::jvp(
const std::vector<array>& primals,
const std::vector<array>& tangents,
const std::vector<int>& argnums) {
assert(primals.size() == 1);
return {as_strided(tangents[0], shape_, strides_, offset_, stream())};
}
bool AsStrided::is_equivalent(const Primitive& other) const {
const AsStrided& a_other = static_cast<const AsStrided&>(other);
return shape_ == a_other.shape_ && strides_ == a_other.strides_ &&
offset_ == a_other.offset_;
}
bool BitwiseBinary::is_equivalent(const Primitive& other) const {
const BitwiseBinary& a_other = static_cast<const BitwiseBinary&>(other);
return op_ == a_other.op_;
}
std::pair<std::vector<array>, std::vector<int>> BitwiseBinary::vmap(
const std::vector<array>& inputs,
const std::vector<int>& axes) {
auto [a, b, to_ax] = vmap_binary_op(inputs, axes, stream());
return {
{array(
a.shape(),
a.dtype(),
std::make_shared<BitwiseBinary>(stream(), op_),
{a, b})},
{to_ax}};
}
std::vector<array> BitwiseBinary::jvp(
const std::vector<array>& primals,
const std::vector<array>& tangents,
const std::vector<int>& argnums) {
assert(primals.size() == 2);
auto shape = broadcast_shapes(primals[0].shape(), primals[1].shape());
return {zeros(shape, tangents[0].dtype(), stream())};
}
std::vector<array> BitwiseBinary::vjp(
const std::vector<array>& primals,
const std::vector<array>& cotangents,
const std::vector<int>& argnums,
const std::vector<array>&) {
std::vector<array> vjps;
for (auto arg : argnums) {
vjps.push_back(zeros_like(primals[arg], stream()));
}
return vjps;
}
std::vector<array>
broadcast_vjp(const array& primal, const array& cotan, const Stream& s) {
// Reduce cotangents to the shape of the primal
auto& shape = primal.shape();
int diff = cotan.ndim() - shape.size();
std::vector<int> squeeze_axes(diff);
std::iota(squeeze_axes.begin(), squeeze_axes.end(), 0);
auto reduce_axes = squeeze_axes;
for (int i = diff; i < cotan.ndim(); ++i) {
if (shape[i - diff] != cotan.shape(i)) {
reduce_axes.push_back(i);
}
}
return {squeeze(sum(cotan, reduce_axes, true, s), squeeze_axes, s)};
}
std::vector<array> Broadcast::vjp(
const std::vector<array>& primals,
const std::vector<array>& cotangents,
const std::vector<int>&,
const std::vector<array>&) {
return broadcast_vjp(primals[0], cotangents[0], stream());
}
std::vector<array> Broadcast::jvp(
const std::vector<array>& primals,
const std::vector<array>& tangents,
const std::vector<int>& argnums) {
return {array(
shape_,
tangents[0].dtype(),
std::make_shared<Broadcast>(stream(), shape_),
tangents)};
}
std::pair<std::vector<array>, std::vector<int>> Broadcast::vmap(
const std::vector<array>& inputs,
const std::vector<int>& axes) {
auto ax = axes[0];
auto& in = inputs[0];
if (ax >= 0) {
int diff = shape_.size() - in.ndim() + 1;
assert(diff >= 0);
shape_.insert(shape_.begin() + ax + diff, in.shape(ax));
ax += diff;
}
return {{broadcast_to(in, shape_, stream())}, {ax}};
}
bool Broadcast::is_equivalent(const Primitive& other) const {
const Broadcast& b_other = static_cast<const Broadcast&>(other);
return shape_ == b_other.shape_;
}
Shape Broadcast::output_shape(const std::vector<array>& inputs) {
auto shape = inputs[0].shape();
for (int i = 1; i < inputs.size(); ++i) {
shape = broadcast_shapes(shape, inputs[i].shape());
}
return shape;
}
std::vector<Shape> Broadcast::output_shapes(const std::vector<array>& inputs) {
if (inputs.size() < 2) {
if (broadcast_shapes(inputs[0].shape(), shape_) != shape_) {
throw std::invalid_argument(
"[Broadcast] Unable to infer broadcast shape");
}
return {shape_};
}
return {output_shape(inputs)};
};
std::vector<array> BroadcastAxes::vjp(
const std::vector<array>& primals,
const std::vector<array>& cotangents,
const std::vector<int>&,
const std::vector<array>&) {
return broadcast_vjp(primals[0], cotangents[0], stream());
}
std::vector<array> BroadcastAxes::jvp(
const std::vector<array>& primals,
const std::vector<array>& tangents,
const std::vector<int>& argnums) {
return {array(
output_shape(primals, ignore_axes_),
tangents[0].dtype(),
std::make_shared<BroadcastAxes>(stream(), ignore_axes_),
tangents)};
}
std::pair<std::vector<array>, std::vector<int>> BroadcastAxes::vmap(
const std::vector<array>& inputs,
const std::vector<int>& axes) {