-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_modeling.py
93 lines (65 loc) · 2.02 KB
/
test_modeling.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
import torch
import torch.nn as nn
from modeling import TiedLinear, TiedEmbedding
def test_TiedLinear_type():
f = nn.Linear(20,10)
g = TiedLinear(f)
assert isinstance(f, nn.Linear)
assert isinstance(g, nn.Linear)
def test_TiedLinear_shapes():
orig = nn.Linear(20,10)
tied = TiedLinear(orig)
x = torch.randn(20)
z = orig(x)
x_rec = tied(z)
x = torch.randn(5, 20)
z = orig(x)
x_rec = tied(z)
def test_TiedLinear_intervention():
orig = nn.Linear(20,10)
tied = TiedLinear(orig)
orig.weight.data[2, 7] = 42.0
assert tied.weight[2, 7] == 42.0
def test_TiedLinear_weight_init():
f = nn.Linear(20,10)
g = TiedLinear(f)
f.reset_parameters()
assert (g.weight.data == f.weight.data).all()
def test_TiedLinear_bias_init():
f = nn.Linear(20,10)
g = TiedLinear(f)
tmp = f.weight.data.clone()
nn.init.ones_(g.bias) # temporarily set to ones
g.reset_parameters() # should reset to all zerosk
assert (g.bias.data == 0.0).all()
# f.weight should be untouched by reset parameters
assert (f.weight.data == tmp).all()
def test_TiedEmbedding_type():
f = nn.Linear(2,3)
g = TiedEmbedding(f)
assert isinstance(f, nn.Linear)
assert isinstance(g, nn.Embedding)
def test_TiedEmbedding_shapes():
f = nn.Linear(20,30)
g = TiedEmbedding(f)
x = torch.randn(20).view(1,-1)
# Test that it doesnt mess with orig Linear
h = f(x)
assert h.size(1) == 30
x = torch.tensor([0,1])
x_emb = g(x)
# assert x_emb.size(0) == 2 # same as input long vals
assert x_emb.size(-1) == 30 # same as linear's output dim
def test_TiedEmbedding_values():
f = nn.Linear(20,30)
g = TiedEmbedding(f)
x = torch.randn(20).view(1,-1)
# Test that it doesnt mess with orig Linear
h = f(x)
assert h.size(1) == 30
x = torch.tensor([0,1,19])
x_emb = g(x)
# assert x_emb.size(0) == 2 # same as input long vals
x_emb[0] = f.weight.T[0]
x_emb[1] = f.weight.T[1]
x_emb[2] = f.weight.T[19]