Skip to content

Commit 5e38478

Browse files
(#3) Separate model/train/data (wip).
1 parent 441e1b0 commit 5e38478

11 files changed

+701
-1121
lines changed

cscg.ipynb

-1,120
This file was deleted.

src/cscg.py

+247
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,247 @@
1+
import torch as T
2+
import torch.nn as nn
3+
from bagoftools.namespace import Namespace
4+
5+
6+
def get_embeddings(config: Namespace) -> nn.Embedding:
7+
emb = nn.Embedding(len(config.lang), config.emb_size,
8+
padding_idx=config.lang.pad_idx)
9+
10+
if config.load_pretrained_emb:
11+
assert config.lang.emb_matrix is not None
12+
emb.weight = nn.Parameter(
13+
T.tensor(config.lang.emb_matrix, dtype=T.float32))
14+
emb.weight.requires_grad = False
15+
16+
return emb
17+
18+
19+
class Model(nn.Module):
20+
def __init__(self, config: Namespace, model_type):
21+
"""
22+
:param model_type: cs / cg
23+
cs: code -> anno
24+
cg: anno -> code
25+
"""
26+
super(Model, self).__init__()
27+
28+
assert model_type in ['cs', 'cg']
29+
self.model_type = model_type
30+
31+
src_cfg = config.anno if model_type == 'cg' else config.code
32+
tgt_cfg = config.code if model_type == 'cg' else config.anno
33+
34+
# 1. ENCODER
35+
self.src_embedding = get_embeddings(src_cfg)
36+
self.encoder = nn.LSTM(input_size=src_cfg.emb_size,
37+
hidden_size=src_cfg.lstm_hidden_size,
38+
dropout=src_cfg.lstm_dropout_p,
39+
bidirectional=True,
40+
batch_first=True)
41+
42+
self.decoder_cell_init_linear = nn.Linear(in_features=2*src_cfg.lstm_hidden_size,
43+
out_features=tgt_cfg.lstm_hidden_size)
44+
45+
# 2. ATTENTION
46+
# project source encoding to decoder rnn's h space (W from Luong score general)
47+
self.att_src_W = nn.Linear(in_features=2*src_cfg.lstm_hidden_size,
48+
out_features=tgt_cfg.lstm_hidden_size,
49+
bias=False)
50+
51+
# transformation of decoder hidden states and context vectors before reading out target words
52+
# this produces the attentional vector in (W from Luong eq. 5)
53+
self.att_vec_W = nn.Linear(in_features=2*src_cfg.lstm_hidden_size + tgt_cfg.lstm_hidden_size,
54+
out_features=tgt_cfg.lstm_hidden_size,
55+
bias=False)
56+
57+
# 3. DECODER
58+
self.tgt_embedding = get_embeddings(tgt_cfg)
59+
self.decoder = nn.LSTMCell(input_size=tgt_cfg.emb_size + tgt_cfg.lstm_hidden_size,
60+
hidden_size=tgt_cfg.lstm_hidden_size)
61+
62+
# prob layer over target language
63+
self.readout = nn.Linear(in_features=tgt_cfg.lstm_hidden_size,
64+
out_features=len(tgt_cfg.lang),
65+
bias=False)
66+
67+
self.dropout = nn.Dropout(tgt_cfg.att_dropout_p)
68+
69+
# 4. COPY MECHANISM
70+
self.copy_gate = ... # TODO
71+
72+
# save configs
73+
self.src_cfg = src_cfg
74+
self.tgt_cfg = tgt_cfg
75+
76+
def forward(self, src, tgt):
77+
"""
78+
src: bs, max_src_len
79+
tgt: bs, max_tgt_len
80+
"""
81+
enc_out, (h0_dec, c0_dec) = self.encode(src)
82+
scores, att_mats = self.decode(enc_out, h0_dec, c0_dec, tgt)
83+
84+
return scores, att_mats
85+
86+
def encode(self, src):
87+
"""
88+
src : bs x max_src_len (emb look-up indices)
89+
out : bs x max_src_len x 2*hid_size
90+
h/c0: bs x tgt_hid_size
91+
"""
92+
emb = self.src_embedding(src)
93+
out, (hn, cn) = self.encoder(emb) # hidden is zero by default
94+
95+
# construct initial state for the decoder
96+
c0_dec = self.decoder_cell_init_linear(T.cat([cn[0], cn[1]], dim=1))
97+
h0_dec = c0_dec.tanh()
98+
99+
return out, (h0_dec, c0_dec)
100+
101+
def decode(self, src_enc, h0_dec, c0_dec, tgt):
102+
"""
103+
src_enc: bs, max_src_len, 2*hid_size (== encoder output)
104+
h/c0 : bs, tgt_hid_size
105+
tgt : bs, max_tgt_len (emb look-up indices)
106+
"""
107+
batch_size, tgt_len = tgt.shape
108+
scores, att_mats = [], []
109+
110+
hidden = (h0_dec, c0_dec)
111+
112+
emb = self.tgt_embedding(tgt) # bs, max_tgt_len, tgt_emb_size
113+
114+
att_vec = T.zeros(
115+
batch_size, self.tgt_cfg.lstm_hidden_size, requires_grad=False)
116+
if CFG.cuda:
117+
att_vec = att_vec.cuda()
118+
119+
# Luong W*hs: same for each timestep of the decoder
120+
src_enc_att = self.att_src_W(src_enc) # bs, max_src_len, tgt_hid_size
121+
122+
for t in range(tgt_len):
123+
emb_t = emb[:, t, :]
124+
x = T.cat([emb_t, att_vec], dim=-1)
125+
h_t, c_t = self.decoder(x, hidden)
126+
127+
ctx_t, att_mat = self.luong_attention(h_t, src_enc, src_enc_att)
128+
129+
# Luong eq. (5)
130+
att_t = self.att_vec_W(T.cat([h_t, ctx_t], dim=1))
131+
att_t = att_t.tanh()
132+
att_t = self.dropout(att_t)
133+
134+
# Luong eq. (6)
135+
score_t = self.readout(att_t)
136+
score_t = F.softmax(score_t, dim=-1)
137+
138+
scores += [score_t]
139+
att_mats += [att_mat]
140+
141+
# for next state t+1
142+
att_vec = att_t
143+
hidden = (h_t, c_t)
144+
145+
# bs, max_tgt_len, tgt_vocab_size
146+
scores = T.stack(scores).permute((1, 0, 2))
147+
148+
# each element: bs, max_src_len, max_tgt_len
149+
att_mats = T.cat(att_mats, dim=1)
150+
151+
return scores, att_mats
152+
153+
def luong_attention(self, h_t, src_enc, src_enc_att, mask=None):
154+
"""
155+
h_t : bs, hid_size
156+
src_enc (hs) : bs, max_src_len, 2*src_hid_size
157+
src_enc_att (W*hs): bs, max_src_len, tgt_hid_size
158+
mask : bs, max_src_len
159+
160+
ctx_vec : bs, 2*src_hid_size
161+
att_weight : bs, max_src_len
162+
att_mat : bs, 1, max_src_len
163+
"""
164+
165+
# bs x src_max_len
166+
score = T.bmm(src_enc_att, h_t.unsqueeze(2)).squeeze(2)
167+
168+
if mask:
169+
score.data.masked_fill_(mask, -np.inf)
170+
171+
att_mat = score.unsqueeze(1)
172+
att_weights = F.softmax(score, dim=-1)
173+
174+
# sum per timestep
175+
ctx_vec = T.sum(att_weights.unsqueeze(2) * src_enc, dim=1)
176+
177+
return ctx_vec, att_mat
178+
179+
def beam_search(self, src, width=3):
180+
"""
181+
Choose most probable sequence, considering top `width` candidates.
182+
"""
183+
184+
hyp = []
185+
186+
batch_size, src_len = src.shape
187+
enc_out, (h0_dec, c0_dec) = self.encode(src)
188+
189+
scores, att_mats = [], []
190+
191+
hidden = (h0_dec, c0_dec)
192+
193+
att_vec = T.zeros(
194+
batch_size, self.tgt_cfg.lstm_hidden_size, requires_grad=False).cuda()
195+
196+
# Luong W*hs: same for each timestep of the decoder
197+
src_enc_att = self.att_src_W(src_enc) # bs, max_src_len, tgt_hid_size
198+
199+
for t in range(tgt_len):
200+
emb_t = self.tgt_embedding(hyp[-1])
201+
x = T.cat([emb_t, att_vec], dim=-1)
202+
h_t, c_t = self.decoder(x, hidden)
203+
204+
ctx_t, att_mat = self.luong_attention(h_t, src_enc, src_enc_att)
205+
206+
att_t = F.tanh(self.att_vec_W(T.cat([h_t, ctx_t], dim=1)))
207+
# att_t = self.dropout(att_t)
208+
209+
score_t = F.softmax(self.readout(att_t), dim=-1)
210+
211+
scores += [score_t]
212+
att_mats += [att_mat]
213+
214+
# for next state t+1
215+
att_vec = att_t
216+
hidden = (h_t, c_t)
217+
218+
# bs, max_tgt_len, tgt_vocab_size
219+
scores = T.stack(scores).permute((1, 0, 2))
220+
221+
# each element: bs, max_src_len, max_tgt_len
222+
att_mats = T.cat(att_mats, dim=1)
223+
224+
return hyp
225+
226+
227+
def JSD(a, b, mask=None):
228+
eps = 1e-8
229+
230+
assert a.shape == b.shape
231+
_, n, _ = a.shape
232+
233+
xa = F.softmax(a, dim=2) + eps
234+
xb = F.softmax(b, dim=2) + eps
235+
236+
# common, averaged dist
237+
avg = 0.5 * (xa + xb)
238+
239+
# kl
240+
xa = T.sum(xa * T.log(xa / avg), dim=2)
241+
xb = T.sum(xb * T.log(xb / avg), dim=2)
242+
243+
# js
244+
xa = T.sum(xa, dim=1) / n
245+
xb = T.sum(xb, dim=1) / n
246+
247+
return 0.5 * (xa + xb)

dataset.py src/dataset.py

File renamed without changes.

0 commit comments

Comments
 (0)