-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy path_gramian_computer.py
More file actions
77 lines (59 loc) · 2.47 KB
/
_gramian_computer.py
File metadata and controls
77 lines (59 loc) · 2.47 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
from abc import ABC, abstractmethod
from typing import Optional
from torch import Tensor
from torch.utils._pytree import PyTree
from torchjd._linalg import Matrix, PSDMatrix, compute_gramian, is_matrix
from torchjd.autogram._jacobian_computer import JacobianComputer
class GramianComputer(ABC):
@abstractmethod
def __call__(
self,
rg_outputs: tuple[Tensor, ...],
grad_outputs: tuple[Tensor, ...],
args: tuple[PyTree, ...],
kwargs: dict[str, PyTree],
) -> Optional[PSDMatrix]:
"""Compute what we can for a module and optionally return the gramian if it's ready."""
def track_forward_call(self) -> None:
"""Track that the module's forward was called. Necessary in some implementations."""
def reset(self) -> None:
"""Reset state if any. Necessary in some implementations."""
class JacobianBasedGramianComputer(GramianComputer, ABC):
def __init__(self, jacobian_computer: JacobianComputer):
self.jacobian_computer = jacobian_computer
class JacobianBasedGramianComputerWithCrossTerms(JacobianBasedGramianComputer):
"""
Stateful JacobianBasedGramianComputer that waits for all usages to be counted before returning
the gramian.
"""
def __init__(self, jacobian_computer: JacobianComputer):
super().__init__(jacobian_computer)
self.remaining_counter = 0
self.summed_jacobian: Optional[Matrix] = None
def reset(self) -> None:
self.remaining_counter = 0
self.summed_jacobian = None
def track_forward_call(self) -> None:
self.remaining_counter += 1
def __call__(
self,
rg_outputs: tuple[Tensor, ...],
grad_outputs: tuple[Tensor, ...],
args: tuple[PyTree, ...],
kwargs: dict[str, PyTree],
) -> Optional[PSDMatrix]:
"""Compute what we can for a module and optionally return the gramian if it's ready."""
jacobian_matrix = self.jacobian_computer(rg_outputs, grad_outputs, args, kwargs)
if self.summed_jacobian is None:
self.summed_jacobian = jacobian_matrix
else:
jacobians_sum = self.summed_jacobian + jacobian_matrix
assert is_matrix(jacobians_sum)
self.summed_jacobian = jacobians_sum
self.remaining_counter -= 1
if self.remaining_counter == 0:
gramian = compute_gramian(self.summed_jacobian)
del self.summed_jacobian
return gramian
else:
return None