-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathtest_grad.py
More file actions
1944 lines (1507 loc) · 68 KB
/
Copy pathtest_grad.py
File metadata and controls
1944 lines (1507 loc) · 68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from collections.abc import Sequence
from functools import partial
import gc
from typing import Any
# NOTE: Dependency on fdm and NumPy is temporary.
# We will remove it once we have a native way to compute numerical derivatives.
import fdm
import numpy as np
import pytest
import torch
import thunder
import thunder.core.dtypes as dtypes
import thunder.core.devices as devices
from thunder import torch as ltorch
from thunder.core.dtypes import is_exact_dtype, to_dtype as thunder_dtype
from thunder.core.pytree import tree_map, tree_flatten
from thunder.core.transforms import vjp, grad, check_bsym_for_vjp
from thunder.core.utils import flatten_func, is_cpu_scalar_tensor
from thunder.tests.framework import (
instantiate,
NOTHING,
ops,
run_snippet,
assert_closer,
IN_CI,
requiresCUDA,
)
from thunder.tests.make_tensor import make_tensor, make_tensor_like
from thunder.tests.opinfos import get_opinfo, opinfos, tensor_creation_ops
from thunder.tests.utils import is_output_differentiable, filter_differentiable_outputs
# TODO: Move this to thunder.tests.opinfos
op_skip = {
# See issue "Support closures of torch.Tensor"
# TODO: AttributeError: 'Tensor' object has no attribute 'true_dtype'
"masked_fill",
# TODO: RuntimeError: Expected index=tensor([2, 3, 2, 0, 3, 1, 0, 2],
# device='cuda:0', dtype=torch.int32) to be a TensorProxy!
"index_select",
# Finite difference approximation doesn't work for this function
"embedding",
"index_put",
"batch_norm",
"instance_norm",
"torch_type",
"type_as",
}
if not torch.cuda.is_available():
# Requires CUDA runtime to be available (fails on CPU only runtimes).
op_skip.add("cuda")
# Don't rely on the generated list of supported ops.
# TODO: modify the generated list to support composite ops
vjp_op_force = {
"abs", # There's no clang.abs or prims.abs OpInfo, only torch.abs
"amax",
"amin",
"cat",
"softmax",
"to",
"linear",
"matmul",
"var",
"var_mean",
"interpolate",
"prod",
"repeat",
"split",
"stack",
"cumsum",
"mse_loss",
"adaptive_avg_pool2d",
"max_pool2d",
"local_response_norm",
}
def _is_exact_dtype(torch_dtype):
"""Check if the given torch.dtype is an exact dtype.
Args:
torch_dtype (torch.dtype): The torch dtype to check.
Returns:
bool: True if the given torch.dtype is an exact dtype, False otherwise.
"""
return is_exact_dtype(thunder_dtype(torch_dtype))
def _generate_supported_op_list(checker):
"""Generate a list of operators that is supported by the given checker.
Args:
checker (callable): A function that takes an operator info object and returns True if the operator
satisfies the condition.
Returns:
generator: A generator of operator info objects that support vjp.
"""
from thunder.core.transforms import trace_interpreter_skip_list
for opinfo in opinfos:
if opinfo not in tensor_creation_ops and opinfo.name not in op_skip:
if opinfo.dtypes().intersection({dtypes.float64}) == set():
continue
samples = iter(opinfo.sample_inputs("cpu", dtypes.float64, requires_grad=True))
while (sample := next(samples, None)) is not None:
trc = thunder.trace()(opinfo.op, *sample.args, **sample.kwargs)
all_skipped = all(s.sym.id in trace_interpreter_skip_list for s in trc.bound_symbols)
if all_skipped:
continue
all_supported = all(checker(s) for s in trc.bound_symbols)
if all_supported:
yield opinfo.name
supported_vjp_ops = set(_generate_supported_op_list(check_bsym_for_vjp)).union(vjp_op_force)
def _to_numpy(x):
"""Convert a torch.Tensor or a numpy.ndarray to a numpy.ndarray.
Args:
x (torch.Tensor or numpy.ndarray): The input tensor.
Returns:
numpy.ndarray: The output array.
Raises:
ValueError: If the input is not a torch.Tensor or a numpy.ndarray.
"""
if isinstance(x, torch.Tensor):
x = x.detach().cpu().numpy()
if isinstance(x, np.ndarray):
return x
raise ValueError(f"_to_numpy: Unsupported type {type(x)}")
def _from_numpy(x, like):
"""Convert a numpy.ndarray to a torch.Tensor.
Args:
x (torch.Tensor or numpy.ndarray or numpy.float64): The input tensor.
like (torch.Tensor): The tensor to use as a reference for the device and dtype.
Returns:
torch.Tensor: The output tensor.
Raises:
ValueError: If the input is not a torch.Tensor, a numpy.ndarray or a numpy.float64.
"""
assert isinstance(like, torch.Tensor), f"_from_numpy: Unsupported type of the second argument {type(like)}"
if isinstance(x, np.ndarray):
return torch.from_numpy(x).to(device=like.device)
if isinstance(x, torch.Tensor) or isinstance(x, np.float64):
return torch.tensor(x, device=like.device, dtype=like.dtype)
raise ValueError(f"_from_numpy: Unsupported type of the first argument {type(x)}")
def numerical_jvp(f):
"""Compute the numerical Jacobian-vector product of a function.
It's a wrapper around fdm.jvp that converts the inputs and outputs to numpy.ndarray.
It's meant to be used for testing of transforms.vjp.
Args:
f (callable): The function to differentiate.
Returns:
callable: The Jacobian-vector product function.
"""
def jvp(primals, tangents):
assert isinstance(primals, Sequence)
assert isinstance(tangents, Sequence)
assert len(primals) == len(tangents)
np_primals, np_tangents = tree_map(_to_numpy, (primals, tangents))
out_primals = f(*primals)
multiple_outputs = True
if not isinstance(out_primals, Sequence):
out_primals = (out_primals,)
multiple_outputs = False
def ff(*args):
out = f(*args)
if not multiple_outputs:
return (out,)
return out
np_out_primals = tree_map(_to_numpy, out_primals)
np_out_tangents = tuple(np.zeros_like(o, dtype=np.float64) for o in np_out_primals)
for j, out_tangent in enumerate(np_out_tangents):
# Skip computing the jth output tangent if the jth output is 0-sized.
if out_tangent.size == 0:
continue
for i in range(len(primals)):
if _is_exact_dtype(primals[i].dtype):
# It doesn't contribute to the Jacobian-vector product.
continue
# fdm only supports single input single output functions
# Create a function that only varies the `i`th argument.
def f_i(x):
x = _from_numpy(x, like=primals[i])
out = ff(*(primals[:i] + (x,) + primals[i + 1 :]))[j]
return _to_numpy(out)
out_tangent += fdm.jvp(f_i, np_tangents[i])(np_primals[i])
out_tangents = tree_map(lambda x: _from_numpy(x, like=out_primals[0]), np_out_tangents)
if not multiple_outputs:
return out_primals[0], out_tangents[0]
return out_primals, out_tangents
return jvp
def _replace_none_with_zero(x, y):
"""Replace None with torch.tensor(0.0) to avoid errors when computing the dot product.
Args:
x (list): The first list of tensors.
y (list): The second list of tensors.
Returns:
tuple: The two lists of tensors.
"""
x = list(x)
y = list(y)
assert x[0] is not None or y[0] is not None, "Both x and y are None"
for i, (a, b) in enumerate(zip(x, y)):
if a is None or b is None:
device = x[i].device if x[i] is not None else y[i].device
x[i] = torch.tensor(0.0, device=device, dtype=torch.float64)
y[i] = torch.tensor(0.0, device=device, dtype=torch.float64)
return x, y
# If one tensor is a CPU scalar tensor and the other is on CUDA, move the scalar tensor to CUDA
# Then do the ravel and dot operation
def _tensor_dot(x, y):
if is_cpu_scalar_tensor(x) and y.is_cuda:
x = x.cuda()
elif is_cpu_scalar_tensor(y) and x.is_cuda:
y = y.cuda()
return torch.dot(x.ravel().type(torch.float64), y.ravel().type(torch.float64))
def _dot(x, y):
"""Compute the dot product of two lists of tensors.
Args:
x (list): The first list of tensors.
y (list): The second list of tensors.
Returns:
torch.Tensor: The dot product.
"""
x, y = _replace_none_with_zero(x, y)
assert all(isinstance(a, torch.Tensor) and isinstance(b, torch.Tensor) for a, b in zip(x, y)), (
"Not all elements are torch.Tensor"
)
return sum([_tensor_dot(a, b) for a, b in zip(x, y)])
def check_vjp(f, *primals, comp, executor="torch", set_compile_data: bool = False, prologue_required: bool = False):
"""Check that the vector-Jacobian product of a function is correct.
Args:
f (callable): The function to differentiate.
*primals (torch.Tensor): The input tensors.
executor (str): The executor to use. Defaults to "torch".
atol (float): Absolute tolerance. Defaults to None.
rtol (float): Relative tolerance. Defaults to None.
Raises:
AssertionError: If the vector-Jacobian product is not correct.
"""
# Let f be a function from vectors of size n to vectors of size m.
# Its Jacobian is a matrix J of size m x n.
# Represent by J^* the conjugate transpose (adjoint) of J.
# J^* is a matrix of size n x m.
# For any vector v of size m, J^* v is a vector of size n.
# For any vector u of size n, J u is a vector of size m.
# The dot product of J^* v and u is the same as the dot product of v and J u.
# This function checks that the dot product of J^* v and u is the same as the dot product of v and J u.
# 〈J u, v〉 == 〈u, J* v〉
# Since u and v can be arbitrary, we take u = rand_like(primals), and v = rand_like(f(primals)).
# We compute J u using numerical_jvp, and J* v using Thunder's vjp. That way we check correctness of Thunder's vjp.
# Using finite differences we can compute J u, but we can't compute J* v, without computing full J, which is expensive.
make = partial(make_tensor_like, low=0, high=1)
u = tree_map(make, primals)
# dirty little trick for speed: skip the prologue, however, the prologue is required when
# there are non-differentiable kwargs
jf = executor.make_callable(f, disable_torch_autograd=True)
# if there are things the prologue passes to the epilogue, we need the prologue
# this happens e.g. if the function returns inputs
prologue_trc = thunder.compile_data(jf).get_computation_and_inputs(*primals)[0].prologue_traces[-1]
prologue_required = prologue_required or prologue_trc.output[1] # non-empty prologue_to_epilogue
if prologue_required:
comp_f = jf
else:
comp_f = thunder.compile_data(jf).get_computation_and_inputs(*primals)[0].computation_fn
outs_p, J_u = numerical_jvp(comp_f)(primals, u)
multiple_results = isinstance(outs_p, Sequence)
v = tree_map(make, outs_p)
if set_compile_data:
with thunder.core.compile_data.compile_data_and_stats(thunder.compile_data(jf), None):
initial_trace_vjp_f = thunder.trace()(vjp(f), primals, v)
else:
initial_trace_vjp_f = thunder.trace()(vjp(f), primals, v)
_, J_star_v = executor.make_callable(initial_trace_vjp_f.python_callable(), disable_torch_autograd=True)(primals, v)
if not multiple_results:
v = (v,)
J_u = (J_u,)
J_u_v = _dot(J_u, v)
u_J_star_v = _dot(u, J_star_v)
if J_u_v.isnan().any():
# TODO: find a better way to handle NaNs in finite differences
return # skip this sample
comp(J_u_v, u_J_star_v)
def _is_differentiable(x):
"""Check if a tensor is allowed to be sent as an argument to a differentiable function.
Args:
x (torch.Tensor): The tensor to check.
Returns:
bool: True if the tensor is differentiable, False otherwise.
"""
if isinstance(x, torch.Tensor):
# Allow passing through bool and integer tensors
# Their gradient is None
if _is_exact_dtype(x.dtype):
return True
return x.requires_grad
# NOTE: we skip testing Python numbers for now
# because internally fp32 may be used for computations with PyTorch
# leading to numerical differences
return False
def _make_differentiable_wrapper(func, args):
"""Make a wrapper for a function that takes a subset of differentiable arguments.
Args:
func (callable): The function to wrap.
args (tuple): The arguments to the function.
Returns:
tuple: A tuple containing the wrapper and the filtered arguments.
"""
differentiable_args_idx = tuple(i for i, arg in enumerate(args) if _is_differentiable(arg))
def wrapper(*differentiable_args):
args_iter = iter(differentiable_args)
full_args = [next(args_iter) if i in differentiable_args_idx else arg for i, arg in enumerate(args)]
return func(*full_args)
filtered_args = tuple(arg for i, arg in enumerate(args) if i in differentiable_args_idx)
return wrapper, filtered_args
def snippet_vjp_correctness(func, args, comp, executor, set_compile_data, prologue_required):
check_vjp(
func,
*args,
comp=comp,
executor=executor,
set_compile_data=set_compile_data,
prologue_required=prologue_required,
)
# TODO Use the given comparator
# TODO(crcrpar): Reason special-casing `adaptive_avg_pool2d` -- https://github.com/Lightning-AI/lightning-thunder/issues/1178
# With the slight revert for the mentioned issue, the VJP rule for `adaptive_avg_pool2d` is unavailable
# unless compile data is available, as it's registered to `TorchExecutor.implmap` but not to
# `thunder.core.transforms.augmented_forward_impls`.
@ops((op for op in opinfos if op.name in supported_vjp_ops), supported_dtypes=(dtypes.float64,))
def test_vjp_correctness(op, device, dtype, executor, comp):
at_least_one_differentiable_input = False
eps = 1e-2
for sample in op.sample_inputs(device, dtype, requires_grad=True):
# Here we convert any args in the sample to thunder args (specifically
# to thunder dtypes). It was necessary to add this for the
# convert_element_type tests, which have a non-differentiable argument
# `dtype`. That argument is typically provided as a `torch.dtype`. In
# the lines below, we strip non-differentiable arguments before
# evaluating the op, which means stripped arguments do not undergo the
# usual conversions in thunder.__init__._make_proxies(). The
# sample.thunder() line below attempts to approximate those conversions
# for non-differentiable arguments like dtypes so that the test will
# execute properly.
# NOTE: While `convert_element_type` is skipeed as of https://github.com/Lightning-AI/lightning-thunder/pull/2213
# as in https://github.com/Lightning-AI/lightning-thunder/blob/dbf6bad3/thunder/tests/opinfos.py#L3324-L3346,
# `torch.Tensor.view(dtype)` seems to require `torch.dtype` to be kept as is, opposite to `convert_element_type`.
if op.name != "view":
sample = sample.thunder() # converts torch.dtype to thunder.dtype
sample = sample.remove_singularities(op, eps)
flat_op, flat_args, spec = flatten_func(op.op, sample.args, sample.kwargs)
filtered_op, filtered_args = _make_differentiable_wrapper(flat_op, flat_args)
if len(filtered_args) == 0:
continue
at_least_one_differentiable_input = True
result = run_snippet(
snippet_vjp_correctness,
op,
device,
dtype,
filtered_op,
filtered_args,
comp,
executor,
"adaptive_avg_pool2d" in op.name,
len(sample.kwargs) != 0,
)
if result is not None:
return result
if not at_least_one_differentiable_input:
raise pytest.skip("No differentiable inputs found")
# Embedding is a special case because its Jacobian product can't be approximated
# with finite differences
@ops((op for op in opinfos if op.name == "embedding"), supported_dtypes=(dtypes.float64,))
def test_vjp_correctness_embedding_manual(op, device, dtype, executor, comp):
for sample in op.sample_inputs(device, dtype, requires_grad=True):
# Compute vjp result using PyTorch
out = op.torch_reference(*sample.args, **sample.kwargs)
v = make_tensor_like(out)
expected = torch.autograd.grad(out, sample.args[1], v)
# Compute vjp result using Thunder
flat_op, flat_args, spec = flatten_func(op.op, sample.args, sample.kwargs)
filtered_op, filtered_args = _make_differentiable_wrapper(flat_op, flat_args)
initial_trace = thunder.trace()(vjp(filtered_op), filtered_args, (v,))
actual_out, (gindices, gweight) = executor.make_callable(
initial_trace.python_callable(), disable_torch_autograd=True
)(filtered_args, (v,))
assert gindices is None, "gindices should be None"
comp(gweight, expected[0])
comp(actual_out, out)
@ops((op for op in opinfos if op.name == "type_as"), supported_dtypes=(dtypes.float64,))
def test_vjp_correctness_type_as_manual(op, device, dtype, executor, comp):
for sample in op.sample_inputs(device, dtype, requires_grad=True):
# Compute vjp result using PyTorch
out = op.torch_reference(*sample.args, **sample.kwargs)
v = make_tensor_like(out)
expected = torch.autograd.grad(out, sample.args[0], v)
# Compute vjp result using Thunder
flat_op, flat_args, spec = flatten_func(op.op, sample.args, sample.kwargs)
filtered_op, filtered_args = _make_differentiable_wrapper(flat_op, flat_args)
initial_trace = thunder.trace()(vjp(flat_op), filtered_args, (v,))
actual_out = executor.make_callable(initial_trace.python_callable(), disable_torch_autograd=True)(
filtered_args, (v,)
)
comp(actual_out[1][0], expected[0])
comp(actual_out[0], out)
@ops(
(get_opinfo("batch_norm"), get_opinfo("instance_norm")),
supported_dtypes=(dtypes.float64,),
)
def test_vjp_correctness_batch_norm_manual(op, device, dtype, executor, comp):
from thunder.tests.framework import nvFuserTestExecutor
if type(executor) is nvFuserTestExecutor and dtype is dtypes.float64:
pytest.skip("nvFuser issue #1964")
for sample in op.sample_inputs(device, dtype, requires_grad=True):
# Compute vjp result using PyTorch
weight = sample.args[3]
bias = sample.args[4]
# Torch fails with "RuntimeError: tensor does not have a device"
if weight is None and bias is not None:
continue
out = op.torch_reference(*sample.args, **sample.kwargs)
v = make_tensor_like(out)
grad_inputs = [x for x in (sample.args[0], weight, bias) if x is not None]
expected = torch.autograd.grad(out, grad_inputs, v)
# Compute vjp result using Thunder
flat_op, flat_args, spec = flatten_func(op.op, sample.args, sample.kwargs)
initial_trace = thunder.trace()(vjp(flat_op), flat_args, (v,))
actual_out, actual_grad = executor.make_callable(initial_trace.python_callable(), disable_torch_autograd=True)(
flat_args, (v,)
)
actual_grad = [
x
for x, grad_input in zip(actual_grad, sample.args[:5])
if grad_input is not None and grad_input.requires_grad
]
comp = partial(comp, equal_nan=True)
comp(actual_out, out)
assert len(actual_grad) == len(expected)
for actual, expect in zip(actual_grad, expected):
comp(actual, expect)
# Testing with finite differences has flaky accuracy fails
@ops((op for op in opinfos if op.name == "index_put"), supported_dtypes=(dtypes.float64,))
def test_vjp_correctness_index_put_manual(op, device, dtype, executor, comp):
for sample in op.sample_inputs(device, dtype, requires_grad=True):
# skip the test cases when indices > 1D or indices are bool
# values.requires_grad is used here just as a way to distinguish unsupported cases
if not sample.args[2].requires_grad:
continue
# Compute vjp result using PyTorch
out = op.torch_reference(*sample.args, **sample.kwargs)
v = make_tensor_like(out)
# args: a, indices, values, accumulate
grad_inputs = [sample.args[0], sample.args[2]]
expected = torch.autograd.grad(out, grad_inputs, v)
# Compute vjp result using Thunder
flat_op, flat_args, spec = flatten_func(op.op, sample.args, sample.kwargs)
initial_trace = thunder.trace()(vjp(flat_op), flat_args, (v,))
actual_out, actual_grad = executor.make_callable(initial_trace.python_callable(), disable_torch_autograd=True)(
flat_args, (v,)
)
comp(actual_out, out)
comp(actual_grad[0], expected[0])
comp(actual_grad[-2], expected[1])
# NOTE Scaled_Dot_Product_Efficient_Attention_Backward does not support fp64 dtypes
# RuntimeError: Only fp32, half & bf16 supported at the moment
@ops(
(get_opinfo("grad_forward_scaled_dot_product_attention"),),
supported_dtypes=(dtypes.float16, dtypes.bfloat16),
supported_devicetypes=(devices.DeviceType.CUDA,),
)
def test_vjp_correctness_sdpa_manual(op, device, dtype, executor, comp):
from thunder.common import CompileData
from thunder.core.compile_data import compile_data_and_stats
for sample in op.sample_inputs(device, dtype, requires_grad=True):
from thunder.executors.sdpaex import sdpa_ex
# Enforce tensor arguments are contiguous for torch reference
contiguous_args = list(map(lambda a: a.contiguous() if isinstance(a, torch.Tensor) else a, sample.args))
# query, key, value
grad_inputs = list(contiguous_args[:3])
if (attn_mask := sample.args[3]) is not None and attn_mask.requires_grad:
grad_inputs.append(attn_mask)
# Compute vjp result using PyTorch
expect_out = op.torch_reference(*contiguous_args, **sample.kwargs)
v = make_tensor_like(expect_out)
expected_grad = torch.autograd.grad(expect_out, grad_inputs, v)
# Compute vjp result using Thunder
flat_op, flat_args, spec = flatten_func(op.op, sample.args, sample.kwargs)
filtered_op, filtered_args = _make_differentiable_wrapper(flat_op, flat_args)
cd = CompileData(
fn=vjp(filtered_op),
executors_list=[sdpa_ex, *executor.executors_list()],
disable_preprocessing=True,
)
with compile_data_and_stats(cd, None):
initial_trace = thunder.trace()(vjp(filtered_op), filtered_args, (v,))
from thunder.executors.sdpaex import sdpea_gradfwd, sdpea_bwd, sdpfa_gradfwd, sdpfa_bwd
# This is a workaround for the issue with python_ctx replacing symbols
# with their "call_ctx" values which are not traceable and accept only
# regular torch tensors
initial_trace.python_ctx = lambda: {
"sdpaex_grad_forward_scaled_dot_product_efficient_attention": sdpea_gradfwd,
"sdpaex_scaled_dot_product_efficient_attention_backward": sdpea_bwd,
"sdpafx_grad_forward_scaled_dot_product_efficient_attention": sdpfa_gradfwd,
"sdpafx_scaled_dot_product_efficient_attention_backward": sdpfa_bwd,
}
actual_out, actual_grad = thunder.jit(
initial_trace.python_callable(),
disable_torch_autograd=True,
executors=[sdpa_ex, *executor.executors_list()],
)(filtered_args, (v,))
comp(actual_out, expect_out, atol=1e-3, rtol=1e-3)
# compare gradients of query, key, value, and attn_mask
for eg, ag in zip(expected_grad, actual_grad):
comp(eg, ag, atol=7e-3, rtol=7e-3)
@ops((get_opinfo("zeta"),), supported_dtypes=(dtypes.float64,))
def test_vjp_correctness_zeta_manual(op, device, dtype, executor, comp):
for sample in op.sample_inputs(device, dtype, requires_grad=True, no_rhs_numbers=True):
# Compute vjp result using PyTorch
out = op.torch_reference(*sample.args, **sample.kwargs)
v = make_tensor_like(out)
expected_grad = torch.autograd.grad(out, sample.args[1], v)
# Compute vjp result using Thunder
flat_op, flat_args, spec = flatten_func(op.op, sample.args, sample.kwargs)
initial_trace = thunder.trace()(vjp(flat_op), flat_args, (v,))
actual_out, (grad_lhs, grad_rhs) = executor.make_callable(
initial_trace.python_callable(), disable_torch_autograd=True
)(flat_args, (v,))
assert grad_lhs is None, "grad_lhs should be None"
comp(actual_out, out, equal_nan=True)
comp(grad_rhs, expected_grad[0], equal_nan=True)
@ops((get_opinfo("item"),), supported_dtypes=(dtypes.float64,))
def test_vjp_correctness_torch_item_manual(op, device, dtype, executor, comp):
from thunder.torch import item
for sample in op.sample_inputs(device, dtype, requires_grad=True, no_rhs_numbers=True):
out = op.torch_reference(*sample.args, **sample.kwargs)
flat_op, flat_args, spec = flatten_func(item, sample.args, sample.kwargs)
initial_trace = thunder.trace()(vjp(flat_op), flat_args, (None,))
actual_out, (grad_in,) = executor.make_callable(initial_trace.python_callable(), disable_torch_autograd=True)(
flat_args, (None,)
)
assert grad_in is None, "grad_in should be None"
comp(actual_out, out, equal_nan=True)
@ops((get_opinfo("nll_loss"),), supported_dtypes=(dtypes.float64,))
def test_vjp_correctness_nll_loss_manual(op, device, dtype, executor, comp):
for sample in op.sample_inputs(device, dtype, requires_grad=True, no_rhs_numbers=True):
# Traced backwards function does not follow PyTorch nll_loss behavior with zero element tensors
if sample.args[0].numel() == 0:
continue
# Compute vjp result using PyTorch
out = op.torch_reference(*sample.args, **sample.kwargs)
v = make_tensor_like(out)
expected_grad = torch.autograd.grad(out, sample.args[0], v)
# Compute vjp result using Thunder
flat_op, flat_args, spec = flatten_func(op.op, sample.args, sample.kwargs)
initial_trace = thunder.trace()(vjp(flat_op), flat_args, (v,))
actual_out, grad_out = executor.make_callable(initial_trace.python_callable(), disable_torch_autograd=True)(
flat_args, (v,)
)
comp(actual_out, out)
comp(grad_out[0], expected_grad[0])
@ops((get_opinfo("cross_entropy"),), supported_dtypes=(dtypes.float64,))
def test_vjp_correctness_cross_entropy_manual(op, device, dtype, executor, comp):
for sample in op.sample_inputs(device, dtype, requires_grad=True, no_rhs_numbers=True):
# Traced backwards function does not follow PyTorch cross_entropy behavior with zero element tensors
if sample.args[0].numel() == 0:
continue
# Compute vjp result using PyTorch
out = op.torch_reference(*sample.args, **sample.kwargs)
v = make_tensor_like(out)
expected_grad = torch.autograd.grad(out, sample.args[0], v)
# Compute vjp result using Thunder
flat_op, flat_args, spec = flatten_func(op.op, sample.args, sample.kwargs)
initial_trace = thunder.trace()(vjp(flat_op), flat_args, (v,))
actual_out, grad_out = executor.make_callable(initial_trace.python_callable(), disable_torch_autograd=True)(
flat_args, (v,)
)
comp(actual_out, out)
comp(grad_out[0], expected_grad[0])
@ops((get_opinfo("einsum"),), supported_dtypes=(dtypes.float64,))
def test_vjp_correctness_einsum_manual(op, device, dtype, executor, comp):
from thunder.tests.framework import nvFuserTestExecutor
if type(executor) is nvFuserTestExecutor and dtype is dtypes.float64:
pytest.skip("nvFuser issue #1645")
for sample in op.sample_inputs(device, dtype, requires_grad=True, no_rhs_numbers=True):
# Compute vjp result using PyTorch
out = op.torch_reference(*sample.args, **sample.kwargs)
v = make_tensor_like(out)
expected_grads = torch.autograd.grad(out, sample.args[1:], v)
# Compute vjp result using Thunder
flat_op, flat_args, spec = flatten_func(op.op, sample.args, sample.kwargs)
initial_trace = thunder.trace()(vjp(flat_op), flat_args, (v,))
actual_out, grads_out = executor.make_callable(initial_trace.python_callable(), disable_torch_autograd=True)(
flat_args, (v,)
)
comp(actual_out, out)
assert len(expected_grads) == len(grads_out) - 1
for torch_grad, thunder_grad in zip(expected_grads, grads_out[1:]):
comp(torch_grad, thunder_grad)
# TODO Extend requires_grad so that tensors produced from thunder.jit functions requires_grad
# and have their autograd functions set properly
# Tests that we track the requires_grad property properly
@instantiate(
dtypes=(dtypes.float32,),
# TODO Reenable this test when we track the requires_grad consistently for all operators
# See https://github.com/Lightning-AI/lightning-thunder/issues/1768
decorators=(pytest.mark.xfail(strict=True, reason="Requires_grad propagation is not implemented"),),
)
def test_requires_grad(executor, device, dtype):
import thunder.torch as ltorch
torch_dtype = ltorch.to_torch_dtype(dtype)
a = make_tensor((2, 2), device=device, dtype=torch_dtype, requires_grad=False)
b = make_tensor((2, 2), device=device, dtype=torch_dtype, requires_grad=False)
ag = make_tensor((2, 2), device=device, dtype=torch_dtype, requires_grad=True)
def foo(a, b):
c = a + b
return c.requires_grad
cfoo = executor.make_callable(foo)
# Tests that when neither inputs requires grad, the result of the addition doesn't, either
result = cfoo(a, b)
assert result is False
# Tests that when one input requires grad, the result of the addition requires grad, too
result = cfoo(ag, b)
assert result is True
def bar(a, b):
c = ltorch.cat((a, b))
return c.requires_grad
cbar = executor.make_callable(bar)
# Tests that when neither inputs requires grad, the result of the cat doesn't, either
result = cbar(a, b)
assert result is False
# Tests that when one input requires grad, the result of the cat requires grad, too
result = cbar(ag, b)
assert result is True
@instantiate(
dtypes=NOTHING,
)
def test_convert_element_type_with_float(executor, device, _):
# Verifies the fix for "grad transform hits error: AttributeError: 'float'
# object has no attribute 'dtype'"
from thunder.core.transforms import value_and_grad
a = make_tensor([5], dtype=torch.float32, device=device)
@value_and_grad
def fn(t0):
return t0 / 2
initial_trace = thunder.trace()(fn, a)
out, (grad,) = executor.make_callable(initial_trace.python_callable(), disable_torch_autograd=True)(a)
torch.testing.assert_close(out, a / 2)
torch.testing.assert_close(grad, torch.ones_like(a) / 2)
@instantiate(
dtypes=NOTHING,
)
def test_multiple_output_vjp(executor, device, _):
from thunder.core.prims import cos, make_prim, sin
from thunder.core.transforms import register_augmented_forward, register_backward, vjp
def sincos_meta(x):
return sin(x), cos(x)
sincos = make_prim("sincos", "sincos", meta=sincos_meta)
@register_augmented_forward("sincos")
def sincos_vjp_rule(x):
out = sincos(x)
saved = out
return out, saved
@register_backward("sincos")
def sincos_backward(sin_x, cos_x, g1, g2):
return g1 * cos_x, g2 * -sin_x
def func(x):
return sincos(x)
x = torch.tensor(1.0)
v = torch.tensor(1.0)
# Let's check that we get the correct error if we don't pass the right number of cotangents
with pytest.raises(RuntimeError, match="Expected cotangents to be a sequence of length 2"):
initial_trace = thunder.trace()(vjp(func), (x,), (v,))
# The "vjp" function defined above is incorrect, let's check that we get the correct error
with pytest.raises(RuntimeError, match="Backward for sincos returned 2 values, but expected at most 1"):
initial_trace = thunder.trace()(vjp(func), (x,), (v, v))
# Let's define a correct sincos_backward function
@register_backward("sincos")
def sincos_backward(sin_x, cos_x, g1, g2): # noqa: F811
return g1 * cos_x + g2 * -sin_x
# It's not possible to teach Thunder about the PyTorch implementation of sincos
# The following doesn't work because the PyTorch executor generates
# a string of code with something like "out1, out2 = <lambda>(input)"
# ops_to_torch_ops_map["sincos"] = lambda x: (torch.sin(x), torch.cos(x))
# Therefore here we'll just check that the trace is correct
trace = thunder.trace()(vjp(func), (x,), (v, v))
# Length of outputs should be two
assert len(trace.output) == 2
# Length of the first output should be two
assert len(trace.output[0]) == 2
# Length of the second output should match the length of primal args
assert len(trace.output[1]) == len(trace.args[0])
# The fifth symbol is sincos
assert trace.bound_symbols[4].sym.name == "sincos"
# The first output should be from sincos
assert trace.output[0] == trace.bound_symbols[4].output
# TODO: see issue
# "thunder/tests/test_grad.py::test_torch_autograd_saved_tensors_memory_release
# is flaky"
@pytest.mark.xfail(strict=False, reason="This test is flaky")
@requiresCUDA
def test_torch_autograd_saved_tensors_memory_release():
# This test checks that the saved tensors are released during compiled
# backward function execution. It's a regression test for the memory leak.
from thunder.core.prims import make_prim
from thunder.core.transforms import register_augmented_forward, register_backward
from thunder.core.proxies import TensorProxy
from thunder.core import codeutils
def noop_meta(x):
return TensorProxy(like=x)
def noop_printer(bsym, out_printables, arg_printables, kwarg_printables):
result_str = f"{codeutils.prettyprint(out_printables, literals_as_underscores=True)} = "
arg_string = ", ".join(codeutils.prettyprint(x, literals_allowed=False) for x in arg_printables)
return result_str + f"{arg_string}.clone()"
noop = make_prim(
"noop",
"noop",
meta=noop_meta,
python_printer=noop_printer,
python_impl=lambda x: x,
)
def noop_backward_meta(x, g):
return TensorProxy(like=g)
def noop_backward_printer(bsym, out_printables, arg_printables, kwarg_printables):
result_str = f"{codeutils.prettyprint(out_printables, literals_as_underscores=True)} = "
return result_str + "torch.tensor(torch.cuda.memory_allocated())"
noop_backward = make_prim(
"noop_backward",
"noop_backward",
meta=noop_backward_meta,
python_printer=noop_backward_printer,
python_impl=lambda x, g: g,
)
@register_augmented_forward("noop")
def noop_vjp_rule(x):
out = noop(x)
saved = (out,)
return out, saved
@register_backward("noop")
def noop_backward_rule(out, g):
return noop_backward(out, g)
def func(x):
x = x + 0
for i in range(10):
x = noop(x)
return x
cfunc = thunder.jit(func, executors=[thunder.executors.torchex.ex])
initial_allocated = torch.cuda.memory_allocated()
x = torch.tensor(1e20, device="cuda", requires_grad=True)
v = torch.tensor(1e20, device="cuda")
fw_out = cfunc(x)
intermediate_allocated = torch.cuda.memory_allocated()
fw_out.backward(v)
final_allocated = torch.cuda.memory_allocated()
assert int(x.grad.item() - initial_allocated) == 2048
assert intermediate_allocated - initial_allocated == 6144
assert final_allocated - initial_allocated == 2048
@instantiate(
dtypes=NOTHING,
)
def test_make_aug_forward_and_backward(executor, device, _):
from thunder.core.vjp_utils import make_aug_forward_and_backward
from thunder.core.prims import mul
def fun(a, b):
return mul(a, b)
@executor.make_callable
def expected_aug_fw(a, b):
return fun(a, b), (a, b)
@executor.make_callable
def fun_bw(a, b, g):
return {"a": g * b, "b": g * a}
x = torch.tensor(2.0, device=device)
y = torch.tensor(3.0, device=device)
v = torch.tensor(1.5, device=device)
trace = thunder.trace()(fun, x, y)
mul_bsym = trace.bound_symbols[2]
assert mul_bsym.sym.name == "mul"
aug_fw, bw = make_aug_forward_and_backward(mul_bsym)
aug_fw = executor.make_callable(aug_fw)
actual_aug_fw, actual_saved = aug_fw(x, y)
expected_aug_fw, expected_saved = expected_aug_fw(x, y)
torch.testing.assert_close(actual_aug_fw, expected_aug_fw)
bw = executor.make_callable(bw)
actual_bw = bw(*actual_saved, v)
expected_bw = fun_bw(*expected_saved, v)
torch.testing.assert_close(actual_bw, expected_bw)
@instantiate(
dtypes=NOTHING,
)
def test_make_aug_forward_and_backward_var_mean(executor, device, _):
# This test checks that the split of the joint forward/backward function for
# var_mean correctly puts the forward part into the augmented forward
# function and the backward part into the backward function without
# overlapping symbols.
from thunder.core.vjp_utils import make_aug_forward_and_backward
from thunder.core.prims import var_mean
def fun(a):
return var_mean(a, (0,), correction=1)
x = torch.tensor((2, 2), device=device, dtype=torch.float32)
trace = thunder.trace()(fun, x)
var_mean_bsym = trace.bound_symbols[-2]
assert var_mean_bsym.sym.name == "var_mean"
aug_fw, bw = make_aug_forward_and_backward(var_mean_bsym)
aug_fw = executor.make_callable(aug_fw)
out, saved = aug_fw(x, (0,), correction=1)
bw = executor.make_callable(bw)
_ = bw(*saved, *out)
bw_trace = thunder.last_traces(bw)[0]
assert "var_mean" not in (s.sym.name for s in bw_trace.bound_symbols)
def test_no_duplicate_backward_registered():
from thunder.core.transforms import backward_impls, _grad_fn_map
same_keys = set(_grad_fn_map.keys()).intersection(set(backward_impls.keys()))
assert not same_keys, f"Duplicate keys: {same_keys}"
@instantiate(
dtypes=NOTHING,