forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_autograd.py
12224 lines (10011 loc) · 462 KB
/
test_autograd.py
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
# Owner(s): ["module: autograd"]
import contextlib
import gc
import io
import math
import os
import random
import sys
import tempfile
import threading
import time
import unittest
import uuid
import warnings
import operator
import subprocess
from copy import deepcopy
from collections import OrderedDict
from itertools import product
from operator import mul
from typing import List, Tuple
from functools import reduce, partial
import torch
from torch import nn
from torch import inf, nan
from torch.autograd.function import once_differentiable
from torch.autograd.profiler import (profile, record_function, emit_nvtx, emit_itt)
from torch.autograd.profiler_util import (_format_time, EventList, FunctionEvent, FunctionEventAvg)
from torch.utils.checkpoint import checkpoint, checkpoint_sequential
from torch.testing import make_tensor
from torch.testing._internal.common_cuda import TEST_CUDA
from torch.testing._internal.common_utils import (
TestCase, run_tests, skipIfNoLapack, slowTest, IS_WINDOWS, IS_MACOS,
disable_gc, gradcheck, gradgradcheck, parametrize,
instantiate_parametrized_tests, skipIfMps, set_warn_always_context,
skipIfTorchDynamo)
from torch.autograd import Variable, Function, detect_anomaly, kineto_available, _calculate_shape
from torch.autograd.function import InplaceFunction
import torch.autograd.forward_ad as fwAD
from torch.autograd.graph import GradientEdge
import torch.autograd._functions
from torch.testing._internal.common_methods_invocations import mask_not_all_zeros
from torch.testing._internal.common_device_type import (instantiate_device_type_tests,
onlyCPU, onlyCUDA, dtypes, dtypesIfCUDA,
deviceCountAtLeast, skipMeta, dtypesIfMPS)
from torch.testing._internal.common_dtype import floating_types_and
from torch.utils._mode_utils import no_dispatch
from torch.utils._python_dispatch import TorchDispatchMode
from torch.utils.hooks import RemovableHandle
import weakref
import collections
import pickle
def graph_desc(fn):
if fn is None:
return 'None'
result = type(fn).__name__ + '('
next_functions = fn.next_functions
for next_fn, _ in next_functions:
result += graph_desc(next_fn)
result += ', '
if next_functions:
result = result[:-2]
return result + ')'
class TestAutograd(TestCase):
def test_copy_slices_graph_task_updates(self):
def f1(x, y):
out = x.clone().view(-1)
out += y
return out
def f2(x, y):
out = x.clone().view(-1)
b = out * 2
out += y
return out + b
x = torch.rand(2, requires_grad=True)
y = torch.rand(2, requires_grad=True)
y_safe = torch._C._functions.DelayedError("Boom!", 1)(y)
for f in [f1, f2]:
# Ensure that the error Node works
out = f(x, y_safe)
with self.assertRaisesRegex(RuntimeError, "Boom!"):
out.sum().backward()
out = f(x, y_safe)
with self.assertRaisesRegex(RuntimeError, "Boom!"):
torch.autograd.grad(out.sum(), y)
# Ensure that if we don't ask for y, it doesn't crash
out = f(x, y_safe)
torch.autograd.grad(out.sum(), x)
out = f(x, y_safe)
torch.autograd.grad(out.sum(), y_safe)
out = f(x, y_safe)
torch.autograd.grad(out.sum(), (x, y_safe))
# Ensure that we don't run extra view Node
def f3(x, y):
out = x.clone().view(-1)
def hook(*args):
# This should never be called!
self.assertTrue(False)
out.register_hook(hook)
b = out + y
out += y
return out + b, b
out, b = f3(x, y_safe)
torch.autograd.grad(out.sum(), (b, y_safe))
def test_grad_mode_class_decoration(self):
# Decorating class is deprecated and should not be used
with self.assertWarnsRegex(UserWarning, "Decorating classes is deprecated"):
@torch.no_grad()
class Foo:
def __init__(self):
assert not torch.is_grad_enabled()
def foo(self):
# Not applied to methods
assert torch.is_grad_enabled()
# Show that we can actually construct the class
foo = Foo()
foo.foo()
# Decorating functions or methods is fine though
with warnings.catch_warnings(record=True) as w:
@torch.no_grad()
def foo():
assert not torch.is_grad_enabled()
foo()
class Foo2:
@torch.no_grad()
def __init__(self):
assert not torch.is_grad_enabled()
@torch.no_grad()
def foo(self):
assert not torch.is_grad_enabled()
foo2 = Foo2()
foo2.foo()
self.assertEqual(len(w), 0)
def test_tensor_grad_warnings(self):
dummy = torch.empty(1)
with warnings.catch_warnings(record=True) as w:
# Accessing .grad on leaf
dummy.requires_grad_()
foo = dummy.grad
self.assertEqual(len(w), 0)
# Accessing .grad on non-leaf
dummy = dummy.clone()
foo = dummy.grad
self.assertEqual(len(w), 1)
# Accessing .grad on non-leaf that retains gradients
dummy.retain_grad()
foo = dummy.grad
self.assertEqual(len(w), 1)
def _function_test(self, cls):
x = torch.randn(5, 5, requires_grad=True)
y = torch.randn(5, 5, requires_grad=True)
result = cls.apply(x, 2, y)
go = torch.ones((), requires_grad=True)
result.sum().backward(go, create_graph=True)
self.assertEqual(x.grad, y + torch.ones(5, 5))
self.assertEqual(y.grad, x + torch.ones(5, 5) * 2)
self.assertIsNotNone(x.grad.grad_fn)
self.assertIsNotNone(y.grad.grad_fn)
return x, y
def test_function(self):
class MyFunction(Function):
@staticmethod
def forward(ctx, tensor1, pyscalar, tensor2):
ctx.pyscalar = pyscalar
ctx.save_for_backward(tensor1, tensor2)
return tensor1 + pyscalar * tensor2 + tensor1 * tensor2
@staticmethod
def backward(ctx, grad_output):
var1, var2 = ctx.saved_tensors
# NOTE: self is the test case here
self.assertIsInstance(var1, torch.Tensor)
self.assertIsInstance(var2, torch.Tensor)
self.assertIsInstance(grad_output, torch.Tensor)
return (grad_output + grad_output * var2, None,
grad_output * ctx.pyscalar + grad_output * var1)
x, y = self._function_test(MyFunction)
x_grad_desc = graph_desc(x.grad.grad_fn)
y_grad_desc = graph_desc(y.grad.grad_fn)
self.assertExpected(x_grad_desc, "x_grad_desc")
self.assertExpected(y_grad_desc, "y_grad_desc")
def test_once_differentiable(self):
class MyFunction(Function):
@staticmethod
def forward(ctx, tensor1, pyscalar, tensor2):
ctx.pyscalar = pyscalar
ctx.save_for_backward(tensor1, tensor2)
return tensor1 + pyscalar * tensor2 + tensor1 * tensor2
@staticmethod
@once_differentiable
def backward(ctx, grad_output):
self.assertFalse(torch.is_grad_enabled())
t1, t2 = ctx.saved_tensors
return (grad_output + grad_output * t2, None,
grad_output * ctx.pyscalar + grad_output * t1)
x, y = self._function_test(MyFunction)
self.assertEqual(graph_desc(x.grad.grad_fn),
'CopyBackwards(None, Error(AccumulateGrad(), None, AccumulateGrad()))')
self.assertEqual(graph_desc(y.grad.grad_fn),
'CopyBackwards(None, Error(AccumulateGrad(), None, AccumulateGrad()))')
def test_function_returns_input(self):
class MyFunction(Function):
@staticmethod
def forward(ctx, x):
return x
@staticmethod
def backward(ctx, grad):
return grad * 2
for shape in [(1,), ()]:
v = torch.ones(shape, requires_grad=True)
MyFunction.apply(v).backward()
self.assertEqual(v.grad, torch.full(shape, 2.))
with torch.no_grad():
v.grad.zero_()
MyFunction.apply(v.clone()).backward()
self.assertEqual(v.grad, torch.full(shape, 2.))
def test_function_returns_undefined_tensor(self):
class MyFunction(Function):
@staticmethod
def forward(ctx, x):
return x * 2
@staticmethod
def backward(ctx, grad):
return None
# Test that undefined tensors returned from custom backward function
# are propagated as undefined and not tensor full of zeroes
x = torch.ones(1, requires_grad=True)
MyFunction.apply(x).backward()
self.assertIsNone(x.grad)
MyFunction.apply(x ** 2).backward()
self.assertIsNone(x.grad)
MyFunction.apply(x).sum().backward()
self.assertIsNone(x.grad)
self.assertIsNone(torch.autograd.grad(MyFunction.apply(x), x, allow_unused=True)[0])
def test_materialize_grads(self):
class MyFunction(Function):
@staticmethod
def forward(ctx, x):
return x
@staticmethod
def backward(ctx, grad):
self.assertEqual(grad, torch.zeros(1))
return grad
x = torch.ones(1, requires_grad=True)
torch._C._functions.UndefinedGrad()(MyFunction.apply(x)).backward()
def test_dont_materialize_grads(self):
class MyFunction(Function):
@staticmethod
def forward(ctx, x):
ctx.set_materialize_grads(False)
return x
@staticmethod
def backward(ctx, grad):
self.assertIsNone(grad)
return grad
x = torch.ones(1, requires_grad=True)
torch._C._functions.UndefinedGrad()(MyFunction.apply(x)).backward()
def test_set_materialize_non_diff_grads(self):
class Func(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
out0 = x.clone()
out1 = x.clone()
ctx.mark_non_differentiable(out1)
ctx._materialize_non_diff_grads = False
return out0, out1
@staticmethod
def backward(ctx, g0, g1):
self.assertIsNone(g1)
return g0
a = torch.tensor(1., requires_grad=True)
out = Func.apply(a)[0]
out.backward()
def test_legacy_function_deprecation_exception(self):
# Trigger exception
class MyFunction(Function):
def forward(self, x):
return x
def backward(self, grad_output):
return grad_output
# Check exception occurs
with self.assertRaisesRegex(
RuntimeError,
'Legacy autograd function with non-static forward method is deprecated'):
MyFunction()(torch.randn(3, 4))
class SimulateBackwardError(Function):
@staticmethod
def forward(ctx, input):
return input.clone()
@staticmethod
@once_differentiable
def backward(ctx, input):
raise Exception("Simulate error on backward pass")
def test_custom_function_exception(self):
t1 = torch.rand((3, 3), requires_grad=True)
t2 = torch.rand((3, 3), requires_grad=True)
tmp = (t1 + t2) * (t1 + t2)
t3 = TestAutograd.SimulateBackwardError.apply(tmp)
with self.assertRaisesRegex(Exception, "Simulate error on backward pass"):
t3.sum().backward()
def test_custom_function_non_tensor_inputs_outputs(self):
class MyFunction(Function):
@staticmethod
def forward(ctx, t1, t2, scale, t3):
t4 = t1 + t2 * t3
t5 = t1 * t2 + t3
t4 *= scale
t5 *= scale
# Save scale
ctx.scale = scale
ctx.save_for_backward(t1, t2, t3)
return scale, t4, None, True, t5, "bar", t1
@staticmethod
@once_differentiable
def backward(ctx, *grads):
# Verify grads
self.assertEqual(7, len(grads))
self.assertIsNone(grads[0])
self.assertIsNone(grads[2])
self.assertIsNone(grads[3])
self.assertIsNone(grads[5])
scale = ctx.scale
var1, var2, var3 = ctx.saved_tensors
return (
grads[1] * scale + grads[4] * var2 * scale + grads[6],
grads[1] * var3 * scale + grads[4] * var1 * scale,
None,
grads[1] * var2 * scale + grads[4] * scale,
)
t1 = torch.rand(10, dtype=torch.double, requires_grad=True)
t2 = torch.rand(10, dtype=torch.double, requires_grad=True)
t3 = torch.rand(10, dtype=torch.double)
scale = random.randint(0, 10)
res = MyFunction.apply(t1, t2, scale, t3)
self.assertEqual(scale, res[0])
self.assertEqual((t1 + t2 * t3) * scale, res[1])
self.assertEqual(None, res[2])
self.assertEqual(True, res[3])
self.assertEqual((t1 * t2 + t3) * scale, res[4])
self.assertEqual("bar", res[5])
self.assertEqual(t1, res[6])
# Validate running backward.
torch.autograd.backward([res[1].sum(), res[4].sum(), res[6].sum()])
self.assertIsNotNone(t1.grad)
self.assertIsNotNone(t2.grad)
self.assertIsNone(t3.grad)
# Test gradcheck
def foo(t1, t2, t3):
res = MyFunction.apply(t1, t2, scale, t3)
return res[1], res[4], res[6]
gradcheck(foo, (t1, t2, t3))
def test_custom_function_no_tensors(self):
class MyFunction(Function):
@staticmethod
def forward(ctx, t1, t2, scale, t3):
t4 = t1 + t2 * t3
t5 = t1 * t2 + t3
t4 *= scale
t5 *= scale
return scale, t4, None, True, t5, "bar", t1
@staticmethod
@once_differentiable
def backward(ctx, *args):
return (args[0], args[1], None, args[2])
t1 = random.random()
t2 = random.random()
t3 = random.random()
scale = random.randint(0, 10)
res = MyFunction.apply(t1, t2, scale, t3)
self.assertEqual(scale, res[0])
self.assertEqual((t1 + t2 * t3) * scale, res[1])
self.assertEqual(None, res[2])
self.assertEqual(True, res[3])
self.assertEqual((t1 * t2 + t3) * scale, res[4])
self.assertEqual("bar", res[5])
self.assertEqual(t1, res[6])
def test_invalid_gradients(self):
class MyFunction(Function):
@staticmethod
def forward(ctx, x):
return x * 2
@staticmethod
def backward(ctx, grad_output):
return torch.randn(10, dtype=torch.float)
with self.assertRaisesRegex(RuntimeError, 'expected shape'):
input = torch.randn(5, 5, dtype=torch.float, requires_grad=True)
MyFunction.apply(input).sum().backward()
def test_unrelated_inputs(self):
# test to ensure grad(grad)check runs successfully even if there is an
# unrelated (but differentiable) inputs
def my_function(x, y):
return x * x
x = torch.rand(10, dtype=torch.double, requires_grad=True)
y = torch.rand(10, dtype=torch.double, requires_grad=True)
gradcheck(my_function, (x, y))
gradgradcheck(my_function, (x, y))
def test_not_implemented_grad(self):
a = torch.rand(2, requires_grad=True)
# if grad for nextafter ends up being implemented, this should be changed
y = torch.nextafter(a, a).sum()
with self.assertRaisesRegex(
NotImplementedError,
'the derivative for .* is not implemented'):
y.backward()
def test_not_implemented_fwad(self):
x = torch.randn(3)
v = torch.rand(3)
with fwAD.dual_level():
dual_x = fwAD.make_dual(x, v)
err_msg = r"Trying to use forward AD with .* that does not support it"
hint_msg = "Running forward AD for an OP that does not implement it should raise a NotImplementedError"
with self.assertRaisesRegex(NotImplementedError, err_msg, msg=hint_msg):
# if forward AD ends up being implemented for torch.igamma, choose a different op
torch.igamma(dual_x, dual_x)
def test_traceable_deprecated(self):
class MyFunction(Function):
@staticmethod
def forward(ctx, x):
return x * 2
@staticmethod
def backward(ctx, gO):
return gO * 2
with self.assertWarnsRegex(UserWarning, "is_traceable .*is deprecated"):
MyFunction.is_traceable
with self.assertWarnsRegex(UserWarning, "is_traceable .*is deprecated"):
MyFunction.is_traceable = True
with self.assertWarnsRegex(UserWarning, "is_traceable .*is deprecated"):
class MyFunction(Function):
is_traceable = True
@staticmethod
def forward(ctx, x):
return x * 2
@staticmethod
def backward(ctx, gO):
return gO * 2
with self.assertWarnsRegex(UserWarning, "traceable .*is deprecated"):
@torch.autograd.function.traceable
class MyFunction(Function):
is_traceable = True
@staticmethod
def forward(ctx, x):
return x * 2
@staticmethod
def backward(ctx, gO):
return gO * 2
def test_will_engine_execute_node(self):
counter = [0]
class MyFunction(Function):
@staticmethod
def forward(ctx, x):
return x * 2
@staticmethod
def backward(ctx, gO):
return gO * 2
def get_grad_fn(t):
if t.requires_grad and t.grad_fn is None:
return t.clone().grad_fn.next_functions[0][0]
else:
return t.grad_fn
a = torch.randn(2, 3, 4, requires_grad=True)
a2 = torch.randn(2, 3, 4, requires_grad=True)
b = a * a2
b2 = b.cos()
c = MyFunction.apply(b)
should_execute = list(map(get_grad_fn, (a, b, c)))
should_not_execute = list(map(get_grad_fn, (a2, b2)))
def fn(x):
counter[0] += 1
for g in should_execute:
self.assertTrue(torch._C._will_engine_execute_node(g))
for g in should_not_execute:
self.assertFalse(torch._C._will_engine_execute_node(g))
b.register_hook(fn)
c.register_hook(fn)
# .backward(inputs=) is OK
out = c.sum()
torch.autograd.backward(out, inputs=(a, b), retain_graph=True)
self.assertEqual(counter[0], 2)
# .backward() is OK
should_execute = list(map(get_grad_fn, (a, a2, b, c)))
should_not_execute = list(map(get_grad_fn, (b2,)))
torch.autograd.backward(out, retain_graph=True)
# .grad is NOT OK when leaf is passed (this is the current state, subject to change)
with self.assertRaisesRegex(RuntimeError, "are currently running autograd.grad()"):
torch.autograd.grad(out, (a,))
# .grad is OK when non-leaf is passed
a = torch.randn(1, 2, 3, requires_grad=True) * 2
b = a * 2
def fn(x):
# Check a non-leaf
counter[0] += 1
self.assertTrue(torch._C._will_engine_execute_node(b.grad_fn))
b.register_hook(fn)
counter[0] = 0
torch.autograd.grad(b.sum(), (a,))
self.assertEqual(counter[0], 1)
# Verify other errors are raised
with self.assertRaisesRegex(RuntimeError, "during the backward pass"):
torch._C._will_engine_execute_node(out.grad_fn)
with self.assertRaisesRegex(RuntimeError, "expects an grad_fn"):
torch._C._will_engine_execute_node(out)
def test_custom_function_vmap_defaults(self):
class MySquare(Function):
@staticmethod
def forward(x):
return x ** 2
@staticmethod
def setup_context(ctx, inputs, output):
x, = inputs
ctx.save_for_backward(x)
@staticmethod
def backward(ctx, gO):
x, = ctx.saved_tensors
return gO * 2 * x
self.assertFalse(MySquare.generate_vmap_rule)
self.assertTrue(hasattr(MySquare, 'vmap'))
def test_custom_function_setup_context_simple(self):
class MySquare(Function):
@staticmethod
def forward(x):
return x ** 2
@staticmethod
def setup_context(ctx, inputs, output):
x, = inputs
ctx.save_for_backward(x)
@staticmethod
def backward(ctx, gO):
x, = ctx.saved_tensors
return gO * 2 * x
x = torch.randn([], requires_grad=True)
y = MySquare.apply(x)
gx, = torch.autograd.grad(y, x)
self.assertEqual(gx, 2 * x)
def test_custom_function_setup_context_multi_output(self):
# Multiple outputs with some non-Tensor outputs.
class MySquare(Function):
@staticmethod
def forward(x):
two_x = x.item() * 2
return x ** 2, two_x
@staticmethod
def setup_context(ctx, inputs, output):
x, = inputs
_, two_x = output
ctx.two_x = two_x
@staticmethod
@once_differentiable
def backward(ctx, gO, _):
return gO * ctx.two_x
x = torch.randn([], requires_grad=True)
y, _ = MySquare.apply(x)
gx, = torch.autograd.grad(y, x)
self.assertEqual(gx, 2 * x)
def test_custom_function_setup_context_multi_input(self):
class MyReshape(Function):
@staticmethod
def forward(x, shape, scale_forward, scale_backward):
return x.reshape(shape) * scale_forward
@staticmethod
def setup_context(ctx, inputs, output):
x, shape, scale_forward, scale_backward = inputs
ctx.scale_backward = scale_backward
ctx.x_shape = x.shape
@staticmethod
def backward(ctx, gO):
return gO.reshape(ctx.x_shape) * ctx.scale_backward, None, None, None
class MyReshapeRef(Function):
@staticmethod
def forward(ctx, x, shape, scale_forward, scale_backward):
ctx.scale_backward = scale_backward
ctx.x_shape = x.shape
return x.reshape(shape) * scale_forward
@staticmethod
def backward(ctx, gO):
return gO.reshape(ctx.x_shape) * ctx.scale_backward, None, None, None
def test(x, shape, scale_forward, scale_backward):
y = MyReshape.apply(x, shape, scale_forward, scale_backward).sum()
gx, = torch.autograd.grad(y, x)
y_expected = MyReshapeRef.apply(x, shape, scale_forward, scale_backward).sum()
gx_expected, = torch.autograd.grad(y_expected, x)
self.assertEqual(y_expected, y)
self.assertEqual(gx_expected, gx)
test(torch.randn(24, requires_grad=True), (3, 8), 7, 11)
test(torch.randn(2, 3, 4, requires_grad=True), (6, 4), -1, 2)
def test_accumulate_grad(self):
grad_output = torch.ones(5, 5)
def compute_grad(create_graph):
x = torch.randn(5, 5, requires_grad=True)
y = x + 2
y.backward(grad_output, retain_graph=True)
x_grad = x.grad
x_grad_clone = x.grad.clone()
y.backward(grad_output, create_graph=create_graph)
return x_grad, x_grad_clone
# Accumulate in-place when create_graph is False
x_grad, x_grad_clone = compute_grad(create_graph=False)
self.assertEqual(x_grad, x_grad_clone * 2)
# Accumulate out-of-place when create_graph is False
x_grad, x_grad_clone = compute_grad(create_graph=True)
self.assertEqual(x_grad, x_grad_clone)
def test_accumulate_grad_tensor_reference(self):
def _test_grad_tensor(params_grad_tensor, backward_grad_tensor, should_preserve_reference, create_graph):
params = torch.tensor([1.5, 1.5]).requires_grad_()
params.grad = params_grad_tensor
grad_saved = params.grad
params.backward(backward_grad_tensor, create_graph=create_graph)
self.assertEqual(id(grad_saved) == id(params.grad), should_preserve_reference)
for create_graph in (False, True):
# Accumulate dense gradient to sparse gradient will change the `params.grad` reference
_test_grad_tensor(
torch.sparse_coo_tensor(torch.tensor([[1, 1]]).long(), torch.tensor([1., 1.])),
torch.tensor([1.5, 1.5]),
False, # never accumulates in-place
create_graph)
# Accumulate dense gradient to dense gradient will preserve the `params.grad` reference,
# but only if create_graph=False.
_test_grad_tensor(
torch.tensor([1.5, 1.5]),
torch.tensor([1.5, 1.5]),
not create_graph,
create_graph)
# Accumulate sparse gradient to sparse gradient will preserve the `params.grad` reference,
# but only if create_graph=False.
_test_grad_tensor(
torch.sparse_coo_tensor(torch.tensor([[1, 1]]).long(), torch.tensor([1., 1.])),
torch.sparse_coo_tensor(torch.tensor([[1, 1]]).long(), torch.tensor([1., 1.])),
not create_graph,
create_graph)
def test_accumulate_grad_with_zero_numel_grad(self):
a = torch.rand(4, 0, requires_grad=True)
b = torch.rand(4, 1, requires_grad=True)
c = a + b
assert c.shape == (4, 0)
c.sum().backward()
self.assertEqual(b.grad, torch.zeros(4, 1))
self.assertEqual(a.grad, torch.zeros(4, 0))
def test_hessian_vector(self):
x = torch.randn(2, 2, requires_grad=True)
y = torch.randn(2, 2, requires_grad=True)
z = x ** 2 + y * x + y ** 2
z.backward(torch.ones(2, 2), create_graph=True)
with torch.no_grad():
x_grad = 2 * x + y
y_grad = x + 2 * y
self.assertEqual(x.grad, x_grad)
self.assertEqual(y.grad, y_grad)
grad_sum = 2 * x.grad + y.grad
grad_sum.backward(torch.ones(2, 2))
x_hv = torch.ones(2, 2) * 5
y_hv = torch.ones(2, 2) * 4
self.assertEqual(x.grad, x_grad + x_hv)
self.assertEqual(y.grad, y_grad + y_hv)
def test_grad(self):
x = torch.randn(2, 2, requires_grad=True)
y = torch.randn(2, 2, requires_grad=True)
z = x ** 2 + y * x + y ** 2
z.backward(torch.ones(2, 2), create_graph=True)
x_grad = 2 * x + y
y_grad = x + 2 * y
self.assertEqual(x.grad, x_grad)
self.assertEqual(y.grad, y_grad)
grad_sum = 2 * x.grad + y.grad
x_hv = torch.autograd.grad(
outputs=[grad_sum], grad_outputs=[torch.ones(2, 2)],
inputs=[x], create_graph=True)
expected_x_hv = torch.ones(2, 2) * 5
expected_y_hv = torch.ones(2, 2) * 4
self.assertEqual(x_hv[0], expected_x_hv)
self.assertEqual(x.grad, x_grad)
self.assertEqual(y.grad, y_grad)
# Test that grad_outputs and outputs have the same shape
grad_out = torch.ones(2)
try:
torch.autograd.grad(
outputs=[grad_sum], grad_outputs=[grad_out],
inputs=[x], create_graph=True)
self.assertFail()
except RuntimeError as error:
self.assertEqual(str(error), "Mismatch in shape: grad_output[0] has a shape of "
+ str(grad_out.shape) + " and output[0] has a shape of "
+ str(grad_sum.shape) + ".")
def test_grad_to_node(self):
def check_matches(out, inp):
ref = torch.autograd.grad(out.sum(), inp)
edge = torch.autograd.graph.get_gradient_edge(inp)
new = torch.autograd.grad(out.sum(), edge)
self.assertEqual(ref, new)
# We need to ensure that our main types of Node work (regular cpp Nodes,
# AccumulateGrad Nodes and custom Function)
x = torch.rand(2, requires_grad=True)
out = x.clone()
check_matches(out, x)
x = x.clone()
out = x.clone()
check_matches(out, x)
x = torch.autograd._functions.Resize.apply(x, (2,))
out = x.clone()
check_matches(out, x)
x = torch.var_mean(x)[1]
out = x.clone()
check_matches(out, x)
def test_grad_to_node_set(self):
x = torch.rand(2, requires_grad=True)
x_edge = torch.autograd.graph.get_gradient_edge(x)
out = x.clone()
with torch.no_grad():
x.set_(torch.rand_like(x))
with self.assertRaisesRegex(RuntimeError, "to not have been used in the graph"):
torch.autograd.grad(out.sum(), x)
# Works
torch.autograd.grad(out.sum(), x_edge)
def test_grad_to_node_inplace(self):
x = torch.rand(2, requires_grad=True).clone()
x_edge = torch.autograd.graph.get_gradient_edge(x)
x *= 2
g_old, g_new = torch.autograd.grad(x.sum(), (x_edge, x))
self.assertEqual(g_old, 2 * torch.ones_like(x))
self.assertEqual(g_new, torch.ones_like(x))
def test_grad_to_node_multi(self):
x = torch.rand(2, requires_grad=True).clone()
y = torch.rand(2, requires_grad=True).clone()
out = x + y
ref = torch.autograd.grad(out.sum(), (x, y))
inp_edges = (GradientEdge(x.grad_fn, x.output_nr), GradientEdge(y.grad_fn, y.output_nr))
new = torch.autograd.grad(out.sum(), inp_edges)
self.assertEqual(ref, new)
def test_grad_to_node_materialize(self):
x = torch.rand(2, requires_grad=True).clone()
edge_x = GradientEdge(x.grad_fn, x.output_nr)
y = torch.rand(2, requires_grad=True).clone()
edge_y = GradientEdge(y.grad_fn, y.output_nr)
out = x.clone()
# Works
torch.autograd.grad(out.sum(), (edge_x, y), allow_unused=True, materialize_grads=True)
torch.autograd.grad(out.sum(), (x, y), allow_unused=True, materialize_grads=True)
torch.autograd.grad(out.sum(), (x, edge_y), allow_unused=True)
with self.assertRaisesRegex(RuntimeError, "materialize_grads cannot be used when the given input is a GradientEdge"):
torch.autograd.grad(out.sum(), (x, edge_y), allow_unused=True, materialize_grads=True)
def test_backward_to_node(self):
x = torch.rand(2, requires_grad=True).clone()
edge_x = GradientEdge(x.grad_fn, x.output_nr)
y = torch.rand(2, requires_grad=True).clone()
edge_y = GradientEdge(y.grad_fn, y.output_nr)
out = x.clone()
# All should work in this case
torch.autograd.backward(out.sum(), inputs=(edge_x, y))
torch.autograd.backward(out.sum(), inputs=(x, y))
torch.autograd.backward(out.sum(), inputs=(x, edge_y))
torch.autograd.backward(out.sum(), inputs=(edge_x, edge_y))
def test_grad_nonleaf(self):
x_init = torch.randn(2, 2, requires_grad=True)
x = x_init
y = torch.randn(2, 2, requires_grad=True)
grad_output = torch.ones(2, 2)
def fn(x):
return x ** 2 + y * x + y ** 2
for _ in range(5):
grad_x, = torch.autograd.grad(
fn(x), x, grad_outputs=grad_output, create_graph=True)
grad_x_expected = 2 * x + y
self.assertIsNone(y.grad)
self.assertIsNone(x.grad)
self.assertEqual(grad_x, grad_x_expected)
x = x + 0.05 * grad_x
val_init = fn(x_init).sum()
val_final = fn(x).sum()
self.assertGreater(val_final, val_init)
x.backward(grad_output)
self.assertIsNotNone(y.grad)
self.assertIsNotNone(x_init.grad)
def test_grad_nonleaf_many_outputs(self):
# This checks an edge case for function callbacks
# We want to capture two grads of a function, but can only
# register a single callback.
x = torch.randn(4, 2, requires_grad=True)
a, b = x.chunk(2)
def hook(*grads):
hook_called[0] = True
hook_called = [False]
x.register_hook(hook)
go = torch.randn(2, 2)
grad_a, grad_b = torch.autograd.grad(
(a + 2 * b), [a, b], grad_outputs=go, create_graph=True)
self.assertEqual(grad_a, go)
self.assertEqual(grad_b, go * 2)
self.assertFalse(hook_called[0])
self.assertIsNone(x.grad)
def test_grad_nonleaf_register_hook(self):
# This checks an edge case for register_hook.
# We want to capture grad of a nonleaf tensor,
# but avoid segfault during backward of other nonleaf tensors
x = torch.randn(5, requires_grad=True)
x_list = x.unbind()
x0 = x_list[0]
hook_results = [None]
def hook(grad):
hook_results[0] = grad
x0.register_hook(hook)