/
gradient.py
2306 lines (1921 loc) · 83.5 KB
/
gradient.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
"""Driver for gradient calculations."""
import time
import warnings
from functools import partial, reduce
from typing import (
TYPE_CHECKING,
Callable,
Dict,
List,
Literal,
Mapping,
MutableSequence,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
)
import numpy as np
import pytensor
from pytensor.compile.ops import ViewOp
from pytensor.configdefaults import config
from pytensor.graph import utils
from pytensor.graph.basic import Apply, NominalVariable, Variable
from pytensor.graph.null_type import NullType, null_type
from pytensor.graph.op import get_test_values
from pytensor.graph.type import Type
if TYPE_CHECKING:
from pytensor.compile.mode import Mode
V = TypeVar("V", bound=Optional[Variable])
# TODO: Refactor this so that it's not a global variable
grad_time: float = 0.0
# TODO: Add `overload` variants
def as_list_or_tuple(
use_list: bool, use_tuple: bool, outputs: Union[V, Sequence[V]]
) -> Union[V, List[V], Tuple[V, ...]]:
"""Return either a single object or a list/tuple of objects.
If `use_list` is True, `outputs` is returned as a list (if `outputs`
is not a list or a tuple then it is converted in a one element list).
If `use_tuple` is True, `outputs` is returned as a tuple (if `outputs`
is not a list or a tuple then it is converted into a one element tuple).
Otherwise (if both flags are false), `outputs` is returned.
"""
if use_list and use_tuple:
raise ValueError("Both flags cannot be simultaneously True")
if use_list or use_tuple:
if isinstance(outputs, Sequence):
if use_list:
return list(outputs)
else:
return tuple(outputs)
else:
if use_list:
return [outputs]
else:
return (outputs,)
else:
if isinstance(outputs, Sequence):
if len(outputs) != 1:
raise ValueError("Wrong arguments; expected a one element list")
return outputs[0]
else:
return outputs
def grad_not_implemented(op, x_pos, x, comment=""):
"""Return an un-computable symbolic variable of type `x.type`.
If any call to `grad` results in an expression containing this
un-computable variable, an exception (e.g. `NotImplementedError`) will be
raised indicating that the gradient on the
`x_pos`'th input of `op` has not been implemented. Likewise if
any call to pytensor.function involves this variable.
Optionally adds a comment to the exception explaining why this
gradient is not implemented.
"""
return (
NullType(
"This variable is Null because the grad method for "
f"input {x_pos} ({x}) of the {op} op is not implemented. {comment}"
)
)()
def grad_undefined(op, x_pos, x, comment=""):
"""Return an un-computable symbolic variable of type `x.type`.
If any call to `grad` results in an expression containing this
un-computable variable, an exception (e.g. `GradUndefinedError`) will be
raised indicating that the gradient on the
`x_pos`'th input of `op` is mathematically undefined. Likewise if
any call to pytensor.function involves this variable.
Optionally adds a comment to the exception explaining why this
gradient is not defined.
"""
return (
NullType(
"This variable is Null because the grad method for "
f"input {x_pos} ({x}) of the {op} op is not implemented. {comment}"
)
)()
class DisconnectedType(Type):
"""A type indicating that a variable is the result of taking the gradient of
``c`` with respect to ``x`` when ``c`` is not a function of ``x``.
It serves as a symbolic placeholder for ``0``, but conveys the extra
information that this gradient is ``0`` because it is disconnected.
"""
def filter(self, data, strict=False, allow_downcast=None):
raise AssertionError(
"If you're assigning to a DisconnectedType you're"
" doing something wrong. It should only be used as"
" a symbolic placeholder."
)
def fiter_variable(self, other):
raise AssertionError(
"If you're assigning to a DisconnectedType you're"
" doing something wrong. It should only be used as"
" a symbolic placeholder."
)
def may_share_memory(a, b):
return False
def value_eq(a, b, force_same_dtype=True):
raise AssertionError(
"If you're assigning to a DisconnectedType you're"
" doing something wrong. It should only be used as"
" a symbolic placeholder."
)
def __str__(self):
return "DisconnectedType"
disconnected_type = DisconnectedType()
def Rop(
f: Union[Variable, Sequence[Variable]],
wrt: Union[Variable, Sequence[Variable]],
eval_points: Union[Variable, Sequence[Variable]],
disconnected_outputs: Literal["ignore", "warn", "raise"] = "raise",
return_disconnected: Literal["none", "zero", "disconnected"] = "zero",
) -> Union[Optional[Variable], Sequence[Optional[Variable]]]:
"""Computes the R-operator applied to `f` with respect to `wrt` at `eval_points`.
Mathematically this stands for the Jacobian of `f` right multiplied by the
`eval_points`.
Parameters
----------
f
The outputs of the computational graph to which the R-operator is
applied.
wrt
Variables for which the R-operator of `f` is computed.
eval_points
Points at which to evaluate each of the variables in `wrt`.
disconnected_outputs
Defines the behaviour if some of the variables in `f`
have no dependency on any of the variable in `wrt` (or if
all links are non-differentiable). The possible values are:
- ``'ignore'``: considers that the gradient on these parameters is zero.
- ``'warn'``: consider the gradient zero, and print a warning.
- ``'raise'``: raise `DisconnectedInputError`.
return_disconnected
- ``'zero'`` : If ``wrt[i]`` is disconnected, return value ``i`` will be
``wrt[i].zeros_like()``.
- ``'none'`` : If ``wrt[i]`` is disconnected, return value ``i`` will be
``None``
- ``'disconnected'`` : returns variables of type `DisconnectedType`
Returns
-------
:class:`~pytensor.graph.basic.Variable` or list/tuple of Variables
A symbolic expression such obeying
``R_op[i] = sum_j (d f[i] / d wrt[j]) eval_point[j]``,
where the indices in that expression are magic multidimensional
indices that specify both the position within a list and all
coordinates of the tensor elements.
If `f` is a list/tuple, then return a list/tuple with the results.
"""
if not isinstance(wrt, (list, tuple)):
_wrt: List[Variable] = [pytensor.tensor.as_tensor_variable(wrt)]
else:
_wrt = [pytensor.tensor.as_tensor_variable(x) for x in wrt]
if not isinstance(eval_points, (list, tuple)):
_eval_points: List[Variable] = [pytensor.tensor.as_tensor_variable(eval_points)]
else:
_eval_points = [pytensor.tensor.as_tensor_variable(x) for x in eval_points]
if not isinstance(f, (list, tuple)):
_f: List[Variable] = [pytensor.tensor.as_tensor_variable(f)]
else:
_f = [pytensor.tensor.as_tensor_variable(x) for x in f]
if len(_wrt) != len(_eval_points):
raise ValueError("`wrt` must be the same length as `eval_points`.")
# Check that each element of wrt corresponds to an element
# of eval_points with the same dimensionality.
for i, (wrt_elem, eval_point) in enumerate(zip(_wrt, _eval_points)):
try:
if wrt_elem.type.ndim != eval_point.type.ndim:
raise ValueError(
f"Elements {i} of `wrt` and `eval_point` have mismatched dimensionalities: "
f"{wrt_elem.type.ndim} and {eval_point.type.ndim}"
)
except AttributeError:
# wrt_elem and eval_point don't always have ndim like random type
# Tensor, Sparse have the ndim attribute
pass
seen_nodes: Dict[Apply, Sequence[Variable]] = {}
def _traverse(node):
"""TODO: writeme"""
if node is None:
return
op = node.op
inputs = node.inputs
# Compute the evaluation points corresponding to each of the
# inputs of the node
local_eval_points = []
for inp in inputs:
if inp in _wrt:
local_eval_points.append(_eval_points[_wrt.index(inp)])
elif inp.owner is None:
try:
local_eval_points.append(inp.zeros_like())
except Exception:
# None should be used for non-differentiable
# arguments, like for example random states
local_eval_points.append(None)
elif inp.owner in seen_nodes:
local_eval_points.append(
seen_nodes[inp.owner][inp.owner.outputs.index(inp)]
)
else:
# We actually need to compute the R_op for this node
_traverse(inp.owner)
local_eval_points.append(
seen_nodes[inp.owner][inp.owner.outputs.index(inp)]
)
same_type_eval_points = []
for x, y in zip(inputs, local_eval_points):
if y is not None:
if not isinstance(x, Variable):
x = pytensor.tensor.as_tensor_variable(x)
if not isinstance(y, Variable):
y = pytensor.tensor.as_tensor_variable(y)
try:
y = x.type.filter_variable(y)
except TypeError:
# This is a hack
# Originally both grad and Rop were written
# with the assumption that a variable and the
# gradient wrt that variable would have the same
# dtype. This was a bad assumption because the
# gradient wrt an integer can take on non-integer
# values.
# grad is now fixed, but Rop is not, so when grad
# does the right thing and violates this assumption
# we have to make it be wrong for Rop to keep working
# Rop should eventually be upgraded to handle integers
# correctly, the same as grad
y = pytensor.tensor.cast(y, x.type.dtype)
y = x.type.filter_variable(y)
assert x.type.in_same_class(y.type)
same_type_eval_points.append(y)
else:
same_type_eval_points.append(y)
seen_nodes[node] = op.R_op(node.inputs, same_type_eval_points)
# end _traverse
# Populate the dictionary
for out in _f:
_traverse(out.owner)
rval: List[Optional[Variable]] = []
for out in _f:
if out in _wrt:
rval.append(_eval_points[_wrt.index(out)])
elif (
seen_nodes.get(out.owner, None) is None
or seen_nodes[out.owner][out.owner.outputs.index(out)] is None
):
message = (
"Rop method was asked to compute the gradient "
"with respect to a variable that is not part of "
"the computational graph of variables in wrt, or is "
f"used only by a non-differentiable operator: {out}"
)
if disconnected_outputs == "ignore":
pass
elif disconnected_outputs == "warn":
warnings.warn(message, stacklevel=2)
elif disconnected_outputs == "raise":
message = utils.get_variable_trace_string(out)
raise DisconnectedInputError(message)
else:
raise ValueError(
"Invalid value for keyword "
"'disconnected_inputs', valid values are "
"'ignore', 'warn' and 'raise'."
)
if return_disconnected.lower() == "zero":
rval.append(pytensor.tensor.zeros_like(out))
elif return_disconnected.lower() == "none":
rval.append(None)
elif return_disconnected.lower() == "disconnected":
rval.append(disconnected_type())
else:
raise ValueError(
"Invalid value for keyword "
"'return_disconnected', valid values are "
"'zero', 'None' and 'Disconnected'."
)
else:
rval.append(seen_nodes[out.owner][out.owner.outputs.index(out)])
using_list = isinstance(f, list)
using_tuple = isinstance(f, tuple)
return as_list_or_tuple(using_list, using_tuple, rval)
def Lop(
f: Union[Variable, Sequence[Variable]],
wrt: Union[Variable, Sequence[Variable]],
eval_points: Union[Variable, Sequence[Variable]],
consider_constant: Optional[Sequence[Variable]] = None,
disconnected_inputs: Literal["ignore", "warn", "raise"] = "raise",
) -> Union[Optional[Variable], Sequence[Optional[Variable]]]:
"""Computes the L-operator applied to `f` with respect to `wrt` at `eval_points`.
Mathematically this stands for the Jacobian of `f` with respect to `wrt`
left muliplied by the `eval_points`.
Parameters
----------
f
The outputs of the computational graph to which the L-operator is
applied.
wrt
Variables for which the L-operator of `f` is computed.
eval_points
Points at which to evaluate each of the variables in `wrt`.
consider_constant
See `grad`.
disconnected_inputs
See `grad`.
Returns
-------
:class:`~pytensor.graph.basic.Variable` or list/tuple of Variables
A symbolic expression satisfying
``L_op[i] = sum_i (d f[i] / d wrt[j]) eval_point[i]``
where the indices in that expression are magic multidimensional
indices that specify both the position within a list and all
coordinates of the tensor elements.
If `f` is a list/tuple, then return a list/tuple with the results.
"""
if not isinstance(eval_points, (list, tuple)):
_eval_points: List[Variable] = [pytensor.tensor.as_tensor_variable(eval_points)]
else:
_eval_points = [pytensor.tensor.as_tensor_variable(x) for x in eval_points]
if not isinstance(f, (list, tuple)):
_f: List[Variable] = [pytensor.tensor.as_tensor_variable(f)]
else:
_f = [pytensor.tensor.as_tensor_variable(x) for x in f]
grads = list(_eval_points)
if not isinstance(wrt, (list, tuple)):
_wrt: List[Variable] = [pytensor.tensor.as_tensor_variable(wrt)]
else:
_wrt = [pytensor.tensor.as_tensor_variable(x) for x in wrt]
assert len(_f) == len(grads)
known = dict(zip(_f, grads))
ret = grad(
cost=None,
known_grads=known,
consider_constant=consider_constant,
wrt=_wrt,
disconnected_inputs=disconnected_inputs,
)
using_list = isinstance(wrt, list)
using_tuple = isinstance(wrt, tuple)
return as_list_or_tuple(using_list, using_tuple, ret)
def grad(
cost: Optional[Variable],
wrt: Union[Variable, Sequence[Variable]],
consider_constant: Optional[Sequence[Variable]] = None,
disconnected_inputs: Literal["ignore", "warn", "raise"] = "raise",
add_names: bool = True,
known_grads: Optional[Mapping[Variable, Variable]] = None,
return_disconnected: Literal["none", "zero", "disconnected"] = "zero",
null_gradients: Literal["raise", "return"] = "raise",
) -> Union[Optional[Variable], Sequence[Optional[Variable]]]:
"""
Return symbolic gradients of one cost with respect to one or more variables.
For more information about how automatic differentiation works in PyTensor,
see :mod:`gradient`. For information on how to implement the gradient of
a certain Op, see :func:`grad`.
Parameters
----------
cost
Value that we are differentiating (i.e. for which we want the
gradient). May be `None` if `known_grads` is provided.
wrt
The term(s) with respect to which we want gradients.
consider_constant
Expressions not to backpropagate through.
disconnected_inputs : {'ignore', 'warn', 'raise'}
Defines the behaviour if some of the variables in `wrt` are
not part of the computational graph computing `cost` (or if
all links are non-differentiable). The possible values are:
- ``'ignore'``: considers that the gradient on these parameters is zero
- ``'warn'``: consider the gradient zero, and print a warning
- ``'raise'``: raise `DisconnectedInputError`
add_names
If ``True``, variables generated by `grad` will be named
``(d<cost.name>/d<wrt.name>)`` provided that both `cost` and `wrt`
have names.
known_grads
An ordered dictionary mapping variables to their gradients. This is
useful in the case where you know the gradients of some
variables but do not know the original cost.
return_disconnected
- ``'zero'`` : If ``wrt[i]`` is disconnected, return value ``i`` will be
``wrt[i].zeros_like()``
- ``'none'`` : If ``wrt[i]`` is disconnected, return value ``i`` will be
``None``
- ``'disconnected'`` : returns variables of type `DisconnectedType`
null_gradients
Defines the behaviour when some of the variables in `wrt` have a
null gradient. The possibles values are:
- ``'raise'`` : raise a `NullTypeGradError` exception
- ``'return'`` : return the null gradients
Returns
-------
:class:`~pytensor.graph.basic.Variable` or list/tuple of Variables
A symbolic expression for the gradient of `cost` with respect to each
of the `wrt` terms. If an element of `wrt` is not differentiable with
respect to the output, then a zero variable is returned.
"""
t0 = time.perf_counter()
if cost is None:
if known_grads is None:
raise ValueError("cost and known_grads can't both be None.")
if cost is not None and isinstance(cost.type, NullType):
raise ValueError(
"Can't differentiate a NaN cost. "
f"Cost is NaN because {cost.type.why_null}"
)
if cost is not None and cost.type.ndim != 0:
raise TypeError("Cost must be a scalar.")
if not isinstance(wrt, Sequence):
_wrt: List[Variable] = [wrt]
else:
_wrt = list(wrt)
outputs = []
if cost is not None:
outputs.append(cost)
if known_grads is not None:
outputs.extend(list(known_grads.keys()))
var_to_app_to_idx = _populate_var_to_app_to_idx(outputs, _wrt, consider_constant)
# build a dict mapping var to the gradient of cost with respect to var
grad_dict = {}
if known_grads is None:
known_grads = {}
assert isinstance(known_grads, dict)
# The gradient of the cost is 1 unless specified otherwise by known_grads.
if cost is not None:
if cost in known_grads:
g_cost = known_grads[cost]
else:
g_cost = _float_ones_like(cost)
# g_cost may be Disconnected or NullType. A creative use of the
# function, sure, but nonetheless one we can and should support.
# So before we try to cast it make sure it even has a dtype
if (
hasattr(g_cost.type, "dtype")
and cost.type.dtype in pytensor.tensor.type.continuous_dtypes
):
# Here we enforce the constraint that floating point variables
# have the same dtype as their gradient.
g_cost = g_cost.astype(cost.type.dtype)
# DO NOT enforce g_cost to be 0 if cost is an integer.
# This is to be enforced by the Op.grad method for the
# Op that outputs cost.
if hasattr(g_cost.type, "dtype"):
assert g_cost.type.dtype in pytensor.tensor.type.continuous_dtypes
grad_dict[cost] = g_cost
for var in known_grads:
g_var = known_grads[var]
if not hasattr(g_var, "type"):
raise TypeError(
"output grads must be pytensor variables."
f"Ambiguous whether {type(g_var)} should be made into tensor"
" or sparse pytensor variable"
)
if not isinstance(
g_var.type, (NullType, DisconnectedType)
) and "float" not in str(g_var.type.dtype):
raise TypeError(
"Gradients must always be NullType, "
"DisconnectedType, or continuous, but grad was "
"given a known_grad of type " + str(g_var.type)
)
# DO NOT check that these gradients are equal to 0 if var is int
# The gradient is allowed to be non-zero on var in that case
# Ops outputting var should not backpropagate its gradient further
# but that is enforced elsewhere (grep for only_connected_to_int)
grad_dict[var] = g_var
def handle_disconnected(var):
message = (
"grad method was asked to compute the gradient "
"with respect to a variable that is not part of "
"the computational graph of the cost, or is used "
f"only by a non-differentiable operator: {var}"
)
if disconnected_inputs == "ignore":
pass
elif disconnected_inputs == "warn":
warnings.warn(message, stacklevel=2)
elif disconnected_inputs == "raise":
message = utils.get_variable_trace_string(var)
raise DisconnectedInputError(message)
else:
raise ValueError(
"Invalid value for keyword "
"'disconnected_inputs', valid values are "
"'ignore', 'warn' and 'raise'."
)
# variables that do not influence the cost have zero gradient.
# if wrt is such a variable, populate the grad_dict with this info
# so that wrt not being in var_to_app_to_idx won't cause an error below
# according to the flag, possibly raise an error if wrt is disconnected
for elem in _wrt:
if elem not in var_to_app_to_idx and elem is not cost and elem not in grad_dict:
handle_disconnected(elem)
grad_dict[elem] = disconnected_type()
cost_name = None
if add_names and cost is not None:
cost_name = cost.name
# Make sure we didn't initialize the grad_dict with any ints
# The gradient may NEVER be an int, even if the variable is an int.
# Read the Op contract and talk to Ian Goodfellow before changing this!
for var in grad_dict:
g = grad_dict[var]
if hasattr(g.type, "dtype"):
assert g.type.dtype in pytensor.tensor.type.float_dtypes
_rval: Sequence[Variable] = _populate_grad_dict(
var_to_app_to_idx, grad_dict, _wrt, cost_name
)
rval: MutableSequence[Optional[Variable]] = list(_rval)
for i in range(len(_rval)):
if isinstance(_rval[i].type, NullType):
if null_gradients == "raise":
raise NullTypeGradError(
f"`grad` encountered a NaN. {_rval[i].type.why_null}"
)
else:
assert null_gradients == "return"
if isinstance(_rval[i].type, DisconnectedType):
handle_disconnected(_rval[i])
if return_disconnected == "zero":
rval[i] = _float_zeros_like(_wrt[i])
elif return_disconnected.lower() == "none":
rval[i] = None
else:
assert return_disconnected.lower() == "disconnected"
t1 = time.perf_counter()
global grad_time
grad_time += t1 - t0
if isinstance(wrt, tuple):
return tuple(rval)
elif not isinstance(wrt, list):
return rval[0]
return rval
def subgraph_grad(wrt, end, start=None, cost=None, details=False):
"""
With respect to `wrt`, computes gradients of cost and/or from
existing `start` gradients, up to the `end` variables of a
symbolic digraph. In other words, computes gradients for a
subgraph of the symbolic pytensor function. Ignores all disconnected
inputs.
This can be useful when one needs to perform the gradient descent
iteratively (e.g. one layer at a time in an MLP), or when a
particular operation is not differentiable in pytensor
(e.g. stochastic sampling from a multinomial). In the latter case,
the gradient of the non-differentiable process could be
approximated by user-defined formula, which could be calculated
using the gradients of a cost with respect to samples (0s and
1s). These gradients are obtained by performing a subgraph_grad
from the `cost` or previously known gradients (`start`) up to the
outputs of the stochastic process (`end`). A dictionary mapping
gradients obtained from the user-defined differentiation of the
process, to variables, could then be fed into another
subgraph_grad as `start` with any other `cost` (e.g. weight
decay).
In an MLP, we could use subgraph_grad to iteratively backpropagate:
.. code-block:: python
x, t = pytensor.tensor.fvector('x'), pytensor.tensor.fvector('t')
w1 = pytensor.shared(np.random.standard_normal((3,4)))
w2 = pytensor.shared(np.random.standard_normal((4,2)))
a1 = pytensor.tensor.tanh(pytensor.tensor.dot(x,w1))
a2 = pytensor.tensor.tanh(pytensor.tensor.dot(a1,w2))
cost2 = pytensor.tensor.sqr(a2 - t).sum()
cost2 += pytensor.tensor.sqr(w2.sum())
cost1 = pytensor.tensor.sqr(w1.sum())
params = [[w2],[w1]]
costs = [cost2,cost1]
grad_ends = [[a1], [x]]
next_grad = None
param_grads = []
for i in range(2):
param_grad, next_grad = pytensor.subgraph_grad(
wrt=params[i], end=grad_ends[i],
start=next_grad, cost=costs[i]
)
next_grad = dict(zip(grad_ends[i], next_grad))
param_grads.extend(param_grad)
Parameters
----------
wrt : list of variables
Gradients are computed with respect to `wrt`.
end : list of variables
PyTensor variables at which to end gradient descent (they are
considered constant in pytensor.grad). For convenience, the
gradients with respect to these variables are also returned.
start : dictionary of variables
If not None, a dictionary mapping variables to their
gradients. This is useful when the gradient on some variables
are known. These are used to compute the gradients backwards up
to the variables in `end` (they are used as known_grad in
pytensor.grad).
cost : :class:`~pytensor.graph.basic.Variable` scalar (0-dimensional) variable
Additional costs for which to compute the gradients. For
example, these could be weight decay, an l1 constraint, MSE,
NLL, etc. May optionally be None if start is provided.
.. warning::
If the gradients of `cost` with respect to any of the `start`
variables is already part of the `start` dictionary, then it
may be counted twice with respect to `wrt` and `end`.
details : bool
When True, additionally returns the list of gradients from
`start` and of `cost`, respectively, with respect to `wrt` (not
`end`).
Returns
-------
Tuple of 2 or 4 Lists of Variables
Returns lists of gradients with respect to `wrt` and `end`,
respectively.
.. versionadded:: 0.7
"""
if cost is None and start is None:
raise ValueError("`cost` or `start` must be specified.")
if not isinstance(end, list):
raise TypeError("`end` must be a list.")
if not isinstance(wrt, list):
raise TypeError("`wrt` must be a list.")
if start is not None:
if not isinstance(start, dict):
raise TypeError("`start` must be a dictionary.")
params = list(set(wrt + end))
start_grads = None
cost_grads = None
if start is not None:
start_grads = list(
pytensor.grad(
cost=None,
wrt=params,
known_grads=start,
consider_constant=end,
disconnected_inputs="ignore",
)
)
if cost is not None:
cost_grads = list(
pytensor.grad(
cost=cost,
wrt=params,
consider_constant=end,
disconnected_inputs="ignore",
)
)
grads = None
if start is None:
grads = cost_grads
else:
grads = start_grads
if cost_grads is not None:
for i in range(len(grads)):
grads[i] += cost_grads[i]
pgrads = dict(zip(params, grads))
# separate wrt from end grads:
wrt_grads = [pgrads[k] for k in wrt]
end_grads = [pgrads[k] for k in end]
if details:
return wrt_grads, end_grads, start_grads, cost_grads
return wrt_grads, end_grads
def _node_to_pattern(node):
"""given an apply node, obtain its connection pattern
this is just a wrapper around Op.connection_pattern
that does type checking and supplies the default value
if the method is not implemented
"""
if hasattr(node.op, "connection_pattern"):
connection_pattern = node.op.connection_pattern(node)
if not isinstance(connection_pattern, list):
raise TypeError(
"Op.connection_pattern should return "
+ f"list of list of bool, but for Op={node.op}"
+ f"got {connection_pattern} with type {type(connection_pattern)}."
)
if len(connection_pattern) != len(node.inputs):
raise ValueError(
f"{node.op}.connection_pattern should have {len(node.inputs)}"
+ f" rows but has {len(connection_pattern)}."
)
for ii, output_pattern in enumerate(connection_pattern):
if not isinstance(output_pattern, list):
raise TypeError(
f"{node.op}.connection_pattern should return"
+ f" a list of lists, but element {int(ii)}"
+ f"is {output_pattern} of type {type(output_pattern)}."
)
else:
connection_pattern = [[True for output in node.outputs] for ipt in node.inputs]
assert isinstance(connection_pattern, list)
assert len(connection_pattern) == len(node.inputs)
for ii in range(len(node.inputs)):
assert isinstance(connection_pattern[ii], list)
assert len(connection_pattern[ii]) == len(node.outputs)
return connection_pattern
def _populate_var_to_app_to_idx(outputs, wrt, consider_constant):
"""
Helper function for grad function.
Parameters
----------
outputs
a list of variables we want to take gradients of
wrt
a list of variables we want to take the gradient with
respect to.
consider_constant
a list of variables not to backpropagate through.
Returns
-------
var_to_app_to_idx:
A dictionary mapping a variable to a second dictionary.
The second dictionary maps apply nodes acting on this
variable to the variable's index in the apply node's
input list.
This dictionary will only contain variables that
meet two criteria:
1) The elements of at least one output are a
function of the elements of the variable
2) The elements of the variable are a function of the
elements of at least one member of wrt.
This set is exactly the set of variables that connect
the variables in wrt to the cost being differentiated.
(A variable in consider_constant is not a function of
anything)
"""
# Validate and format consider_constant
if consider_constant is None:
consider_constant = []
else:
# error checking on consider_constant: verify that it is a collection
# of pytensor variables
# this is important, if someone accidentally passes a nested data
# structure with pytensor variables at the leaves, only the root will
# be properly considered constant
try:
iter(consider_constant)
except TypeError:
raise TypeError(
"consider_constant must be an iterable collection,"
" got " + str(type(consider_constant))
)
for elem in consider_constant:
if not isinstance(elem, Variable):
raise TypeError(
"Elements of consider_constant must be "
"variables, but got " + str(type(elem))
)
# var_to_app_to_idx[var][node] = [i,j] means node has
# var as input at positions i and j
var_to_app_to_idx = dict()
# Set of variables that have been added to their true parents
# ('true' here means that the elements of the variable are a function
# of the elements of the parent, according to the op's
# connection_pattern)
# Note: we need to revisit the apply nodes repeatedly, because
# different outputs of the apply node are connected to
# different subsets of the inputs.
accounted_for = set()
def account_for(var):
# Don't visit the same variable twice
if var in accounted_for:
return
accounted_for.add(var)
# Constants are not a function of anything
if var in consider_constant:
return
# Recursively add the variables that this variable is
# a function of.
if var.owner is not None:
app = var.owner
connection_pattern = _node_to_pattern(app)
var_idx = app.outputs.index(var)
for i, ipt in enumerate(app.inputs):
# don't process ipt if it is not a true
# parent of var
if not connection_pattern[i][var_idx]:
continue
if ipt not in var_to_app_to_idx:
# This object here *must* be ordered, because
# we iterate over its keys when adding up the terms of the
# gradient on ipt. If it is a regular dict, the grad method
# will return something that is analytically correct, but
# whose order of doing additions depends on the memory
# location of the apply nodes.
var_to_app_to_idx[ipt] = {}
app_to_idx = var_to_app_to_idx[ipt]
if app not in app_to_idx:
app_to_idx[app] = []
idx = app_to_idx[app]
if i not in idx:
idx.append(i)
account_for(ipt)
# add all variables that are true ancestors of the cost
for output in outputs:
account_for(output)
# determine which variables have elements of wrt as a true
# ancestor. Do this with an upward pass starting from wrt,
# following only true connections
visited = set()
def visit(var):
if var in visited:
return
if var not in var_to_app_to_idx:
return
visited.add(var)
nodes = var_to_app_to_idx[var]
for node in nodes:
connection_pattern = _node_to_pattern(node)
for idx in nodes[node]:
for ii, output in enumerate(node.outputs):
if connection_pattern[idx][ii]:
visit(output)
for elem in wrt:
visit(elem)
# Remove variables that don't have wrt as a true ancestor
orig_vars = list(var_to_app_to_idx.keys())
for var in orig_vars:
if var not in visited:
del var_to_app_to_idx[var]
return var_to_app_to_idx
class NullTypeGradError(TypeError):
"""
Raised when grad encounters a NullType.
"""
class DisconnectedInputError(ValueError):