forked from jrk/gradient-halide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Derivative.cpp
1993 lines (1878 loc) · 90.1 KB
/
Derivative.cpp
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
#include "Derivative.h"
#include "BoundaryConditions.h"
#include "DerivativeUtils.h"
#include "Error.h"
#include "FindCalls.h"
#include "IREquality.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "RealizationOrder.h"
#include "Simplify.h"
#include "Solve.h"
#include "Substitute.h"
#include <cmath>
#include <iostream>
namespace Halide {
namespace Internal {
bool check_opname(const std::string &op_name,
const std::string &func_name) {
return op_name == (func_name + "_f16") ||
op_name == (func_name + "_f32") ||
op_name == (func_name + "_f64");
};
/** Compute derivatives through reverse accumulation
*/
class ReverseAccumulationVisitor : public IRVisitor {
public:
using IRVisitor::visit;
void propagate_adjoints(const Func &output,
const Func &adjoint,
const std::vector<std::pair<Expr, Expr>> &output_bounds);
std::map<FuncKey, Func> get_adjoint_funcs() const {
return adjoint_funcs;
}
protected:
void visit(const Cast *op);
void visit(const Variable *op);
void visit(const Add *op);
void visit(const Sub *op);
void visit(const Mul *op);
void visit(const Div *op);
void visit(const Min *op);
void visit(const Max *op);
void visit(const Let *op);
void visit(const Select *op);
void visit(const Call *op);
private:
void accumulate(const Expr &stub, const Expr &adjoint);
// For each expression, we store the accumulated adjoints expression
std::map<const BaseExprNode *, Expr> expr_adjoints;
// For each function and each update, we store the accumulated adjoints func
std::map<FuncKey, Func> adjoint_funcs;
// Let variables and their mapping
std::map<std::string, Expr> let_var_mapping;
std::vector<std::string> let_variables;
// Bounds of functions
std::map<std::string, Box> func_bounds;
// Current function that scatters its adjoints to its dependencies
Func current_func;
// Current update of the function
int current_update_id;
// We compute the derivatives in several passes.
// Sometimes we don't want to propagate through Halide function calls
bool is_forward_overwrite_detection_phase;
bool is_self_referencing_phase;
// Is the current function update a non overwriting scan?
bool is_current_non_overwriting_scan;
// A temporary flag for checking the derivatives
// to self reference of a Halide function is 1 or not
// Used in forward overwrite detection phase
Tuple self_reference_adjoint = Tuple(Expr());
std::vector<std::vector<Expr>> self_reference_args;
};
void ReverseAccumulationVisitor::propagate_adjoints(
const Func &output,
const Func &adjoint,
const std::vector<std::pair<Expr, Expr>> &output_bounds) {
// Topologically sort the functions
std::map<std::string, Function> env = find_transitive_calls(output.function());
std::vector<std::string> order =
realization_order({ output.function() }, env).first;
std::vector<Func> funcs;
funcs.reserve(order.size());
// Internal::debug(0) << "Sorted Func list:" << "\n";
// for (const auto &func_name : order) {
// Internal::debug(0) << " . " << func_name << "\n";
// }
for (const auto &func_name : order) {
Func func(env[func_name]);
funcs.push_back(Func(env[func_name]));
}
internal_assert(funcs.size() > 0);
// If the derivatives depend on an in-place overwrite,
// and the self reference adjoint is not 0 or 1,
// throws an error to the users.
// For example:
//
// f(x) = g(x)
// f(x) = f(x) * f(x)
// f'(x) depends on first f(x)
//
// f(x) = 0
// f(x) = 2 * f(x) + g(r.x)
// g'(r.x) depends on intermediate f'(x)
//
// This is fine because the self reference adjoint is 1:
// f(x) = f(x) + g(r.x)
// (when it's 1 all instances of f(x) have the same adjoint)
//
// The issue is that the self reference to f makes propagation to g
// using the wrong adjoints.
//
// The user should rewrite the above updates to the following.
//
// f_(x, 0) = g(x)
// f_(x, 1) = f_(x, 0) * f_(x, 0)
// f(x) = f_(x, 1)
//
// f_(x, 0) = 0
// f_(x, r.x + 1) = 2 * f_(x, r.x) + g(r.x)
// f(x) = f_(x, r.x.max() + 1)
//
// We can do the rewrite for the users automatically, but it requires
// generating the indirect reference f_, making scheduling these
// functions extremely difficult.
is_forward_overwrite_detection_phase = true;
std::set<FuncKey> non_overwriting_scans;
for (int func_id = 0; func_id < (int) funcs.size(); func_id++) {
const Func &func = funcs[func_id];
current_func = func;
// Precompute the left hand side intervals for each update
// We use this to determine if there's overlaps between the updates
std::vector<Box> boxes;
boxes.reserve(func.num_update_definitions());
for (int update_id = 0;
update_id < func.num_update_definitions(); update_id++) {
const std::vector<Expr> &args = func.update_args(update_id);
std::vector<Interval> intervals;
intervals.reserve(args.size());
for (int arg_id = 0; arg_id < (int) args.size(); arg_id++) {
Scope<Interval> scope;
ReductionDomain rdom = extract_rdom(args[arg_id]);
if (rdom.defined()) {
const std::vector<ReductionVariable> &rvars = rdom.domain();
for (const auto &r : rvars) {
Expr r_max = simplify(r.min + r.extent + 1);
scope.push(r.var, Interval(r.min, r_max));
}
}
Interval interval = bounds_of_expr_in_scope(args[arg_id], scope);
intervals.push_back(interval);
}
boxes.push_back(Box(intervals));
}
for (int update_id = 0;
update_id < func.num_update_definitions(); update_id++) {
// We check for two criteria:
// 1. We check if the derivatives
// depend on previous update, and if that particular
// value has been overwritten.
// 2. For updates of f with reduction variables,
// unless the derivatives to self reference is 1 or 0,
// we make sure overwritten f' is not used by others.
// We conservatively detect this by distinguish two cases:
// a. If f' is always never being overwritten for all instances of
// the reduction variables
// b. Or if f' is never used by others except itself.
//
// A few examples:
//
// f(x) = f(x) + g(r.x) // good, the self update derivative is 1
//
// f(x) = 2 * f(x) // good, although the self update derivative is 2,
// there's no reduction variables
//
// f(x) = 2 * f(x) + g(r.x) // bad, f'(x) will be used for updating
// g(r.x) but will be overwritten
//
// f(x) = f(x) * f(x) // bad, derivative of f(x) depends on previous value
// which has been overwritten
//
// f(x, 0) = ...
// f(x, 1) = f(x, 0) * f(x, 0) // good, although the derivative depends on
// // previous value, the updates do not overlap
//
// f(x, r.x + 1) = 2 * f(x, r.x) + g(r.x) // good,
// // f' is never overwritten
//
// f(x, y) = g(x)
// f(x, r.x + 1) = f(x, r.x) * f(x, r.x); // bad, the derivatives
// depend on previous updates
//
// f(x, y, 0) = g(x)
// f(x, r.x + 1, 1) = f(x, r.x, 0) * f(x, r.x, 0); // good
//
// f(x, r.x + 1, r.y + 1) = 2 * f(x, r.x, r.y) + g(r.x) // good
//
// f(x, r.x + 1, r.x + r.y + 1) = 2 * f(x, r.x, r.y) + g(r.x) // bad
std::vector<Expr> zeros;
Tuple rhs_tuple = func.values();
zeros.reserve(rhs_tuple.size());
for (int i = 0; i < (int) rhs_tuple.size(); i++) {
zeros.push_back(make_const(rhs_tuple[i].type(), 0.0));
}
self_reference_adjoint = Tuple(zeros);
self_reference_args.clear();
// Checking 1. here:
// Take the derivative at expression level, the results are
// stored in expr_adjoints
std::vector<Expr> expr_list;
Tuple update_tuple = func.update_values(update_id);
std::vector<const BaseExprNode *> output_exprs;
const std::vector<Expr> &update_tuple_vector = update_tuple.as_vector();
for (const auto &expr : update_tuple_vector) {
std::vector<Expr> value_expr_list = sort_expressions(expr);
expr_list.insert(expr_list.end(),
value_expr_list.begin(), value_expr_list.end());
output_exprs.push_back((const BaseExprNode *) expr_list.back().get());
}
// TODO: replace let_var_mapping with Scope
// Gather let variables
let_var_mapping.clear();
let_variables.clear();
for (auto it = expr_list.begin(); it != expr_list.end(); it++) {
Expr expr = *it;
if (expr.get()->node_type == IRNodeType::Let) {
const Let *op = expr.as<Let>();
// Assume Let variables are unique
assert(let_var_mapping.find(op->name) == let_var_mapping.end());
let_var_mapping[op->name] = op->value;
let_variables.push_back(op->name);
}
}
// Set the output adjoint to 1
// We're not really propagating adjoints, just checking if there's
// self references
for (int i = 0; i < (int) output_exprs.size(); i++) {
expr_adjoints[output_exprs[i]] = 1.f;
}
// Traverse the expressions in reverse order
for (auto it = expr_list.rbegin(); it != expr_list.rend(); it++) {
it->accept(this);
}
auto error = [&]() {
user_error << "Can't take the gradients of " << func.name() << ", which depend on intermediate values. "
<< "Use a scan (which saves intermediate results) instead.";
};
// For each adjoint expression depositing to a function or image,
// check if it references to the function
bool adjoints_used_by_others = false;
for (const auto &it : expr_adjoints) {
Expr target_expr(it.first);
bool is_target_func_or_buffer = false;
const Call *call_op = target_expr.as<Call>();
if (call_op != nullptr) {
is_target_func_or_buffer =
call_op->call_type == Call::Image ||
call_op->call_type == Call::Halide;
}
Expr expr = it.second;
if (is_target_func_or_buffer &&
is_calling_function(func.name(), expr, let_var_mapping)) {
// Self reference might not be bad.
// If we carefully avoid overwriting intermediate values,
// we can still backprop.
// First we check for the pure definition.
// If the pure definition depends on any functions or buffers,
// there is no hope since we will overwrite something
Tuple rhs_tuple = func.values();
for (int tuple_id = 0; tuple_id < (int) rhs_tuple.size();
tuple_id++) {
if (is_calling_function(rhs_tuple[tuple_id], let_var_mapping)) {
error();
}
}
// Now we check all previous updates, see if the left hand
// side arguments overlap.
Box current_box = boxes[update_id];
for (int prev_update_id = 0; prev_update_id < update_id;
prev_update_id++) {
// Gather two boxes from current update and previous update
Box prev_box = boxes[prev_update_id];
internal_assert(current_box.size() == prev_box.size());
// If any of the boxes overlap, we need to throw an error
if (boxes_overlap(current_box, prev_box)) {
error();
}
}
}
if (is_target_func_or_buffer && call_op->name != func.name()) {
adjoints_used_by_others = true;
}
}
expr_adjoints.clear();
// Checking 2. here:
bool all_zero_or_one_self_adjoint = true;
for (int i = 0; i < (int) self_reference_adjoint.size(); i++) {
if (!is_const(self_reference_adjoint[i], 0) &&
!is_const(self_reference_adjoint[i], 1)) {
all_zero_or_one_self_adjoint = false;
break;
}
}
bool has_reduction_var = func.rvars(update_id).size() > 0;
if (!all_zero_or_one_self_adjoint && has_reduction_var) {
// a. is there any instance of reduction variable such that
// the self reference update overwrites itself?
// Or, equivalently, for all possible values of the reduction
// variables, does the self reference update always
// reads from/writes to different locations?
// First we determine the ranges of RDoms for
// and_condition_over_domain
Scope<Interval> varying;
// Loop over lhs & rhs to grab a reduction domain
ReductionDomain r;
const std::vector<Expr> &update_args = func.update_args(update_id);
for (const Expr &expr : update_args) {
r = extract_rdom(expr);
if (r.defined()) {
break;
}
}
if (!r.defined()) {
for (int tuple_id = 0; tuple_id < (int) update_tuple.size();
tuple_id++) {
r = extract_rdom(update_tuple[tuple_id]);
if (r.defined()) {
break;
}
}
}
internal_assert(r.defined());
// Go over all self reference call arguments
bool is_not_overwriting = true;
for (const std::vector<Expr> &self_ref_args : self_reference_args) {
internal_assert(self_ref_args.size() == update_args.size());
Expr not_overwriting_cond = const_false();
for (int arg_id = 0; arg_id < (int) self_ref_args.size(); arg_id++) {
// Are the read from/write to arguments always different?
not_overwriting_cond = simplify(not_overwriting_cond ||
(self_ref_args[arg_id] != update_args[arg_id]));
}
not_overwriting_cond = and_condition_over_domain(
not_overwriting_cond, varying);
// Needs to be true for all self reference
is_not_overwriting = is_not_overwriting &&
can_prove(not_overwriting_cond);
}
// b. Even if the derivative is overwritten, as long as
// we don't use it in this update we are good.
// Otherwise we throw an error
if (!is_not_overwriting && adjoints_used_by_others) {
error();
}
if (is_not_overwriting) {
// This is a non overwriting scan, let's remember it
non_overwriting_scans.insert(FuncKey{ func.name(), update_id });
}
}
}
}
is_forward_overwrite_detection_phase = false;
// Bounds inference
func_bounds = inference_bounds(output, output_bounds);
// Create a stub for each function and each update to accumulate adjoints.
for (int func_id = 0; func_id < (int) funcs.size(); func_id++) {
const Func &func = funcs[func_id];
for (int update_id = -1;
update_id < func.num_update_definitions(); update_id++) {
Func adjoint_func(
func.name() + "_" + std::to_string(update_id + 1) + "_d_def__");
bool is_final_output = func_id == (int) funcs.size() - 1 &&
update_id == func.num_update_definitions() - 1;
std::vector<Var> args = func.args();
for (auto &arg : args) {
if (arg.is_implicit()) {
// Replace implicit variables with non implicit ones
arg = Var();
}
}
if (is_final_output) {
adjoint_func(args) = adjoint(args);
} else {
// Initialize to 0
if (func.values().size() == 1) {
adjoint_func(args) = make_const(func.values()[0].type(), 0.0);
} else {
std::vector<Expr> init(func.values().size());
for (int i = 0; i < (int) init.size(); i++) {
init[i] = make_const(func.values()[i].type(), 0.0);
}
adjoint_func(args) = Tuple(init);
}
}
FuncKey func_key{ func.name(), update_id };
assert(adjoint_funcs.find(func_key) == adjoint_funcs.end());
adjoint_funcs[func_key] = adjoint_func;
}
}
// Also create stubs for buffers referenced by the functions
std::map<std::string, BufferInfo> called_buffers;
for (int func_id = 0; func_id < (int) funcs.size(); func_id++) {
const Func &func = funcs[func_id];
std::map<std::string, BufferInfo> buffers = find_buffer_calls(func);
called_buffers.insert(buffers.begin(), buffers.end());
}
for (const auto &it : called_buffers) {
Func adjoint_func(it.first + "_d__");
std::vector<Var> args;
for (int i = 0; i < it.second.dimension; i++) {
args.push_back(Var());
}
adjoint_func(args) = make_const(it.second.type, 0.0);
FuncKey func_key{ it.first, -1 };
if (adjoint_funcs.find(func_key) != adjoint_funcs.end()) {
user_error << "Naming conflict between buffer and function:" << it.first << "\n";
}
adjoint_funcs[func_key] = adjoint_func;
}
// Traverse functions from producers to consumers for reverse accumulation
for (int func_id = funcs.size() - 1; func_id >= 0; func_id--) {
const Func &func = funcs[func_id];
current_func = func;
FuncKey func_key{ func.name(), func.num_update_definitions() - 1 };
// Set up boundary condition for the last adjoint, for
// non overwriting scans, we delay the boundary condition
// setup since the gradients depend on itself.
auto add_boundary_condition = [&](const FuncKey &func_key) {
Func &adjoint_func = adjoint_funcs[func_key];
const Box &bounds = func_bounds[func.name()];
// Save a pointer to the unbounded def. Useful for scheduling
FuncKey unbounded_func_key{ func.name() + "_unbounded", func_key.second };
adjoint_funcs[unbounded_func_key] = adjoint_func;
if (adjoint_func.values().size() == 1) {
Type type = adjoint_func.values()[0].type();
adjoint_func = BoundaryConditions::constant_exterior(
adjoint_func, make_const(type, 0.0), box_to_vector(bounds),
adjoint_func.name() + "_ce");
} else {
std::vector<Expr> values(adjoint_func.values().size());
for (int i = 0; i < (int) values.size(); i++) {
values[i] = make_const(adjoint_func.values()[i].type(), 0.0);
}
adjoint_func = BoundaryConditions::constant_exterior(
adjoint_func, Tuple(values), box_to_vector(bounds),
adjoint_func.name() + "_ce");
}
};
if (non_overwriting_scans.find(func_key) == non_overwriting_scans.end()) {
add_boundary_condition(func_key);
}
// Traverse from the last update to first
for (int update_id = func.num_update_definitions() - 1;
update_id >= -1; update_id--) {
current_update_id = update_id;
FuncKey func_key{ func.name(), update_id };
Func adjoint_func = adjoint_funcs[func_key];
internal_assert(func_bounds.find(func.name()) != func_bounds.end());
// The propagation of adjoints to self reference goes to
// current update instead of previous if it's a non overwriting scan
is_current_non_overwriting_scan = false;
if (update_id >= 0) {
auto it = non_overwriting_scans.find(func_key);
if (it != non_overwriting_scans.end()) {
is_current_non_overwriting_scan = true;
}
}
// Initialize the next adjoint function by
// propagating the adjoints to next update
// Example:
// f(x) = ...
// f(1) = ... <- we're here
// We have an adjoint for f(1) defined over the whole support of f
// Now we want to initialize for the f(x) update
// Need to propagate back to all x while masking 1
// x -> next_args
// 1 -> update_args
auto mask_previous_update = [&]() {
FuncKey prev_func_key{ func.name(), update_id - 1 };
Func &prev_adjoint_func = adjoint_funcs[prev_func_key];
std::vector<Var> prev_args = prev_adjoint_func.args();
std::vector<Expr> update_args = func.update_args(update_id);
// Replace implicit variables
for (auto &arg : update_args) {
std::set<std::string> implicit_variables =
find_implicit_variables(arg);
for (const auto &var : implicit_variables) {
arg = substitute(var, prev_args[Var::implicit_index(var)], arg);
}
}
// Check if prev_args are the same as update_args
// If they are the same simply set everything to zero
bool is_noop = true;
for (int i = 0; i < (int) prev_args.size(); i++) {
const Variable *update_var = update_args[i].as<Variable>();
if (update_var == nullptr || prev_args[i].name() != update_var->name) {
is_noop = false;
}
}
prev_adjoint_func = Func(prev_adjoint_func.name());
if (!is_noop) {
// f'(x) = adjoint
prev_adjoint_func(prev_args) =
adjoint_funcs[func_key](prev_args);
}
if (func.values().size() == 1) {
Type type = func.values()[0].type();
prev_adjoint_func(update_args) = make_const(type, 0.0);
} else {
std::vector<Expr> init(func.values().size());
for (int i = 0; i < (int) init.size(); i++) {
init[i] = make_const(func.values()[i].type(), 0.0);
}
prev_adjoint_func(update_args) = Tuple(init);
}
};
if (update_id >= 0 && !is_current_non_overwriting_scan) {
// Delay the masking if we're keeping track of intermediate values
// Since in this case we are propagating to current update
// instead of previous update.
mask_previous_update();
}
// Now we want to propagate the derivatives at expression level
// Topologically sort the expressions for each value in the tuple
std::vector<Expr> expr_list;
Tuple rhs_tuple =
update_id < 0 ? func.values() : func.update_values(update_id);
std::vector<const BaseExprNode *> output_exprs;
const std::vector<Expr> &rhs_tuple_vector = rhs_tuple.as_vector();
for (const auto &expr : rhs_tuple_vector) {
std::vector<Expr> value_expr_list = sort_expressions(expr);
expr_list.insert(
expr_list.end(), value_expr_list.begin(), value_expr_list.end());
output_exprs.push_back((const BaseExprNode *) expr_list.back().get());
}
// TODO: replace let_var_mapping with Scope
// Gather let variables
let_var_mapping.clear();
let_variables.clear();
for (auto it = expr_list.begin(); it != expr_list.end(); it++) {
Expr expr = *it;
if (expr.get()->node_type == IRNodeType::Let) {
const Let *op = expr.as<Let>();
// Assume Let variables are unique
assert(let_var_mapping.find(op->name) == let_var_mapping.end());
let_var_mapping[op->name] = op->value;
let_variables.push_back(op->name);
}
}
// Retrieve previously propagated adjoint for the Func,
// apply it to expression adjoints
// f(x) = g(x)
// d_g(x) = d_f(x) * df/dg
std::vector<Expr> update_args;
if (update_id >= 0) {
update_args = func.update_args(update_id);
} else {
update_args.reserve(func.args().size());
Func adjoint_func = adjoint_funcs[func_key];
for (const auto &var : adjoint_func.args()) {
update_args.push_back(var);
}
}
// We propagate in two phases, the first phase only propagates
// to self references, the second phase propagates to the rest
{ // First phase
is_self_referencing_phase = true;
expr_adjoints.clear();
for (int i = 0; i < (int) output_exprs.size(); i++) {
expr_adjoints[output_exprs[i]] =
Call::make(adjoint_funcs[func_key].function(),
update_args, i);
}
// Traverse the expressions in reverse order
for (auto it = expr_list.rbegin(); it != expr_list.rend(); it++) {
// Propagate adjoints
it->accept(this);
}
}
if (is_current_non_overwriting_scan) {
if (update_id == func.num_update_definitions() - 1) {
// Set up the delayed boundary condition now we're done with
// the updates
add_boundary_condition(func_key);
}
// Now, if we detect a non-overwriting scan operation,
// the update of adjoints
// goes to the current function.
// We let the previous adjoint the same as the current one
FuncKey prev_func_key{ func_key.first, func_key.second - 1 };
// Recreate a new adjoint for previous update
Func prev_adjoint;
std::vector<Expr> args;
args.reserve(adjoint_func.args().size());
for (const auto &arg : adjoint_func.args()) {
args.push_back(arg);
}
std::vector<Expr> calls;
calls.reserve(rhs_tuple.size());
for (int i = 0; i < (int) rhs_tuple.size(); i++) {
calls.push_back(Call::make(
adjoint_funcs[func_key].function(), args, i));
}
prev_adjoint(args) = Tuple(calls);
adjoint_funcs[prev_func_key] = prev_adjoint;
mask_previous_update();
}
{ // Second phase
is_self_referencing_phase = false;
expr_adjoints.clear();
for (int i = 0; i < (int) output_exprs.size(); i++) {
expr_adjoints[output_exprs[i]] =
Call::make(adjoint_funcs[func_key].function(),
update_args, i);
}
// Traverse the expressions in reverse order
for (auto it = expr_list.rbegin(); it != expr_list.rend(); it++) {
// Propagate adjoints
it->accept(this);
}
}
}
}
}
void ReverseAccumulationVisitor::accumulate(const Expr &stub, const Expr &adjoint) {
const BaseExprNode *stub_ptr = (const BaseExprNode *) stub.get();
if (expr_adjoints.find(stub_ptr) == expr_adjoints.end()) {
expr_adjoints[stub_ptr] = adjoint;
} else {
expr_adjoints[stub_ptr] += adjoint;
}
}
void ReverseAccumulationVisitor::visit(const Cast *op) {
assert(expr_adjoints.find(op) != expr_adjoints.end());
Expr adjoint = expr_adjoints[op];
// d/dx cast(x) = 1.f if op->type is float otherwise 0
if (op->type.is_float()) {
accumulate(op->value, make_const(op->type, 1.0));
} else {
accumulate(op->value, make_const(op->type, 0));
}
}
void ReverseAccumulationVisitor::visit(const Variable *op) {
assert(expr_adjoints.find(op) != expr_adjoints.end());
Expr adjoint = expr_adjoints[op];
// If the variable is a let variable, accumulates adjoints into the content
auto it = let_var_mapping.find(op->name);
if (it != let_var_mapping.end()) {
accumulate(it->second, Let::make(op->name, it->second, adjoint));
}
}
void ReverseAccumulationVisitor::visit(const Add *op) {
assert(expr_adjoints.find(op) != expr_adjoints.end());
Expr adjoint = expr_adjoints[op];
// d/da a + b = 1
accumulate(op->a, adjoint);
// d/db a + b = 1
accumulate(op->b, adjoint);
}
void ReverseAccumulationVisitor::visit(const Sub *op) {
assert(expr_adjoints.find(op) != expr_adjoints.end());
Expr adjoint = expr_adjoints[op];
// d/da a - b = 1
accumulate(op->a, adjoint);
// d/db a - b = -1
accumulate(op->b, -adjoint);
}
void ReverseAccumulationVisitor::visit(const Mul *op) {
assert(expr_adjoints.find(op) != expr_adjoints.end());
Expr adjoint = expr_adjoints[op];
// d/da a * b = b
accumulate(op->a, adjoint * op->b);
// d/db a * b = a
accumulate(op->b, adjoint * op->a);
}
void ReverseAccumulationVisitor::visit(const Div *op) {
assert(expr_adjoints.find(op) != expr_adjoints.end());
Expr adjoint = expr_adjoints[op];
// d/da a / b = 1 / b
accumulate(op->a, adjoint / op->b);
// d/db a / b = - a / b^2
accumulate(op->b, -adjoint * op->a / (op->b * op->b));
}
void ReverseAccumulationVisitor::visit(const Min *op) {
assert(expr_adjoints.find(op) != expr_adjoints.end());
Expr adjoint = expr_adjoints[op];
// d/da min(a, b) = a <= b ? 1 : 0
accumulate(op->a,
select(op->a <= op->b, adjoint, make_const(adjoint.type(), 0.0)));
// d/db min(a, b) = b <= a ? 1 : 0
accumulate(op->b,
select(op->b <= op->a, adjoint, make_const(adjoint.type(), 0.0)));
}
void ReverseAccumulationVisitor::visit(const Max *op) {
assert(expr_adjoints.find(op) != expr_adjoints.end());
Expr adjoint = expr_adjoints[op];
// d/da max(a, b) = a >= b ? 1 : 0
accumulate(op->a,
select(op->a >= op->b, adjoint, make_const(adjoint.type(), 0.0)));
// d/db max(a, b) = b >= a ? 1 : 0
accumulate(op->b,
select(op->b >= op->a, adjoint, make_const(adjoint.type(), 0.0)));
}
void ReverseAccumulationVisitor::visit(const Let *op) {
assert(expr_adjoints.find(op) != expr_adjoints.end());
Expr adjoint = expr_adjoints[op];
accumulate(op->body, adjoint);
}
void ReverseAccumulationVisitor::visit(const Select *op) {
assert(expr_adjoints.find(op) != expr_adjoints.end());
Expr adjoint = expr_adjoints[op];
// d/db select(a, b, c) = select(a, 1, 0)
accumulate(op->true_value,
select(op->condition, adjoint, make_const(adjoint.type(), 0.0)));
// d/dc select(a, b, c) = select(a, 0, 1)
accumulate(op->false_value,
select(op->condition, make_const(adjoint.type(), 0.0), adjoint));
}
void ReverseAccumulationVisitor::visit(const Call *op) {
assert(expr_adjoints.find(op) != expr_adjoints.end());
Expr adjoint = expr_adjoints[op];
if (op->is_extern()) {
// Math functions
if (check_opname(op->name, "exp")) {
// d/dx exp(x) = exp(x)
accumulate(op->args[0], adjoint * exp(op->args[0]));
} else if (check_opname(op->name, "log")) {
// d/dx log(x) = 1 / x
accumulate(op->args[0], adjoint / op->args[0]);
} else if (check_opname(op->name, "sin")) {
// d/dx sin(x) = cos(x)
accumulate(op->args[0], adjoint * cos(op->args[0]));
} else if (check_opname(op->name, "asin")) {
// d/dx asin(x) = 1 / sqrt(1 - x^2)
Expr one = make_const(op->type, 1.0);
accumulate(op->args[0], adjoint / sqrt(one - op->args[0] * op->args[0]));
} else if (check_opname(op->name, "cos")) {
// d/dx cos(x) = -sin(x)
accumulate(op->args[0], -adjoint * sin(op->args[0]));
} else if (check_opname(op->name, "acos")) {
// d/dx acos(x) = - 1 / sqrt(1 - x^2)
Expr one = make_const(op->type, 1.0);
accumulate(op->args[0], -adjoint / sqrt(one - op->args[0] * op->args[0]));
} else if (check_opname(op->name, "tan")) {
// d/dx tan(x) = 1 / cos(x)^2
Expr c = cos(op->args[0]);
accumulate(op->args[0], adjoint / (c * c));
} else if (check_opname(op->name, "atan")) {
// d/dx atan(x) = 1 / (1 + x^2)
Expr one = make_const(op->type, 1.0);
accumulate(op->args[0], adjoint / (one + op->args[0] * op->args[0]));
} else if (check_opname(op->name, "atan2")) {
Expr x2y2 = op->args[0] * op->args[0] + op->args[1] * op->args[1];
// d/dy atan2(y, x) = x / (x^2 + y^2)
accumulate(op->args[0], adjoint * op->args[1] / x2y2);
// d/dx atan2(y, x) = -y / (x^2 + y^2)
accumulate(op->args[1], -adjoint * op->args[0] / x2y2);
} else if (check_opname(op->name, "sinh")) {
// d/dx sinh(x) = cosh(x)
accumulate(op->args[0], adjoint * cosh(op->args[0]));
} else if (check_opname(op->name, "asinh")) {
// d/dx asin(x) = 1 / sqrt(1 + x^2)
Expr one = make_const(op->type, 1.0);
accumulate(op->args[0], adjoint / sqrt(one + op->args[0] * op->args[0]));
} else if (check_opname(op->name, "cosh")) {
// d/dx cosh(x) = sinh(x)
accumulate(op->args[0], adjoint * sinh(op->args[0]));
} else if (check_opname(op->name, "acosh")) {
// d/dx acosh(x) = 1 / (sqrt(x - 1) sqrt(x + 1)))
Expr one = make_const(op->type, 1.0);
accumulate(op->args[0],
adjoint / (sqrt(op->args[0] - one) * sqrt(op->args[0] + one)));
} else if (check_opname(op->name, "tanh")) {
// d/dx tanh(x) = 1 / cosh(x)^2
Expr c = cosh(op->args[0]);
accumulate(op->args[0], adjoint / (c * c));
} else if (check_opname(op->name, "atanh")) {
// d/dx atanh(x) = 1 / (1 - x^2)
Expr one = make_const(op->type, 1.0);
accumulate(op->args[0], adjoint / (one - op->args[0] * op->args[0]));
} else if (check_opname(op->name, "ceil")) {
// TODO: d/dx = dirac(n) for n in Z ...
accumulate(op->args[0], make_const(op->type, 0.0));
} else if (check_opname(op->name, "floor")) {
// TODO: d/dx = dirac(n) for n in Z ...
accumulate(op->args[0], make_const(op->type, 0.0));
} else if (check_opname(op->name, "round")) {
accumulate(op->args[0], make_const(op->type, 0.0));
} else if (check_opname(op->name, "trunc")) {
accumulate(op->args[0], make_const(op->type, 0.0));
} else if (check_opname(op->name, "sqrt")) {
Expr half = make_const(op->type, 0.5);
accumulate(op->args[0], adjoint * half / sqrt(op->args[0]));
} else if (check_opname(op->name, "pow")) {
Expr one = make_const(op->type, 1.0);
accumulate(op->args[0],
adjoint * op->args[1] * pow(op->args[0], op->args[1] - one));
accumulate(op->args[1],
adjoint * pow(op->args[0], op->args[1]) * log(op->args[0]));
} else if (check_opname(op->name, "fast_inverse")) {
// d/dx 1/x = -1/x^2
Expr inv_x = fast_inverse(op->args[0]);
accumulate(op->args[0], -adjoint * inv_x * inv_x);
} else if (check_opname(op->name, "fast_inverse_sqrt")) {
// d/dx x^(-0.5) = -0.5*x^(-1.5)
Expr inv_sqrt_x = fast_inverse_sqrt(op->args[0]);
Expr neg_half = make_const(op->type, -0.5);
accumulate(op->args[0],
neg_half * adjoint * inv_sqrt_x * inv_sqrt_x * inv_sqrt_x);
} else if (op->name == "halide_print") {
accumulate(op->args[0], make_const(op->type, 0.0));
} else {
internal_error << "The derivative of " << op->name << " is not implemented.";
}
} else if (op->is_intrinsic()) {
if (op->is_intrinsic(Call::abs)) {
accumulate(op->args[0],
adjoint * select(op->args[0] > 0,
make_const(op->type, 1.0), make_const(op->type, -1.0)));
} else if (op->is_intrinsic(Call::lerp)) {
// z = x * (1 - w) + y * w
// dz/dx = 1 - w
// dz/dy = w
// dz/dw = y - x
accumulate(op->args[0], adjoint * (make_const(op->type, 1.0) - op->args[2]));
accumulate(op->args[1], adjoint * op->args[2]);
accumulate(op->args[2], adjoint * (op->args[1] - op->args[0]));
} else if (op->is_intrinsic(Call::likely)) {
accumulate(op->args[0], adjoint);
} else if (op->is_intrinsic(Call::return_second)) {
accumulate(op->args[0], make_const(op->type, 0.0));
accumulate(op->args[1], adjoint);
} else if (op->is_intrinsic(Call::undef)) {
// do nothing
} else {
user_warning << "Dropping gradients at call to " << op->name << "\n";
for (const auto &arg : op->args) {
accumulate(arg, make_const(op->type, 0.0));
}
}
} else if (op->call_type == Call::Halide ||
op->call_type == Call::Image) { // Halide function call or Halid buffer
// Add Let expressions
adjoint = add_let_expression(adjoint, let_var_mapping, let_variables);
std::vector<Expr> lhs = op->args;
for (int i = 0; i < (int) lhs.size(); i++) {
lhs[i] = add_let_expression(lhs[i], let_var_mapping, let_variables);
}
Expr adjoint_before_canonicalize = adjoint;
std::vector<Expr> lhs_before_canonicalize = lhs;
if (is_forward_overwrite_detection_phase) {
// Don't need to propagate through function in this phase, we're just
// checking local derivatives
// However, we'll accumulate the derivatives to self reference
// for checking if the self update is harmful for gradients
if (op->func.same_as(current_func.function().get_contents())) {
self_reference_adjoint[op->value_index] =
simplify(self_reference_adjoint[op->value_index] + adjoint);
std::vector<Expr> args = op->args;
for (int i = 0; i < (int) args.size(); i++) {
args[i] = add_let_expression(args[i], let_var_mapping, let_variables);
}
self_reference_args.push_back(args);
}
return;
}
if (is_self_referencing_phase) {
// We want to make sure we propagate to the self reference first.
// In this phase only self reference is propagated
if (!op->func.same_as(current_func.function().get_contents())) {
return;
}
} else {
// In the other phase we ignore the self reference
if (op->func.same_as(current_func.function().get_contents())) {
return;
}
}
// We create different functions for the initial condition and each update
// When update i uses value from update i-1, we accumulate the
// adjoints to update i-1
// If target is the current function itself, send to previous update
// e.g. f(x) = ...
// f(x) = f(x) + 1
// For the one with non-commutative-associative reductions
// e.g. f(x, ver) = ...
// f(x, 0) = ...
// f(x, r.x + 1) = f(x, r.x) * f(x, r.x) + g(r.x)
// We propagate the whole r.x to the current update.
// In addition, we propagate the first one (d_f(x, 0)) to the previous update,
// by setting all reduction variables to their min() values.
// Because only f(x, 0) comes from the last update, and
// the rest belongs to the current update.
// The above case will be handled by the caller, here we just
// propagate to current update.
// TODO: make the comments clearer and clean up the code
FuncKey func_key;
if (op->func.defined()) {
Function func(op->func);
func_key = func.name() != current_func.name() ? FuncKey{ func.name(), func.updates().size() - 1 } : FuncKey{ func.name(), current_update_id - 1 };
if (is_current_non_overwriting_scan && is_self_referencing_phase) {
func_key = FuncKey{ func.name(), current_update_id };
}
} else {
func_key = FuncKey{ op->name, -1 };
}
assert(adjoint_funcs.find(func_key) != adjoint_funcs.end());
Func &func_to_update = adjoint_funcs[func_key];
assert(func_to_update.dimensions() == (int) lhs.size());
bool debug_flag = false;
if (debug_flag) {
debug(0) << "current_func:" << current_func.name() << "\n";
debug(0) << "Scattering to " << op->name << "\n";
debug(0) << "lhs is:";
for (const auto &arg : lhs) {
debug(0) << " " << arg;
}
debug(0) << "\n";
debug(0) << "adjoint is:" << simplify(adjoint) << "\n";
//PrintFuncOptions options;
//options.depth = 1;
}
// Gather argument & bounds information
// current_args are the pure variables
// current_update_args are the actual updates at left hand side
Func current_adjoint_func =
adjoint_funcs[FuncKey{ current_func.name(), current_update_id }];
std::vector<Var> current_args = current_adjoint_func.args();
std::vector<Expr> current_update_args;
if (current_update_id >= 0) {
current_update_args = current_func.update_args(current_update_id);
} else {
current_update_args.reserve(current_args.size());
for (const auto &var : current_args) {
current_update_args.push_back(var);
}
}
const Box ¤t_bounds = func_bounds[current_func.name()];