-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodules.py
38 lines (32 loc) · 1.29 KB
/
modules.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
import torch
import torch.nn as nn
import torch.nn.functional as F
class embedding(nn.Module):
def __init__(self, vocab_size, num_units, zeros_pad=True, scale=True):
'''Embeds a given Variable.
Args:
vocab_size: An int. Vocabulary size.
num_units: An int. Number of embedding hidden units.
zero_pad: A boolean. If True, all the values of the fist row (id 0)
should be constant zeros.
scale: A boolean. If True. the outputs is multiplied by sqrt num_units.
'''
super(embedding, self).__init__()
self.vocab_size = vocab_size
self.num_units = num_units
self.zeros_pad = zeros_pad
self.scale = scale
self.lookup_table = nn.Parameter(torch.Tensor(vocab_size, num_units))
nn.init.xavier_normal_(self.lookup_table.data)
if self.zeros_pad:
self.lookup_table.data[0, :].fill_(0)
def forward(self, inputs):
if self.zeros_pad:
self.padding_idx = 0
else:
self.padding_idx = -1
outputs = F.embedding(
inputs, self.lookup_table, self.padding_idx, None, 2, False, False) # copied from torch.nn.modules.sparse.py
if self.scale:
outputs = outputs * (self.num_units ** 0.5)
return outputs