-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathpcgrad.py
More file actions
75 lines (56 loc) · 2.43 KB
/
pcgrad.py
File metadata and controls
75 lines (56 loc) · 2.43 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
import torch
from torch import Tensor
from .bases import _WeightedAggregator, _Weighting
class PCGrad(_WeightedAggregator):
"""
:class:`~torchjd.aggregation.bases.Aggregator` as defined in algorithm 1 of
`Gradient Surgery for Multi-Task Learning <https://arxiv.org/pdf/2001.06782.pdf>`_.
.. admonition::
Example
Use PCGrad to aggregate a matrix.
>>> from torch import tensor
>>> from torchjd.aggregation import PCGrad
>>>
>>> A = PCGrad()
>>> J = tensor([[-4., 1., 1.], [6., 1., 1.]])
>>>
>>> A(J)
tensor([0.5848, 3.8012, 3.8012])
"""
def __init__(self):
super().__init__(weighting=_PCGradWeighting())
class _PCGradWeighting(_Weighting):
"""
:class:`~torchjd.aggregation.bases._Weighting` that extracts weights using the PCGrad
algorithm, as defined in algorithm 1 of `Gradient Surgery for Multi-Task Learning
<https://arxiv.org/pdf/2001.06782.pdf>`_.
.. note::
This implementation corresponds to the paper's algorithm, which differs from the `official
implementation <https://github.com/tianheyu927/PCGrad>`_ in the way randomness is handled.
"""
def forward(self, matrix: Tensor) -> Tensor:
# Pre-compute the inner products
gramian = matrix @ matrix.T
return self._compute_from_gramian(gramian)
@staticmethod
def _compute_from_gramian(inner_products: Tensor) -> Tensor:
# Move all computations on cpu to avoid moving memory between cpu and gpu at each iteration
device = inner_products.device
dtype = inner_products.dtype
cpu = torch.device("cpu")
inner_products = inner_products.to(device=cpu)
dimension = inner_products.shape[0]
weights = torch.zeros(dimension, device=cpu, dtype=dtype)
for i in range(dimension):
permutation = torch.randperm(dimension)
current_weights = torch.zeros(dimension, device=cpu, dtype=dtype)
current_weights[i] = 1.0
for j in permutation:
if j == i:
continue
# Compute the inner product between g_i^{PC} and g_j
inner_product = inner_products[j] @ current_weights
if inner_product < 0.0:
current_weights[j] -= inner_product / (inner_products[j, j])
weights = weights + current_weights
return weights.to(device)