| 265 | |
| 266 | |
| 267 | class TextEncoderBiGRU(nn.Module): |
| 268 | def __init__(self, word_size, pos_size, hidden_size, device): |
| 269 | super(TextEncoderBiGRU, self).__init__() |
| 270 | self.device = device |
| 271 | |
| 272 | self.pos_emb = nn.Linear(pos_size, word_size) |
| 273 | self.input_emb = nn.Linear(word_size, hidden_size) |
| 274 | self.gru = nn.GRU(hidden_size, hidden_size, batch_first=True, bidirectional=True) |
| 275 | # self.linear2 = nn.Linear(hidden_size, output_size) |
| 276 | |
| 277 | self.input_emb.apply(init_weight) |
| 278 | self.pos_emb.apply(init_weight) |
| 279 | # self.linear2.apply(init_weight) |
| 280 | # self.batch_size = batch_size |
| 281 | self.hidden_size = hidden_size |
| 282 | self.hidden = nn.Parameter(torch.randn((2, 1, self.hidden_size), requires_grad=True)) |
| 283 | |
| 284 | # input(batch_size, seq_len, dim) |
| 285 | def forward(self, word_embs, pos_onehot, cap_lens): |
| 286 | num_samples = word_embs.shape[0] |
| 287 | |
| 288 | pos_embs = self.pos_emb(pos_onehot) |
| 289 | inputs = word_embs + pos_embs |
| 290 | input_embs = self.input_emb(inputs) |
| 291 | hidden = self.hidden.repeat(1, num_samples, 1) |
| 292 | |
| 293 | cap_lens = cap_lens.data.tolist() |
| 294 | emb = pack_padded_sequence(input_embs, cap_lens, batch_first=True) |
| 295 | |
| 296 | gru_seq, gru_last = self.gru(emb, hidden) |
| 297 | |
| 298 | gru_last = torch.cat([gru_last[0], gru_last[1]], dim=-1) |
| 299 | gru_seq = pad_packed_sequence(gru_seq, batch_first=True)[0] |
| 300 | forward_seq = gru_seq[..., :self.hidden_size] |
| 301 | backward_seq = gru_seq[..., self.hidden_size:].clone() |
| 302 | |
| 303 | # Concate the forward and backward word embeddings |
| 304 | for i, length in enumerate(cap_lens): |
| 305 | backward_seq[i:i+1, :length] = torch.flip(backward_seq[i:i+1, :length].clone(), dims=[1]) |
| 306 | gru_seq = torch.cat([forward_seq, backward_seq], dim=-1) |
| 307 | |
| 308 | return gru_seq, gru_last |
| 309 | |
| 310 | |
| 311 | class TextEncoderBiGRUCo(nn.Module): |
nothing calls this directly
no outgoing calls
no test coverage detected