-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrix_initializers.py
More file actions
48 lines (34 loc) · 1.39 KB
/
Copy pathmatrix_initializers.py
File metadata and controls
48 lines (34 loc) · 1.39 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
import torch
class SparseMatrixInitializer:
def __init__(self, device=None):
self.device = device
pass
def __call__(self, *args, **kwds):
pass
class SparseMatrixBySparsityInitializer(SparseMatrixInitializer):
def __init__(self, sparsity, device=None):
"""
:param sparsity: float, sparsity of the matrix. sparsity = 1 means all zeros, sparsity = 0 means no zeros
"""
super().__init__(device=device)
self.sparsity = sparsity
def __call__(self, shape):
mask = (torch.rand(shape, device=self.device) < 1 - self.sparsity).float()
return torch.normal(0, 1, shape, device=self.device) * mask
class SparseMatrixByScalingInitializer(SparseMatrixInitializer):
def __init__(self, scale, mean=0, device=None):
super().__init__(device=device)
self.device = device
self.mean = mean
self.std = scale
def __call__(self, shape):
return torch.normal(self.mean, self.std, shape, device=self.device)
class ConstantInitializer(SparseMatrixInitializer):
def __init__(self, value: torch.Tensor, device=None):
super().__init__(device=device)
self.value = value
def __call__(self, shape):
assert (
shape == self.value.shape
), "Shape mismatch between constant and requested shape"
return self.value.detach().clone().to(self.device)