Repository navigation
Expand file tree
/
Copy pathtransforms.cpp
More file actions
1221 lines (1095 loc) · 38.4 KB
/
Copy pathtransforms.cpp
File metadata and controls
1221 lines (1095 loc) · 38.4 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.
#include <algorithm>
#include <deque>
#include <future>
#include <numeric>
#include <ranges>
#include <set>
#include <sstream>
#include <stack>
#include <unordered_map>
#include "mlx/backend/cpu/eval.h"
#include "mlx/backend/gpu/eval.h"
#include "mlx/fence.h"
#include "mlx/memory.h"
#include "mlx/ops.h"
#include "mlx/primitives.h"
#include "mlx/scheduler.h"
#include "mlx/transforms.h"
#include "mlx/transforms_impl.h"
#include "mlx/utils.h"
namespace mlx::core {
namespace {
#ifndef NDEBUG
// Throw if a primitive did not set the data of each output.
void check_outputs_have_data(const array& arr) {
for (auto& out : arr.outputs()) {
if (!out.data_shared_ptr()) {
std::ostringstream msg;
msg << "[" << arr.primitive().name() << "] Output with shape "
<< out.shape() << " has no data after eval.";
throw std::runtime_error(msg.str());
}
}
}
#endif
// Get the stream of the first array that has a primitive, else the default.
StreamOrDevice find_stream(const std::vector<array>& arrays) {
for (auto& a : arrays) {
if (a.has_primitive()) {
return a.primitive().stream();
}
}
return std::monostate{};
}
StreamOrDevice find_stream(
const std::vector<array>& arrays1,
const std::vector<array>& arrays2) {
auto s = find_stream(arrays1);
if (!std::holds_alternative<std::monostate>(s)) {
return s;
}
return find_stream(arrays2);
}
array make_tracer(const array& p, StreamOrDevice fallback_stream) {
// A computed primal only needs its own identity: share its buffer so the
// trace adds no node and no stream for it. An active tracer from an enclosing
// transform still needs the Copy below to link the traces.
if (!p.is_tracer() && !p.has_primitive() && p.is_available()) {
array out(p.shape(), p.dtype(), nullptr, {});
out.copy_shared_buffer(p);
out.set_status(array::Status::available);
out.set_tracer(true);
return out;
}
// If the primal is a stale Copy from a previous transform call (not an active
// tracer), peel it off to prevent copy-chain accumulation when containers
// feed tracers back.
auto source = p;
if (!p.is_tracer() && p.has_primitive() && !p.inputs().empty()) {
auto& prim = p.primitive();
if (typeid(prim) == typeid(Copy)) {
source = p.inputs()[0];
}
}
// Create a tracer copy of a primal for use in vjp/jvp.
auto s = p.has_primitive() ? StreamOrDevice(p.primitive().stream())
: fallback_stream;
auto out = copy(source, s);
out.set_tracer(true);
return out;
}
auto get_inputs(auto& a) {
size_t count = a.inputs().size();
if (a.has_primitive()) {
// For CustomTransforms, trailing inputs are outputs.
auto& p = a.primitive();
if (typeid(p) == typeid(CustomTransforms)) {
count -= a.outputs().size();
}
}
return std::views::take(a.inputs(), count);
}
} // namespace
/* This class is only meant to be used in eval
* for synchronizing with the main thread. */
class Synchronizer : public Primitive {
public:
explicit Synchronizer(Stream stream) : Primitive(stream) {}
void eval_cpu(const std::vector<array>&, std::vector<array>&) override {}
void eval_gpu(const std::vector<array>&, std::vector<array>&) override {}
DEFINE_NAME(Synchronize);
};
// Initialize the static tracing members from transforms_impl.h
//
// These are used to implement the in_tracing() function the returns true if we
// are currently under a function transformation and the retain_graph()
// function which returns true if we are forced to retain the graph during
// evaluation. They are thread_local since a trace belongs to the thread that
// runs it, so that concurrent transforms on different threads do not race on
// shared tracing state.
std::vector<std::pair<char, char>>& detail::InTracing::trace_stack() {
static thread_local std::vector<std::pair<char, char>> trace_stack_;
return trace_stack_;
}
int& detail::InTracing::grad_counter() {
static thread_local int grad_counter_{0};
return grad_counter_;
}
int& detail::InExportTracing::counter() {
static thread_local int counter_;
return counter_;
}
int& detail::RetainGraph::tracing_counter() {
static thread_local int tracing_counter_{0};
return tracing_counter_;
}
int& detail::InBackward::counter() {
static thread_local int counter_{0};
return counter_;
}
array eval_impl(std::vector<array> outputs, bool async) {
std::deque<array> tape;
// Make an effort to choose a good output stream, and only create the default
// stream when there is no other choice.
Stream stream = [&outputs]() {
for (auto& o : outputs) {
if (o.status() == array::Status::unscheduled && o.has_primitive()) {
return o.primitive().stream();
}
}
return default_stream(default_device());
}();
struct FenceInfo {
int stream_index;
bool cross_device;
uint32_t value{0};
};
std::unordered_map<uintptr_t, FenceInfo> needs_fence;
auto synchronizer = array(
{}, bool_, std::make_shared<Synchronizer>(stream), std::move(outputs));
// Stream fences for inter-stream synchronization
std::unordered_map<uint32_t, Fence> fences;
// Stream events for synchronization after eval
std::unordered_map<uint32_t, Event> events;
{
auto e = Event{stream};
e.set_value(1);
synchronizer.attach_event(e);
events.emplace(stream.index, std::move(e));
}
{
// Record the degree of each input
std::unordered_map<std::uintptr_t, int> cache;
std::stack<std::pair<std::reference_wrapper<array>, int>> dfs;
dfs.emplace(synchronizer, 0);
while (!dfs.empty()) {
auto& [a_ref, idx] = dfs.top();
auto& a = a_ref.get();
if (idx < a.inputs().size()) {
// Add an input, and continue
auto& in = a.inputs()[idx++];
if (in.status() == array::Status::unscheduled) {
if (async && in.is_tracer()) {
throw std::invalid_argument(
"[async_eval] Not allowed inside a graph transformation.");
}
if (!in.has_primitive()) {
if (in.is_tracer()) {
throw std::invalid_argument(
"[eval] Attempting to eval an array during function"
" transformations like compile or vmap is not allowed.");
}
throw std::runtime_error(
"[eval] Attempting to eval an array without a primitive.\n"
"If you are compiling a function, make sure all the inputs "
"and outputs are captured:\n"
"https://ml-explore.github.io/mlx/build/html/usage/compile.html#pure-functions.\n"
"If you are not using compile, this may be a bug. "
"Please file an issue here:\n"
"https://github.com/ml-explore/mlx/issues.");
}
if (a.primitive().stream() != in.primitive().stream()) {
bool device_switch =
a.primitive().stream().device != in.primitive().stream().device;
auto [it, inserted] = needs_fence.emplace(
in.id(),
FenceInfo{in.primitive().stream().index, device_switch});
if (!inserted) {
it->second.cross_device |= device_switch;
}
}
}
// All siblings have the same degree
auto cache_it = cache.find(in.id());
if (cache_it == cache.end()) {
dfs.emplace(in, 0);
cache.insert({in.id(), 1});
for (auto& s : in.siblings()) {
cache.insert({s.id(), 1});
}
} else {
cache_it->second++;
for (auto& s : in.siblings()) {
cache[s.id()]++;
}
}
continue;
}
if ((a.status() != array::Status::unscheduled) && !a.is_tracer() &&
a.has_primitive()) {
// If the array is evaluated and is no longer a tracer, detach it
a.detach();
}
dfs.pop();
}
// Build the tape in BFS order with a width limit
int max_width = config::get("MLX_BFS_MAX_WIDTH", 20);
dfs = std::stack<std::pair<std::reference_wrapper<array>, int>>();
tape.push_back(synchronizer);
for (int i = 0; !cache.empty() && (i < tape.size() || !dfs.empty());) {
auto& a = (i >= tape.size()) ? dfs.top().first.get() : tape[i];
int j = 0;
if (i >= tape.size()) {
j = dfs.top().second;
dfs.pop();
} else {
i++;
}
for (; j < a.inputs().size(); ++j) {
auto& in = a.inputs()[j];
if (in.status() != array::Status::unscheduled) {
continue;
}
// If the width limit is exceeded, push the array on the stack
// and go down a level
if ((tape.size() - i) >= max_width) {
dfs.emplace(a, j);
break;
}
auto it = cache.find(in.id());
it->second -= 1;
if (it->second != 0) {
for (auto& s : in.siblings()) {
cache[s.id()] -= 1;
}
continue;
}
// Remove input and siblings from cache
cache.erase(it);
for (auto& s : in.siblings()) {
cache.erase(s.id());
}
tape.push_back(in);
}
}
}
std::set<Stream> open_streams;
try {
while (!tape.empty()) {
auto arr = std::move(tape.back());
tape.pop_back();
auto stream = arr.primitive().stream();
open_streams.insert(stream);
if (async) {
// Lookup corresponding event
auto e = events.find(stream.index);
if (e == events.end()) {
e = events.emplace(stream.index, Event{stream}).first;
}
e->second.set_value(1);
arr.attach_event(e->second);
for (auto& s : arr.siblings()) {
s.attach_event(e->second);
}
}
for (auto& in : arr.inputs()) {
if (auto it = needs_fence.find(in.id()); it != needs_fence.end()) {
// Use fence to wait within a single eval
// Get the input array's stream fence and wait on the
// output arrays stream
auto& info = it->second;
fences.at(info.stream_index).wait(stream, in, info.value);
} else if (in.event().valid()) {
if (in.event().is_signaled()) {
in.detach_event();
} else if (in.event().stream() != stream) {
// Use event to wait across async eval
in.event().wait(stream);
}
}
}
if (arr.primitive().device() == Device::gpu) {
gpu::eval(arr);
} else {
cpu::eval(arr);
}
#ifndef NDEBUG
// The synchronizer has no output data.
if (arr.id() != synchronizer.id()) {
check_outputs_have_data(arr);
}
#endif
scheduler::wait_for_capacity(open_streams);
auto maybe_update_fence =
[&fences, &needs_fence, stream](const array& a) {
if (auto nf = needs_fence.find(a.id()); nf != needs_fence.end()) {
auto it = fences.find(stream.index);
if (it == fences.end()) {
it = fences.emplace(stream.index, Fence{stream}).first;
}
nf->second.value =
it->second.update(stream, a, nf->second.cross_device);
}
};
arr.set_status(array::Status::evaluated);
// TODO Maybe always want the fence coherent kernel in the same cbuf
// as the other kernels?
maybe_update_fence(arr);
for (auto& sib : arr.siblings()) {
sib.set_status(array::Status::evaluated);
maybe_update_fence(sib);
}
if (!arr.is_tracer()) {
arr.detach();
}
}
} catch (...) {
// A primitive threw from inside its eval (e.g. argument validation in
// eval_gpu, or a JIT compile failure). Arrays evaluated earlier in this
// tape are already marked evaluated, but their kernels sit in pending
// command buffers that only the epilogue below would commit, and events
// attached during this eval would never be signaled. Left that way, a
// later read of an affected array returns an unwritten buffer or blocks
// forever. Signal the events and flush the touched streams, then let the
// exception propagate.
for (auto& [idx, e] : events) {
try {
auto es = e.stream();
e.signal(es);
open_streams.insert(es);
} catch (...) {
}
}
// Commit GPU streams before the wait.
for (auto& s : open_streams) {
if (s.device == Device::gpu) {
try {
gpu::finalize(s);
} catch (...) {
}
}
}
for (auto& s : open_streams) {
try {
synchronize(s);
} catch (...) {
// Preserve the original exception.
}
}
throw;
}
// Signal the event in its stream
for (auto& s : open_streams) {
if (auto e = events.find(s.index); e != events.end()) {
e->second.signal(s);
}
if (s.device == Device::gpu) {
gpu::finalize(s);
}
}
return synchronizer;
}
void async_eval(std::vector<array> outputs) {
if (outputs.empty()) {
return;
}
if (std::none_of(outputs.begin(), outputs.end(), [](array& x) {
return x.status() == array::Status::unscheduled;
})) {
return;
}
eval_impl(std::move(outputs), true);
}
void eval(std::vector<array> outputs) {
if (outputs.empty()) {
return;
}
if (std::none_of(outputs.begin(), outputs.end(), [](array& x) {
return x.status() == array::Status::unscheduled;
})) {
for (auto& x : outputs) {
x.wait();
}
return;
}
eval_impl(std::move(outputs), false).wait();
}
std::pair<std::vector<array>, std::vector<array>> vjp(
const std::function<std::vector<array>(const std::vector<array>&)>& fun,
const std::vector<array>& primals,
const std::vector<array>& cotans,
const std::vector<int>& argnums) {
// Set the global tracing flag.
detail::InTracing in_tracing{false, true};
// Make tracers from given primals
auto fallback_stream = find_stream(primals, cotans);
std::vector<array> primals_;
for (auto& p : primals) {
primals_.push_back(make_tracer(p, fallback_stream));
}
// Pass tracer primals through the function
// Any variables that depend on the primals are marked as tracers
auto outputs = fun(primals_);
// Map outputs to passed cotans while ignoring the outputs
// that have stop_gradient called on them
int cotan_index = 0;
std::vector<std::pair<int, int>> output_cotan_pairs;
for (int i = 0; i < outputs.size(); ++i) {
auto& out = outputs[i];
if (out.has_primitive()) {
if (auto& p = out.primitive(); typeid(p) == typeid(StopGradient)) {
continue;
}
}
if (cotan_index >= cotans.size()) {
std::ostringstream msg;
msg << "[vjp] Number of outputs to compute gradients for ("
<< outputs.size() << ") does not match number of cotangents ("
<< cotans.size() << ").";
throw std::invalid_argument(msg.str());
}
if (out.shape() != cotans[cotan_index].shape()) {
std::ostringstream msg;
msg << "[vjp] Output shape " << out.shape()
<< " does not match cotangent shape " << cotans[cotan_index].shape()
<< ".";
if (outputs.size() == 1 && out.size() == 1) {
msg << " If you are using grad your function must return a scalar.";
}
throw std::invalid_argument(msg.str());
}
output_cotan_pairs.emplace_back(i, cotan_index++);
}
// Topologically sort the compute graph, add graph nodes
// to the tape which need a gradient.
SmallUnorderedSet<std::uintptr_t> cache;
SmallUnorderedSet<std::uintptr_t> calc_grad;
for (int i = 0, j = 0; i < primals_.size(); ++i) {
auto& primal = primals_[i];
primal.set_tracer(false);
cache.insert(primal.id());
if (j < argnums.size() && argnums[j] == i) {
j++;
calc_grad.insert(primal.id());
}
}
std::vector<array> tape;
std::function<void(array&)> recurse;
recurse = [&](auto& a) {
// Check if visited and add to cache if not
if (auto inserted = cache.insert(a.id()); !inserted.second) {
return;
}
a.set_tracer(false);
for (auto& s : a.siblings()) {
s.set_tracer(false);
cache.insert(s.id());
}
std::ranges::for_each(get_inputs(a), recurse);
// Stop grad
if (a.has_primitive()) {
if (auto& p = a.primitive(); typeid(p) == typeid(StopGradient)) {
return;
}
}
// Calculate gradient if any inputs require gradient
for (auto& input : get_inputs(a)) {
if (calc_grad.find(input.id()) != calc_grad.end()) {
tape.push_back(a);
calc_grad.insert(a.id());
for (auto& s : a.siblings()) {
calc_grad.insert(s.id());
}
break;
}
}
};
std::ranges::for_each(outputs, recurse);
// Run the tape backwards, computing vector-jacobian
// products for each primitive
detail::InBackward in_backward;
std::unordered_map<std::uintptr_t, array> cotan_map;
for (auto [out_idx, cotan_idx] : output_cotan_pairs) {
auto& o = outputs[out_idx];
auto s = o.has_primitive() ? o.primitive().stream()
: default_stream(default_device());
cotan_map.insert({o.id(), astype(cotans[cotan_idx], o.dtype(), s)});
}
for (auto it = tape.rbegin(); it != tape.rend(); ++it) {
auto& a = *it;
// Get the arguments whose gradients are needed
std::vector<int> argnums;
for (int i = 0; i < a.inputs().size(); ++i) {
if (calc_grad.find(a.inputs()[i].id()) != calc_grad.end()) {
argnums.push_back(i);
}
}
// Check if any of the array or its siblings have cotangents,
// if not, we can skip this primitive
auto outputs = a.outputs();
bool has_cotans =
std::any_of(outputs.cbegin(), outputs.cend(), [&cotan_map](auto& s) {
return cotan_map.find(s.id()) != cotan_map.end();
});
if (!has_cotans) {
continue;
}
auto s = a.primitive().stream();
std::vector<array> cotangents{};
for (auto& o : outputs) {
if (auto cotan_it = cotan_map.find(o.id()); cotan_it != cotan_map.end()) {
cotangents.push_back(cotan_map.extract(cotan_it).mapped());
} else {
cotangents.push_back(zeros_like(o, s));
}
}
std::vector<array> vjps;
{
detail::RetainGraph retain;
vjps = a.primitive().vjp(a.inputs(), cotangents, argnums, outputs);
}
// Accumulate the vector-jacobian products for each input
for (int i = 0; i < argnums.size(); ++i) {
auto in_id = a.inputs()[argnums[i]].id();
if (auto cotan_it = cotan_map.find(in_id); cotan_it != cotan_map.end()) {
cotan_it->second = add(cotan_it->second, vjps[i], s);
} else {
cotan_map.insert({in_id, vjps[i]});
}
}
}
std::vector<array> vjps;
for (auto arg : argnums) {
auto& primal = primals_[arg];
if (auto cotan_it = cotan_map.find(primal.id());
cotan_it != cotan_map.end()) {
vjps.push_back(cotan_it->second);
} else {
auto s = primal.has_primitive()
? StreamOrDevice(primal.primitive().stream())
: fallback_stream;
vjps.push_back(zeros_like(primal, s));
}
}
return {outputs, vjps};
}
std::pair<std::vector<array>, std::vector<array>> vjp(
const std::function<std::vector<array>(const std::vector<array>&)>& fun,
const std::vector<array>& primals,
const std::vector<array>& cotans) {
std::vector<int> argnums(primals.size());
std::iota(argnums.begin(), argnums.end(), 0);
return vjp(fun, primals, cotans, argnums);
}
std::pair<array, array> vjp(
const std::function<array(const array&)>& fun,
const array& primal,
const array& cotan) {
auto vec_fun = [fun](const std::vector<array>& inputs) {
return std::vector<array>{fun(inputs[0])};
};
auto [outputs, vjps] = vjp(vec_fun, {primal}, {cotan});
return {outputs[0], vjps[0]};
}
std::pair<std::vector<array>, std::vector<array>> jvp(
const std::function<std::vector<array>(const std::vector<array>&)>& fun,
const std::vector<array>& primals,
const std::vector<array>& tangents) {
// Set the global tracing flag.
detail::InTracing in_tracing{false, true};
if (primals.size() != tangents.size()) {
throw std::invalid_argument(
"[jvp] Number of inputs does not match number of tangents.");
}
for (int i = 0; i < primals.size(); ++i) {
if (primals[i].shape() != tangents[i].shape()) {
throw std::invalid_argument(
"[jvp] Input shape does not match shape of tangent.");
}
}
auto fallback_stream = find_stream(primals, tangents);
std::vector<array> primals_;
for (auto& p : primals) {
primals_.push_back(make_tracer(p, fallback_stream));
}
auto outputs = fun(primals_);
// Topologically sort the compute graph, record outputs
// in the tape if a gradient is needed.
SmallUnorderedSet<std::uintptr_t> cache;
SmallUnorderedSet<std::uintptr_t> calc_grad;
for (auto& primal : primals_) {
primal.set_tracer(false);
calc_grad.insert(primal.id());
cache.insert(primal.id());
}
std::vector<array> tape;
std::function<void(array&)> recurse;
recurse = [&](auto& a) {
// Check if visited and add to cache if not
if (auto inserted = cache.insert(a.id()); !inserted.second) {
return;
}
a.set_tracer(false);
for (auto& s : a.siblings()) {
s.set_tracer(false);
cache.insert(s.id());
}
std::ranges::for_each(get_inputs(a), recurse);
// Stop grad
if (a.has_primitive()) {
if (auto& p = a.primitive(); typeid(p) == typeid(StopGradient)) {
return;
}
}
// Calculate gradient if any inputs require gradient
for (auto& input : get_inputs(a)) {
if (calc_grad.find(input.id()) != calc_grad.end()) {
tape.push_back(a);
calc_grad.insert(a.id());
for (auto& s : a.siblings()) {
calc_grad.insert(s.id());
}
break;
}
}
};
std::ranges::for_each(outputs, recurse);
std::unordered_map<std::uintptr_t, array> tan_map;
for (int i = 0; i < primals_.size(); ++i) {
tan_map.insert({primals_[i].id(), tangents[i]});
}
for (auto& a : tape) {
// Get the arguments used in the jvp
std::vector<int> argnums;
std::vector<array> tangents;
for (int i = 0; i < a.inputs().size(); ++i) {
if (auto it = tan_map.find(a.inputs()[i].id()); it != tan_map.end()) {
argnums.push_back(i);
tangents.push_back(it->second);
}
}
auto jvps = a.primitive().jvp(a.inputs(), tangents, argnums);
auto outputs = a.outputs();
// A primitive's jvp returns one tangent per output
assert(jvps.size() <= outputs.size());
for (int i = 0; i < jvps.size(); ++i) {
tan_map.insert({outputs[i].id(), jvps[i]});
}
}
std::vector<array> jvps;
for (auto& out : outputs) {
if (auto it = tan_map.find(out.id()); it != tan_map.end()) {
jvps.push_back(it->second);
} else {
auto s = out.has_primitive() ? out.primitive().stream()
: default_stream(default_device());
jvps.push_back(zeros_like(out, s));
}
}
return {outputs, jvps};
}
std::pair<array, array> jvp(
const std::function<array(const array&)>& fun,
const array& primal,
const array& tangent) {
auto vec_fun = [fun](const std::vector<array>& inputs) {
return std::vector<array>{fun(inputs[0])};
};
auto [outputs, jvps] = jvp(vec_fun, {primal}, {tangent});
return {outputs[0], jvps[0]};
}
ValueAndGradFn value_and_grad(
const std::function<std::vector<array>(const std::vector<array>&)>& fun,
const std::vector<int>& argnums) {
if (argnums.empty()) {
throw std::invalid_argument("[grad] Must specify at least one argument.");
}
return [fun, argnums](const std::vector<array>& inputs) {
std::set<int> args;
for (auto& arg : argnums) {
args.insert(arg < 0 ? arg + inputs.size() : arg);
}
if (args.size() != argnums.size()) {
throw std::invalid_argument(
"[grad] Repeat argument number not allowed in grad.");
}
if (*args.begin() < 0 || *args.rbegin() >= inputs.size()) {
std::ostringstream msg;
msg << "[grad] Invalid argument number for function with "
<< inputs.size() << " inputs.";
throw std::invalid_argument(msg.str());
}
std::vector<int> sorted_argnums(args.begin(), args.end());
auto gfun = [&fun](const std::vector<array>& inputs) {
auto outputs = fun(inputs);
for (int i = 1; i < outputs.size(); i++) {
auto& out = outputs[i];
auto s = out.has_primitive() ? out.primitive().stream()
: default_stream(default_device());
outputs[i] = stop_gradient(out, s);
}
return outputs;
};
// Set the incoming gradient to float32, vjp will cast it to the output type
auto [outputs, grads] = vjp(gfun, inputs, {array(1.0f)}, sorted_argnums);
return std::make_pair(outputs, grads);
};
}
namespace detail {
std::pair<std::vector<array>, std::vector<array>> vmap_trace(
const std::function<std::vector<array>(const std::vector<array>&)>& fun,
const std::vector<array>& inputs,
const std::vector<int>& in_axes) {
// Set the global tracing flag.
detail::InTracing in_tracing;
if (in_axes.size() != inputs.size()) {
std::stringstream ss;
ss << "[vmap] The number of in axes (" << in_axes.size()
<< ") must match the number of inputs (" << inputs.size() << ").";
throw std::invalid_argument(ss.str());
}
// Some error checking and get the vmap axis size
size_t vmap_ax_size;
for (int i = 0; i < inputs.size(); ++i) {
if (in_axes[i] != -1) {
if (inputs[i].ndim() == 0) {
throw std::invalid_argument(
"[vmap] Cannot vmap an input with zero dimensions.");
}
if (in_axes[i] > inputs[i].ndim()) {
std::ostringstream msg;
msg << "[vmap] Axis " << in_axes[i] << " invalid for input with "
<< inputs[i].ndim() << " dimensions.";
throw std::invalid_argument(msg.str());
}
vmap_ax_size = inputs[i].shape(in_axes[i]);
}
}
// Check that all vmapped axes have the same size
for (int i = 0; i < inputs.size(); ++i) {
if (in_axes[i] != -1) {
if (size_t in_ax = inputs[i].shape(in_axes[i]); vmap_ax_size != in_ax) {
std::ostringstream msg;
msg << "[vmap] Inconsistent axis sizes: " << in_ax << " and "
<< vmap_ax_size << ".";
throw std::invalid_argument(msg.str());
}
}
}
// Run the function on placeholder inputs
// to get the original graph
std::vector<array> s_inputs;
for (int i = 0; i < inputs.size(); ++i) {
if (in_axes[i] != -1) {
auto shape = inputs[i].shape();
shape.erase(shape.begin() + in_axes[i]);
array in(shape, inputs[i].dtype(), nullptr, {});
s_inputs.push_back(in);
s_inputs.back().set_tracer(true);
} else {
s_inputs.push_back(inputs[i]);
}
}
return {s_inputs, fun(s_inputs)};
}
std::vector<array> vmap_replace(
const std::vector<array>& inputs,
const std::vector<array>& s_inputs,
const std::vector<array>& s_outputs,
const std::vector<int>& in_axes,
const std::vector<int>& out_axes) {
if (out_axes.size() != s_outputs.size()) {
std::stringstream msg;
msg << "[vmap] The number of out axes (" << out_axes.size()
<< ") must match the number of outputs (" << s_outputs.size() << ").";
throw std::invalid_argument(msg.str());
}
int vmap_size = -1;
for (int i = 0; i < inputs.size(); ++i) {
if (in_axes[i] >= 0) {
vmap_size = inputs[i].shape(in_axes[i]);
break;
}
}
if (vmap_size == -1) {
throw std::invalid_argument("At least one of in_axes must be non-None.");
}
std::unordered_map<std::uintptr_t, std::pair<array, int>> tmap;
SmallUnorderedSet<std::uintptr_t> needs_vmap;
SmallUnorderedSet<std::uintptr_t> cache;
for (int i = 0; i < s_inputs.size(); ++i) {
auto in = s_inputs[i];
if (in_axes[i] != -1) {
tmap.insert({in.id(), {inputs[i], in_axes[i]}});
needs_vmap.insert(in.id());
in.set_tracer(false);
}
cache.insert(in.id());
}
// Topologically sort the graph
std::vector<array> tape;
std::function<void(const array&)> recurse;
recurse = [&](const array& a) {
auto id = a.id();
if (cache.find(id) != cache.end()) {
return;
}
cache.insert(id);
for (auto& s : a.siblings()) {
cache.insert(s.id());
}
// Recurse on inputs
std::ranges::for_each(get_inputs(a), recurse);
// If any input needs a vmap, then the outputs also need
// a vmap
for (auto& input : get_inputs(a)) {
if (needs_vmap.find(input.id()) != needs_vmap.end()) {
tape.push_back(a);
tape.back().set_tracer(false);
needs_vmap.insert(a.id());
for (auto s : a.siblings()) {
needs_vmap.insert(s.id());
s.set_tracer(false);
}
break;
}
}
};
for (auto& out : s_outputs) {
if (out.has_primitive()) {
recurse(out);
}
}
// Transform each primitive in the graph with
// its vmap implementation
for (auto& a : tape) {
std::vector<array> v_inputs;
std::vector<int> v_axes;
for (auto& in : a.inputs()) {
auto map_it = tmap.find(in.id());
if (map_it != tmap.end()) {
v_inputs.push_back(map_it->second.first);
v_axes.push_back(map_it->second.second);
} else {
v_inputs.push_back(in);
v_axes.push_back(-1);
}
}
auto [v_outputs, v_out_axes] = a.primitive().vmap(v_inputs, v_axes);
// For each primitive's outputs add its id, the vout id and the vax
auto outputs = a.outputs();
for (int i = 0; i < v_outputs.size(); ++i) {
tmap.insert({outputs[i].id(), {v_outputs[i], v_out_axes[i]}});
}
}
// Populate the outputs and make sure all the output axes are
// in the right place
std::vector<array> outputs;
for (int i = 0; i < s_outputs.size(); ++i) {
auto& s_out = s_outputs[i];
StreamOrDevice s =
s_out.has_primitive() ? s_out.primitive().stream() : StreamOrDevice{};
if (auto map_it = tmap.find(s_out.id()); map_it != tmap.end()) {
auto& [out, vdim] = map_it->second;
if (vdim != out_axes[i]) {
if (out_axes[i] >= out.ndim()) {
std::ostringstream msg;
msg << "[vmap] Axis " << out_axes[i] << " invalid for output with "
<< out.ndim() << " dimensions.";
throw std::invalid_argument(msg.str());
}
out = moveaxis(out, vdim, out_axes[i], s);
}
outputs.push_back(out);
} else {
// When the output has no input dependencies
// use the size of the vmapped axis in the inputs to expand the output
array output = expand_dims(s_outputs[i], out_axes[i], s);