forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
autograd.cpp
1676 lines (1432 loc) · 51.1 KB
/
autograd.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 <ATen/core/boxing/impl/test_helpers.h>
#include <gtest/gtest.h>
#include <ATen/core/op_registration/op_registration.h>
#include <torch/torch.h>
#include <torch/csrc/autograd/FunctionsManual.h>
#include <torch/csrc/autograd/functions/basic_ops.h>
#include <test/cpp/api/support.h>
using namespace torch::autograd;
using namespace torch::test;
#define ASSERT_VARIABLE_EQ(a, b) ASSERT_TRUE(torch::allclose((a), (b)))
#define EXPECT_VARIABLE_EQ(a, b) EXPECT_TRUE(torch::allclose((a), (b)))
std::string graph_desc(std::shared_ptr<Node> node) {
if (!node) {
return "None";
}
auto result = node->name() + "(";
auto next_edges = node->next_edges();
for (auto& edge : next_edges) {
result += graph_desc(edge.function);
}
return result + ")";
}
Variable simple_fn(const Variable& x, const Variable& y) {
return x + 2 * y + x * y;
}
TEST(AutogradAPITests, BackwardSimpleTest) {
Variable x = torch::randn({2, 2}, torch::requires_grad());
Variable y = torch::randn({2, 2}, torch::requires_grad());
auto res = simple_fn(x, y);
backward({res.sum()}, {});
ASSERT_VARIABLE_EQ(x.grad(), y + torch::ones({2, 2}));
ASSERT_VARIABLE_EQ(y.grad(), x + torch::ones({2, 2}) * 2);
}
TEST(AutogradAPITests, BackwardTest) {
Variable x = torch::randn({2, 2}, torch::requires_grad());
Variable y = torch::randn({2, 2}, torch::requires_grad());
auto res = simple_fn(x, y);
backward({res}, {torch::ones({2, 2})}, {}, true);
backward({res}, {torch::ones({2, 2})});
ASSERT_VARIABLE_EQ(x.grad(), 2 * (y + torch::ones({2, 2})));
ASSERT_VARIABLE_EQ(y.grad(), 2 * (x + torch::ones({2, 2}) * 2));
}
TEST(AutogradAPITests, GradSimpleTest) {
// basic grad
Variable x = torch::randn({2, 2}, torch::requires_grad());
Variable y = torch::randn({2, 2}, torch::requires_grad());
auto res = simple_fn(x, y);
auto grad_res = grad({res}, {x, y}, {torch::ones({2, 2})});
ASSERT_VARIABLE_EQ(grad_res[0], y + torch::ones({2, 2}));
ASSERT_VARIABLE_EQ(grad_res[1], x + torch::ones({2, 2}) * 2);
}
TEST(AutogradAPITests, GradTest) {
Variable x = torch::randn({2, 2}, torch::requires_grad());
Variable y = torch::randn({2, 2}, torch::requires_grad());
auto res = simple_fn(x, y);
res.backward(torch::ones({2, 2}), false, true);
Variable x_grad = y + torch::ones({2, 2});
Variable y_grad = x + torch::ones({2, 2}) * 2;
ASSERT_VARIABLE_EQ(x.grad(), x_grad);
ASSERT_VARIABLE_EQ(y.grad(), y_grad);
Variable grad_sum = 2 * x.grad() + y.grad();
auto x_hv = grad({grad_sum}, {x}, {torch::ones({2, 2})}, {}, true);
ASSERT_VARIABLE_EQ(x_hv[0], torch::ones({2, 2}));
ASSERT_VARIABLE_EQ(x.grad(), x_grad);
ASSERT_VARIABLE_EQ(y.grad(), y_grad);
}
TEST(AutogradAPITests, GradNonLeafTest) {
Variable x_init = torch::randn({2, 2}, torch::requires_grad());
Variable x = x_init;
Variable y = torch::randn({2, 2}, torch::requires_grad());
Variable grad_output = torch::ones({2, 2});
for (int i = 0; i < 5; ++i) {
auto res = simple_fn(x, y);
auto input_grads = grad({res}, {x}, {grad_output}, {}, true);
Variable grad_x_expected = y + torch::ones({2, 2});
ASSERT_VARIABLE_EQ(input_grads[0], grad_x_expected);
ASSERT_FALSE(x.grad().defined());
ASSERT_FALSE(y.grad().defined());
x = x + 0.05 * input_grads[0];
}
float val_init = simple_fn(x_init, y).sum().item().toFloat();
float val_final = simple_fn(x, y).sum().item().toFloat();
ASSERT_TRUE(val_final > val_init);
x.backward(grad_output, false, true);
ASSERT_TRUE(x_init.grad().defined());
ASSERT_TRUE(y.grad().defined());
}
TEST(AutogradAPITests, GradUnreachableTest) {
Variable x = torch::ones({1}, torch::requires_grad());
Variable y = torch::ones({1}, torch::requires_grad());
Variable z = x * 2;
Variable w = y * 2;
auto grad_res = grad({x * 2}, {x, y}, {}, {}, false, true);
ASSERT_VARIABLE_EQ(grad_res[0], x * 2);
ASSERT_FALSE(grad_res[1].defined());
// This is slightly different than the case above, because z doesn't even
// have a grad accumulator allocated.
z = torch::ones({1}, torch::requires_grad());
grad_res = grad({x * 2}, {x, z}, {}, {}, false, true);
ASSERT_VARIABLE_EQ(grad_res[0], x * 2);
ASSERT_FALSE(grad_res[1].defined());
// allow_unused=False, but grads contains None inside, should throw
ASSERT_THROWS_WITH(
grad({x * 2}, {x, y}, {}, {}, false, false), "Set allow_unused=True");
}
TEST(CustomAutogradTest, GradUnreachableDiscoveryTest) {
// Test that certain nodes are not erroneously executed when an input
// is unreachable. See #39784
struct MyFunction : public Function<MyFunction> {
static Variable forward(AutogradContext* ctx, Variable var) {
return var;
}
static variable_list backward(
AutogradContext* ctx,
variable_list grad_output) {
ADD_FAILURE() << "This node should not be executed!";
return grad_output;
}
};
auto x = torch::randn(1, torch::requires_grad());
auto x1 = torch::randn(1);
auto x2 = MyFunction::apply(x + x1);
auto y = torch::randn(1, torch::requires_grad());
auto grad_res = torch::autograd::grad({x2}, {y}, {}, {}, false, true);
ASSERT_FALSE(grad_res[0].defined());
}
TEST(AutogradAPITests, EmptyInput) {
Variable x = torch::ones({1}, torch::requires_grad());
ASSERT_THROWS_WITH(
grad({x * 2}, /*inputs=*/{}, {x}), "grad requires non-empty inputs.");
}
TEST(AutogradAPITests, RetainGrad) {
auto input = torch::rand({1, 3}, torch::requires_grad());
auto h1 = input * 3;
auto out = (h1 * h1).sum();
{
// Warning when grad is accessed for non-leaf tensor
WarningCapture warnings;
ASSERT_FALSE(h1.grad().defined());
ASSERT_TRUE(warnings.str().find("is not a leaf") != std::string::npos);
}
// It should be possible to call retain_grad() multiple times
h1.retain_grad();
h1.retain_grad();
{
// If retain_grad is true for a non-leaf tensor,
// there should not be any warning when grad is accessed
WarningCapture warnings;
ASSERT_FALSE(h1.grad().defined());
ASSERT_FALSE(warnings.str().find("is not a leaf") != std::string::npos);
}
// Gradient should be accumulated
// NOLINTNEXTLINE(bugprone-argument-comment)
out.backward({}, /*keep_graph=*/true);
ASSERT_VARIABLE_EQ(h1 * 2, h1.grad());
// NOLINTNEXTLINE(bugprone-argument-comment)
out.backward({}, /*keep_graph=*/true);
ASSERT_VARIABLE_EQ(h1 * 4, h1.grad());
{
torch::NoGradGuard no_grad;
input.grad().zero_();
}
// It should be a no-op for leaves
input.retain_grad();
input.retain_grad();
out.backward();
ASSERT_VARIABLE_EQ(input * 18, input.grad());
}
TEST(AutogradAPITests, AnomalyMode) {
// Needs to have backtrace as warning and then throw an error
torch::autograd::DetectAnomalyGuard detect_anomaly;
{
WarningCapture warnings;
auto x = torch::tensor({5.0}, torch::requires_grad());
auto y = x * x;
auto z = y * y;
y += 1;
ASSERT_THROWS_WITH(z.backward(), "inplace");
ASSERT_TRUE(
warnings.str().find("Traceback of forward") != std::string::npos);
}
auto double_backward_produce_nan = [](bool should_throw) {
auto x = torch::tensor({0.0}, torch::requires_grad());
auto y = x.pow(1.5);
auto gr =
// NOLINTNEXTLINE(bugprone-argument-comment)
grad({y}, {x}, {}, /*retain_graph=*/true, /*create_backward=*/true);
if (should_throw) {
WarningCapture warnings;
ASSERT_THROWS_WITH(grad({gr[0]}, {x}, {torch::tensor({0.0})});
, "returned nan");
auto msgs = warnings.messages();
ASSERT_EQ(msgs.size(), 2);
ASSERT_TRUE(
msgs[0].find("Traceback of forward call that caused the error") !=
std::string::npos);
ASSERT_TRUE(
msgs[1].find(
"Traceback of forward call that induced the previous calculation") !=
std::string::npos);
} else {
grad({gr[0]}, {x}, {torch::tensor({0.0})});
}
};
double_backward_produce_nan(true);
{
torch::autograd::DetectAnomalyGuard detect_anomaly(/*check_nan=*/false);
double_backward_produce_nan(false);
{
torch::autograd::DetectAnomalyGuard detect_anomaly(/*check_nan=*/true);
double_backward_produce_nan(true);
}
}
double_backward_produce_nan(true);
}
TEST(CustomAutogradTest, CustomFunctionReturnInputAsIsAndSavesIt) {
struct MyFunction : public Function<MyFunction> {
static Variable forward(
AutogradContext* ctx,
Variable var1,
Variable var2) {
ctx->save_for_backward({var1, var2});
return var1 * var2, var1;
}
static variable_list backward(
AutogradContext* ctx,
variable_list grad_output) {
return {};
}
};
Variable x = torch::randn({5, 5}, torch::requires_grad());
Variable y = torch::randn({5, 5}, torch::requires_grad());
MyFunction::apply(x, y);
}
TEST(CustomAutogradTest, CustomFunction) {
struct MyFunction : public Function<MyFunction> {
static Variable forward(
AutogradContext* ctx,
Variable var1,
int mul,
Variable var2) {
ctx->saved_data["mul"] = mul;
ctx->save_for_backward({var1, var2});
return var1 + mul * var2 + var1 * var2;
}
static variable_list backward(
AutogradContext* ctx,
variable_list grad_output) {
int mul = ctx->saved_data["mul"].toInt();
auto saved = ctx->get_saved_variables();
auto var1 = saved[0];
auto var2 = saved[1];
variable_list output = {
grad_output[0] + grad_output[0] * var2,
Variable(),
grad_output[0] * mul + grad_output[0] * var1};
return output;
}
};
Variable x = torch::randn({5, 5}, torch::requires_grad());
Variable y = torch::randn({5, 5}, torch::requires_grad());
auto res = MyFunction::apply(x, 2, y);
auto go = torch::ones({}, torch::requires_grad());
res.sum().backward(go, false, true);
ASSERT_VARIABLE_EQ(x.grad(), y + torch::ones({5, 5}));
ASSERT_VARIABLE_EQ(y.grad(), x + torch::ones({5, 5}) * 2);
}
TEST(CustomAutogradTest, CustomFunctionWithTensorList) {
struct MyFunction : public Function<MyFunction> {
static Variable forward(AutogradContext* ctx, at::TensorList tensors) {
torch::autograd::variable_list vars;
for (const at::Tensor& tensor : tensors) {
vars.push_back(tensor);
}
ctx->save_for_backward(vars);
return tensors[0] + tensors[1] + tensors[0] * tensors[1];
}
static variable_list backward(
AutogradContext* ctx,
variable_list grad_output) {
auto saved = ctx->get_saved_variables();
auto var1 = saved[0];
auto var2 = saved[1];
variable_list output = {
grad_output[0] + grad_output[0] * var2,
grad_output[0] + grad_output[0] * var1};
return output;
}
};
at::Tensor x = torch::randn({5, 5}, torch::requires_grad());
at::Tensor y = torch::randn({5, 5}, torch::requires_grad());
torch::autograd::variable_list variables = {x, y};
at::TensorList tensors = variables;
auto res = MyFunction::apply(tensors);
auto go = torch::ones({}, torch::requires_grad());
res.sum().backward(go, false, true);
ASSERT_VARIABLE_EQ(x.grad(), y + torch::ones({5, 5}));
ASSERT_VARIABLE_EQ(y.grad(), x + torch::ones({5, 5}));
}
TEST(CustomAutogradTest, GraphTaskTrimEdges) {
struct MyFunction : public Function<MyFunction> {
static Variable forward(
AutogradContext* ctx,
Variable var1,
Variable var2,
int mul,
bool needs_input1_grad,
bool needs_input2_grad) {
// setup the expected should and should not compute idx
ctx->saved_data["needs_input1_grad"] = needs_input1_grad;
ctx->saved_data["needs_input2_grad"] = needs_input2_grad;
ctx->saved_data["mul"] = mul;
ctx->save_for_backward({var1, var2});
return var1 + mul * var2 + var1 * var2;
}
static variable_list backward(
AutogradContext* ctx,
variable_list grad_output) {
// Test `needs_input_grad` method is working correctly.
// We have to test this within the backward function.
auto needs_input1_grad = ctx->saved_data["needs_input1_grad"].toBool();
auto needs_input2_grad = ctx->saved_data["needs_input2_grad"].toBool();
IndexRange var1_idx = {0, 1};
IndexRange var2_idx = {1, 2};
EXPECT_EQ(ctx->needs_input_grad(0), needs_input1_grad);
EXPECT_EQ(ctx->needs_input_grad(1), needs_input2_grad);
EXPECT_EQ(ctx->needs_input_grad({var1_idx}), needs_input1_grad);
EXPECT_EQ(ctx->needs_input_grad({var2_idx}), needs_input2_grad);
EXPECT_EQ(
ctx->needs_input_grad({var1_idx, var2_idx}),
needs_input1_grad || needs_input2_grad);
// calculate gradients
int mul = ctx->saved_data["mul"].toInt();
auto saved = ctx->get_saved_variables();
auto var1 = saved[0];
auto var2 = saved[1];
Variable grad_var1, grad_var2;
if (ctx->needs_input_grad(0)) {
grad_var1 = grad_output[0] + grad_output[0] * var2;
}
if (ctx->needs_input_grad(1)) {
grad_var2 = grad_output[0] * mul + grad_output[0] * var1;
}
variable_list output = {
grad_var1,
grad_var2,
Variable(),
Variable(),
Variable(),
};
return output;
}
};
Variable x = torch::randn({5, 5}, torch::requires_grad());
Variable y = torch::randn({5, 5}, torch::requires_grad());
auto go = torch::ones_like(x);
Variable out;
// grad_x
out = MyFunction::apply(
x,
y,
2,
/* needs_input1_grad= */ true,
/* needs_input2_grad= */ false);
auto grad_x = torch::autograd::grad({out}, {x}, {go})[0];
ASSERT_VARIABLE_EQ(grad_x, y + torch::ones({5, 5}));
// grad_y
out = MyFunction::apply(
x,
y,
2,
/* needs_input1_grad= */ false,
/* needs_input2_grad= */ true);
auto grad_y = torch::autograd::grad({out}, {y}, {go})[0];
ASSERT_VARIABLE_EQ(grad_y, x + torch::ones({5, 5}) * 2);
// grad_x and grad_y
out = MyFunction::apply(
x,
y,
2,
/* needs_input1_grad= */ true,
/* needs_input2_grad= */ true);
auto grads = torch::autograd::grad({out}, {x, y}, {go});
ASSERT_VARIABLE_EQ(grads[0], y + torch::ones({5, 5}));
ASSERT_VARIABLE_EQ(grads[1], x + torch::ones({5, 5}) * 2);
}
TEST(CustomAutogradTest, FunctionReturnsInput) {
struct MyFunction : public Function<MyFunction> {
static Variable forward(AutogradContext* ctx, Variable var1) {
return var1;
}
static variable_list backward(
AutogradContext* ctx,
variable_list grad_output) {
return {grad_output[0] * 2};
}
};
Variable x(torch::ones(1, torch::requires_grad()));
MyFunction::apply(x).backward(torch::ones(1), true, true);
ASSERT_VARIABLE_EQ(x.grad(), torch::full(1, 2.));
}
TEST(CustomAutogradTest, FunctionReturnsUndefined) {
struct MyFunction : public Function<MyFunction> {
static Variable forward(AutogradContext* ctx, Variable var) {
return var * 2;
}
static variable_list backward(
AutogradContext* ctx,
variable_list grad_output) {
at::Tensor undefined_tensor;
return {undefined_tensor};
}
};
auto x = torch::ones(1, torch::requires_grad());
MyFunction::apply(x).backward();
ASSERT_FALSE(x.grad().defined());
MyFunction::apply(x.pow(2)).backward();
ASSERT_FALSE(x.grad().defined());
MyFunction::apply(x).sum().backward();
ASSERT_FALSE(x.grad().defined());
ASSERT_FALSE(torch::autograd::grad(
{MyFunction::apply(x)}, {x}, {}, false, false, true)[0]
.defined());
}
TEST(CustomAutogradTest, MaterializeGrads) {
struct MyFunction : public Function<MyFunction> {
static Variable forward(AutogradContext* ctx, Variable var) {
return var;
}
static variable_list backward(
AutogradContext* ctx,
variable_list grad_output) {
EXPECT_VARIABLE_EQ(grad_output[0], torch::zeros(1));
return grad_output;
}
};
auto x = torch::ones(1, torch::requires_grad());
UndefinedGrad().apply({MyFunction::apply(x)})[0].backward();
}
TEST(CustomAutogradTest, DontMaterializeGrads) {
struct MyFunction : public Function<MyFunction> {
static Variable forward(AutogradContext* ctx, Variable var) {
ctx->set_materialize_grads(false);
return var;
}
static variable_list backward(
AutogradContext* ctx,
variable_list grad_output) {
EXPECT_FALSE(grad_output[0].defined());
return grad_output;
}
};
auto x = torch::ones(1, torch::requires_grad());
UndefinedGrad().apply({MyFunction::apply(x)})[0].backward();
}
TEST(CustomAutogradTest, NoGradCustomFunction) {
// Custom Function should respect grad mode
struct MyOp : public Function<MyOp> {
static Variable forward(AutogradContext* ctx, Variable x) {
return x + 1;
}
static variable_list backward(AutogradContext* ctx, variable_list dy) {
return dy;
}
};
auto x = torch::ones({5, 5}, torch::requires_grad());
{
at::NoGradGuard no_grad;
auto y = MyOp::apply(x);
ASSERT_FALSE(y.requires_grad());
}
}
TEST(CustomAutogradTest, MarkDirty) {
struct MyFunction : public Function<MyFunction> {
static Variable forward(AutogradContext* ctx, Variable v) {
// Change the value inplace
auto v_data = v.data_ptr<float>();
v_data[0] = 2;
ctx->mark_dirty({v});
return v;
}
static variable_list backward(
AutogradContext* ctx,
variable_list grad_output) {
return {(grad_output[0] * 2.0)};
}
};
// Clone here because modifying leafs inplace is not allowed
auto x = torch::randn({5, 5}, torch::requires_grad()).clone();
auto version_before = x._version();
auto out = MyFunction::apply(x);
auto version_after = x._version();
ASSERT_TRUE(version_after >= (version_before + 1));
out.sum().backward();
}
TEST(CustomAutogradTest, MarkNonDifferentiable) {
struct MyFunction : public Function<MyFunction> {
static Variable forward(AutogradContext* ctx, Variable v) {
Variable output = v > 0;
ctx->mark_non_differentiable({output});
return output;
}
static variable_list backward(
AutogradContext* ctx,
variable_list grad_output) {
return {(grad_output[0] * 0.0)};
}
};
auto x = torch::randn({5, 5}, torch::requires_grad());
auto mask = MyFunction::apply(x);
ASSERT_FALSE(mask.requires_grad());
auto y = x.masked_fill(mask, 0);
y.sum().backward();
}
TEST(CustomAutogradTest, MarkNonDifferentiableMixed) {
struct MyFunction : public Function<MyFunction> {
static variable_list forward(AutogradContext* ctx, Variable input) {
Variable a = input + 1;
Variable b = input + 2;
ctx->mark_non_differentiable({a});
return {a, b};
}
static variable_list backward(
AutogradContext* ctx,
variable_list grad_output) {
const Variable &grad_a = grad_output[0], &grad_b = grad_output[1];
EXPECT_VARIABLE_EQ(grad_a, torch::zeros({5, 5}));
EXPECT_VARIABLE_EQ(grad_b, torch::ones({5, 5}));
return {grad_b};
}
};
auto x = torch::randn({5, 5}, torch::requires_grad());
auto out = MyFunction::apply(x);
ASSERT_FALSE(out[0].requires_grad());
ASSERT_TRUE(out[1].requires_grad());
out[1].sum().backward();
ASSERT_VARIABLE_EQ(x.grad(), torch::ones({5, 5}));
}
TEST(CustomAutogradTest, MarkNonDifferentiableNone) {
struct MyFunction : public Function<MyFunction> {
static Variable forward(AutogradContext* ctx, Variable input) {
auto output = input.clone();
ctx->mark_non_differentiable({output});
return output;
}
static variable_list backward(
AutogradContext* ctx,
variable_list grad_outputs) {
return {};
}
};
auto x = torch::randn({5, 5}, torch::requires_grad());
auto r = MyFunction::apply(x * x);
(r * x).sum().backward();
}
TEST(CustomAutogradTest, ReturnLeafInplace) {
struct Inplace : public Function<Inplace> {
static variable_list forward(AutogradContext* ctx, Variable a, Variable b) {
ctx->mark_dirty({a});
return {a.add_(b), b + 2};
}
static variable_list backward(
AutogradContext* ctx,
variable_list grad_output) {
return {grad_output[0], grad_output[0] + grad_output[1]};
}
};
Variable x = torch::randn({5, 5});
Variable y = torch::randn({5, 5}, torch::requires_grad());
auto out = Inplace::apply(x, y);
auto& q = out[0];
ASSERT_TRUE(torch::equal(q, x));
ASSERT_TRUE(q.requires_grad());
q.sum().backward();
ASSERT_VARIABLE_EQ(y.grad(), torch::ones({5, 5}));
}
TEST(CustomAutogradTest, ReturnDuplicateInplace) {
struct DoubleInplace : public Function<DoubleInplace> {
static variable_list forward(AutogradContext* ctx, Variable x) {
x.mul_(2);
ctx->mark_dirty({x});
return {x, x};
}
static variable_list backward(
AutogradContext* ctsx,
variable_list grad_outputs) {
return {grad_outputs[0] * 2 + grad_outputs[1] * 2};
}
};
auto x = torch::randn({5, 5}, torch::requires_grad());
ASSERT_THROWS_WITH(
DoubleInplace::apply(x), "leaf Variable that requires grad");
// TODO ASSERT_THROWS_WITH(DoubleInplace::apply(x.clone()[0]), "only one
// output");
auto out = DoubleInplace::apply(x.clone());
ASSERT_TRUE(torch::equal(out[0], out[1]));
}
TEST(CustomAutogradTest, ReturnDuplicate) {
struct DoubleDuplicate : public Function<DoubleDuplicate> {
static variable_list forward(AutogradContext* ctx, Variable x) {
auto output = x * 2;
return {output, output};
}
static variable_list backward(
AutogradContext* ctx,
variable_list grad_outputs) {
return {grad_outputs[0] * 2 + grad_outputs[1] * 2};
}
};
auto x = torch::randn({5, 5}, torch::requires_grad());
auto out = DoubleDuplicate::apply(x);
ASSERT_TRUE(torch::equal(out[0], out[1]));
}
TEST(CustomAutogradTest, SaveEmptyForBackward) {
struct MyFunction : public Function<MyFunction> {
static Variable forward(AutogradContext* ctx, Variable input) {
ctx->save_for_backward({Variable(), input, Variable()});
return input * input;
}
static variable_list backward(
AutogradContext* ctx,
variable_list grad_output) {
auto saved = ctx->get_saved_variables();
EXPECT_FALSE(saved[0].defined());
EXPECT_FALSE(saved[2].defined());
return {saved[1] * 2 * grad_output[0]};
}
};
Variable x = torch::randn({5, 5}, torch::requires_grad());
auto y = MyFunction::apply(x);
y.sum().backward();
ASSERT_VARIABLE_EQ(x.grad(), 2 * x);
}
TEST(CustomAutogradTest, InvalidGradients) {
struct MyFunction : public Function<MyFunction> {
static Variable forward(AutogradContext* ctx, Variable x) {
return x * 2;
}
static variable_list backward(
AutogradContext* ctsx,
variable_list grad_outputs) {
return {
torch::randn(10, torch::dtype(torch::kFloat).requires_grad(true))};
}
};
auto input1 =
torch::randn({5, 5}, torch::dtype(torch::kFloat).requires_grad(true));
ASSERT_THROWS_WITH(
MyFunction::apply(input1).sum().backward(), "expected shape");
auto input2 =
torch::randn(10, torch::dtype(torch::kDouble).requires_grad(true));
}
TEST(CustomAutogradTest, NoGradInput) {
struct MyFunction : public Function<MyFunction> {
static Variable forward(AutogradContext*, Variable x) {
return x;
}
static variable_list backward(
AutogradContext*,
variable_list grad_outputs) {
return grad_outputs;
}
};
Variable x = torch::randn({5, 5}, torch::requires_grad());
Variable y;
{
at::NoGradGuard no_grad;
y = MyFunction::apply(x);
}
ASSERT_TRUE(x.requires_grad());
ASSERT_FALSE(y.grad_fn());
}
TEST(CustomAutogradTest, TooManyGrads) {
struct MyFunction : public Function<MyFunction> {
static Variable forward(AutogradContext*, Variable input) {
return input;
}
static variable_list backward(AutogradContext*, variable_list grad_output) {
grad_output.insert(grad_output.end(), {Variable(), Variable()});
return grad_output;
}
};
}
TEST(CustomAutogradTest, DepNoGrad) {
struct F1 : public Function<F1> {
static variable_list forward(AutogradContext* ctx, Variable input) {
auto out = torch::randn(input.sizes());
ctx->mark_non_differentiable({out});
return {input, out};
}
static variable_list backward(
AutogradContext* ctx,
variable_list grad_output) {
return {grad_output[0]};
}
};
struct F2 : public Function<F2> {
static Variable forward(AutogradContext*, Variable input, Variable ignore) {
return input;
}
static variable_list backward(AutogradContext*, variable_list grad_output) {
return {grad_output[0], Variable()};
}
};
auto x = torch::randn(5, torch::requires_grad());
auto out = F1::apply(x);
Variable &a = out[0], &b = out[1];
b = b + 1; // Separate F1 and F2 by another operation
ASSERT_TRUE(a.requires_grad());
ASSERT_FALSE(b.requires_grad());
auto c = F2::apply(a, b);
c.backward(torch::ones(c.sizes()), false, false);
ASSERT_VARIABLE_EQ(x.grad(), torch::ones(x.sizes()));
}
TEST(CustomAutogradTest, Reentrant) {
static Variable y_data = torch::randn({2, 2});
struct Reenter : public Function<Reenter> {
static Variable forward(AutogradContext* ctx, Variable input) {
Variable output;
{
at::AutoGradMode enable_grad(true);
auto x = make_variable(input.tensor_data(), true);
auto y = make_variable(y_data.tensor_data(), true);
output = x * y;
ctx->saved_data["x"] = x;
ctx->saved_data["y"] = y;
ctx->saved_data["output_var"] = output;
}
return output.detach();
}
static variable_list backward(
AutogradContext* ctx,
variable_list grad_output) {
{
at::AutoGradMode enable_grad(true);
auto out = ctx->saved_data["output_var"].toTensor();
out.sum().backward();
}
return {ctx->saved_data["x"].toTensor().grad() * grad_output[0]};
}
};
auto x = torch::randn({2, 2}, torch::requires_grad());
auto out = Reenter::apply(x);
out.sum().backward();
ASSERT_VARIABLE_EQ(x.grad(), y_data);
}
// NOTE: If this fails for apparently unrelated reasons in TSAN be aware of
// the TSAN limit on mutex: https://github.com/google/sanitizers/issues/950
TEST(CustomAutogradTest, DeepReentrant) {
struct DeepReenter : public Function<DeepReenter> {
static Variable forward(AutogradContext* ctx, Variable x) {
{
at::AutoGradMode enable_grad(true);
ctx->saved_data["x"] = make_variable(x.tensor_data(), true) - 1;
}
return ctx->saved_data["x"].toTensor().detach();
}
static variable_list backward(
AutogradContext* ctx,
variable_list grad_output) {
if (!at::native::is_nonzero(ctx->saved_data["x"].toTensor())) {
return grad_output;
}
{
at::AutoGradMode enable_grad(true);
apply(ctx->saved_data["x"].toTensor())[0].sum().backward();
return grad_output;
}
}
};
// This should not stack overflow
auto v =
torch::tensor({8193}, torch::dtype(torch::kFloat).requires_grad(true));
DeepReenter::apply(v).sum().backward();
}
TEST(CustomAutogradTest, ReentrantPriority) {
static std::vector<int> order;
struct MyFunction : public Function<MyFunction> {
static Variable forward(AutogradContext*, Variable x) {
return x;
}
static variable_list backward(AutogradContext*, variable_list grad) {
order.push_back(0);
return grad;
}
};
struct Reenter : public Function<Reenter> {
static Variable forward(AutogradContext* ctx, Variable x) {
{
at::AutoGradMode enable_grad(true);
ctx->saved_data["x"] = make_variable(x.tensor_data(), true) - 1;
}
return ctx->saved_data["x"].toTensor().detach();
}
static variable_list backward(
AutogradContext* ctx,
variable_list grad_output) {
order.push_back(1);
if (!at::native::is_nonzero(ctx->saved_data["x"].toTensor())) {
return grad_output;
}
{
at::AutoGradMode enable_grad(true);
apply(ctx->saved_data["x"].toTensor())[0].sum().backward();
return grad_output;
}
}
};
auto a = MyFunction::apply(
torch::tensor({6}, torch::dtype(torch::kFloat).requires_grad(true)));
auto b = Reenter::apply(
torch::tensor({9}, torch::dtype(torch::kFloat).requires_grad(true)));
auto v = a * b;
v.backward();
// All the reentrant tasks should be prioritized over the MyFunction backward
// task.
ASSERT_EQ(order.size(), 10);
ASSERT_EQ(std::count(order.begin(), order.end(), 1), 9);
ASSERT_EQ(order.back(), 0);
// Clear static variable in case test get executed in a loop
order.clear();
}
TEST(CustomAutogradTest, Hooks) {
Variable x = torch::ones({5, 5}, torch::requires_grad());
Variable y = torch::ones({5, 5}) * 4;
y.set_requires_grad(true);
int counter = 0;
std::function<void(int, Variable)> bw_hook(
[&counter](int inc, Variable grad) { counter += inc; });
Variable z = x * x + x * 2 + x * y + y;
x.register_hook([&bw_hook](Variable grad) { bw_hook(0, grad); });
auto hook_1 =
z.register_hook([&bw_hook](Variable grad) { bw_hook(1, grad); });
z.backward(torch::ones({5, 5}), true, true);
ASSERT_EQ(counter, 1);
auto hook_2 =
z.register_hook([&bw_hook](Variable grad) { bw_hook(2, grad); });
z.backward(torch::ones({5, 5}), true, true);
ASSERT_EQ(counter, 4);
z.remove_hook(hook_2);
z.backward(torch::ones({5, 5}), true, true);
ASSERT_EQ(counter, 5);
std::function<Variable(Variable)> bw_hook_modify(
[](Variable grad) { return grad.mul(2); });
z.remove_hook(hook_1);
z.register_hook(bw_hook_modify);
y.grad().zero_();
z.backward(torch::ones({5, 5}), true, false);
ASSERT_VARIABLE_EQ(y.grad(), (x + 1) * 2);
y.register_hook(bw_hook_modify);
y.grad().zero_();
z.backward(torch::ones({5, 5}), false, false);
ASSERT_VARIABLE_EQ(y.grad(), (x + 1) * 4);
ASSERT_THROWS_WITH(y.remove_hook(3), "Invalid index");