| 21 | |
| 22 | |
| 23 | class 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: |
no outgoing calls