-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.py
More file actions
72 lines (60 loc) · 1.88 KB
/
models.py
File metadata and controls
72 lines (60 loc) · 1.88 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
import itertools
import jaxtyping as jt
import torch
import torch.nn as nn
class MLP(nn.Module):
def __init__(
self,
d_in: int,
d_out: int,
w: int=64,
h: int=2
) -> None:
super().__init__()
act = nn.SELU() ## will get registered inside nn.Sequential()
linears = (nn.Linear(w, w) for _ in range(h))
self.net = nn.Sequential(
nn.Linear(d_in, w),
act,
*itertools.chain.from_iterable(zip(linears, itertools.repeat(act))),
nn.Linear(w, d_out)
)
def forward(
self,
x: jt.Real[torch.Tensor, '*batch d_in']
) -> jt.Real[torch.Tensor, '*batch d_out']:
return self.net(x)
class FlowScoreMLP(nn.Module):
def __init__(
self,
d_in: int,
d_out: int,
w: int=64,
h: int=2
) -> None:
super().__init__()
act = nn.SELU()
linears = (nn.Linear(w, w) for _ in range(h))
self.trunk = nn.Sequential(
nn.Linear(d_in, w),
act,
*itertools.chain.from_iterable(zip(linears, itertools.repeat(act)))
)
self.flow_head = nn.Linear(w, d_out)
self.score_head = nn.Linear(w, d_out)
def forward(
self,
x: jt.Real[torch.Tensor, '*batch d_in']
) -> tuple[jt.Real[torch.Tensor, '*batch d_out'], jt.Real[torch.Tensor, '*batch d_out']]:
z = self.trunk(x)
return self.flow_head(z), self.score_head(z)
class flowscore_wrapper(nn.Module):
'''Wrapper to convert single-head model to double-head model'''
def __init__(self, model: nn.Module) -> None:
super().__init__()
self.model = model
def forward(
self,
x: jt.Real[torch.Tensor, '*batch d_in']
) -> tuple[jt.Real[torch.Tensor, '*batch d_out'], None]:
return self.model(x), None