-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
97 lines (84 loc) · 2.55 KB
/
utils.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
#*
# @file Different utility functions
# Copyright (c) Zhewei Yao, Amir Gholami
# All rights reserved.
# This file is part of PyHessian library.
#
# PyHessian is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyHessian is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyHessian. If not, see <http://www.gnu.org/licenses/>.
#*
import torch
import math
from torch.autograd import Variable
import numpy as np
def group_product(xs, ys):
"""
the inner product of two lists of variables xs,ys
:param xs:
:param ys:
:return:
"""
return sum([torch.sum(x * y) for (x, y) in zip(xs, ys)])
def group_add(params, update, alpha=1):
"""
params = params + update*alpha
:param params: list of variable
:param update: list of data
:return:
"""
for i, p in enumerate(params):
params[i].data.add_(update[i] * alpha)
return params
def normalization(v):
"""
normalization of a list of vectors
return: normalized vectors v
"""
s = group_product(v, v)
s = s**0.5
s = s.cpu().item()
v = [vi / (s + 1e-6) for vi in v]
return v
def get_params_grad(model):
"""
get model parameters and corresponding gradients
"""
params = []
grads = []
for param in model.parameters():
if not param.requires_grad:
continue
params.append(param)
grads.append(0. if param.grad is None else param.grad + 0.)
return params, grads
def hessian_vector_product(gradsH, params, v):
"""
compute the hessian vector product of Hv, where
gradsH is the gradient at the current point,
params is the corresponding variables,
v is the vector.
"""
hv = torch.autograd.grad(gradsH,
params,
grad_outputs=v,
only_inputs=True,
retain_graph=True)
return hv
def orthnormal(w, v_list):
"""
make vector w orthogonal to each vector in v_list.
afterwards, normalize the output w
"""
for v in v_list:
w = group_add(w, v, alpha=-group_product(w, v))
return normalization(w)