MCPcopy Create free account
hub / github.com/MegEngine/MegEngine / Grad

Class Grad

imperative/python/megengine/core/autodiff/grad.py:23–115  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

21
22
23class Grad:
24 stack = []
25 grouping = False
26 key2grad = weakref.WeakValueDictionary()
27
28 def __init__(self, name=None):
29 global _grad_count
30 if name is None:
31 name = "grad_%d" % _grad_count
32 _grad_count += 1
33 self._refkeeper = []
34 self._impl = GradKey(name)
35 Grad.key2grad[self._impl] = self
36 _grad_manager_dict[self._name] = self
37 self._group = [weakref.ref(self)]
38
39 @property
40 def _name(self):
41 return self._impl.name
42
43 def _is_attached_to(self, tensor):
44 return self._impl.is_attached_to(tensor)
45
46 def wrt(self, *tensors, callback=None):
47 for x in tensors:
48 self._impl.attach(x, callback)
49 return self
50
51 def __call__(self, ys, dys):
52 from collections.abc import Sequence
53
54 if not isinstance(ys, Sequence):
55 ys = [ys]
56
57 if not isinstance(dys, Sequence):
58 dys = [dys]
59
60 group = [ref() for ref in self._group]
61
62 for grad in group:
63 if grad is self:
64 continue
65 grad.suppress()
66
67 self._impl.backward(ys, dys)
68
69 for grad in group:
70 if grad is self:
71 continue
72 grad.resume()
73
74 self._refkeeper = None
75 return None
76
77 def __enter__(self):
78 ref = weakref.ref(self)
79 self._impl.enter()
80 if Grad.grouping:

Callers 15

test_ShuffleRNGFunction · 0.90
test_tqtFunction · 0.90
runFunction · 0.90
test_lsqFunction · 0.90
workerFunction · 0.90
test_gradFunction · 0.90
test_grad_2Function · 0.90
test_2nd_gradFunction · 0.90
test_wrt_visibilityFunction · 0.90
_Function · 0.90

Calls

no outgoing calls

Tested by 15

test_ShuffleRNGFunction · 0.72
test_tqtFunction · 0.72
runFunction · 0.72
test_lsqFunction · 0.72
workerFunction · 0.72
test_gradFunction · 0.72
test_grad_2Function · 0.72
test_2nd_gradFunction · 0.72
test_wrt_visibilityFunction · 0.72
_Function · 0.72