Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

model.py 6.2 KB

You have to be logged in to leave a comment. Sign In
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. import numpy as np
  5. from typing import List
  6. from src.model.cnn import ConvNet
  7. class CharEncoder(nn.Module):
  8. """
  9. char encoder takes in list of list of word represented by array of char idx
  10. and outputs word embedding
  11. """
  12. def __init__(
  13. self,
  14. num_chars: int,
  15. embedding_size: int,
  16. padding_idx: int,
  17. embedding_dropout: float,
  18. channels: List[int],
  19. kernel_size: int,
  20. cnn_dropout: float):
  21. super().__init__()
  22. self.embedding = nn.Embedding(
  23. num_chars, embedding_size, padding_idx=padding_idx)
  24. self.emb_dropout = nn.Dropout(embedding_dropout)
  25. # TODO other parameters
  26. self.conv_net = ConvNet(channels, kernel_size, dropout=cnn_dropout)
  27. self.init_weights()
  28. def forward(self, inputs):
  29. # inputs is (batch_size, seq_len)
  30. seq_len = inputs.size(1)
  31. # (batch_size, seq_len, embedding)
  32. embedded_chars = self.embedding_dropout(self.embedding(inputs))
  33. # (batch_size, embedding, seq_len)
  34. # we want convolution over the sequence, hence the transpose
  35. embedded_chars = embedded_chars.transpose(1, 2).contiguous()
  36. # (batch_size, conv_size, seq_len)
  37. output = self.conv_net(embedded_chars)
  38. # maxpool over entire sequence
  39. # (batch_size, embedding, 1)
  40. output = F.max_pool1d(output, seq_len)
  41. # (batch_size, embedding)
  42. return output.squeeze()
  43. def init_weights(self):
  44. nn.init.kaiming_uniform_(
  45. self.embedding.weight.data, mode="fan_in", nonlinearity='relu')
  46. class WordEncoder(nn.Module):
  47. def __init__(
  48. self,
  49. initial_embedding_weights: torch.Tensor,
  50. emb_dropout: float,
  51. channels: List[int],
  52. kernel_size: int,
  53. cnn_dropout: float):
  54. # used for word2vec
  55. super().__init__()
  56. self.embedding = nn.Embedding.from_pretrained(
  57. initial_embedding_weights, freeze=False)
  58. self.dropout = nn.Dropout(emb_dropout)
  59. # TODO, why dilated and not residual
  60. self.conv_net = ConvNet(channels, kernel_size, dropout=cnn_dropout,
  61. add_residual=False)
  62. def forward(self, word_inputs, char_embedding_inputs):
  63. # word_inputs (batch_size, seq_len)
  64. # char_embedding_inputs (batch_size, seq_len, char_embed)
  65. # (batch_size, sequence_len, seq_len)
  66. word_embedding = self.embedding(word_inputs)
  67. # (batch_size, seq_len, word_embed + char_embed)
  68. embedded = torch.cat((word_embedding, char_embedding_inputs), 2)
  69. # (batch_size, word_embed + char_embed, seq_len)
  70. embedded = embedded.transpose(1, 2).contiguous()
  71. # (batch_size, conv_size, seq_len)
  72. conv_out = self.conv_net(self.dropout(embedded))
  73. # (batch_size, conv_size + word_embed + char_embed, seq_len)
  74. output = torch.cat((conv_out, embedded), 1)
  75. # (batch_size, seq_len, conv_size + word_embed + char_embed)
  76. return output.transpose(1, 2).contiguous()
  77. class Decoder(nn.Module):
  78. """
  79. LSTM tag decoder
  80. """
  81. def __init__(
  82. self,
  83. input_dim: int,
  84. hidden_dim: int,
  85. output_dim: int,
  86. num_layers: int):
  87. super().__init__()
  88. self.input_dim = input_dim
  89. self.hidden_dim = hidden_dim
  90. self.output_dim = output_dim
  91. # TODO batchfirst, dropout?
  92. self.lstm = nn.LSTM(
  93. input_dim, hidden_dim, num_layers=num_layers, batch_first=True)
  94. self.hidden2label = nn.Linear(hidden_dim, output_dim)
  95. self.init_weight()
  96. def forward(self, inputs):
  97. # input (batch_size, seq_len, input_dim)
  98. # TODO need to initialize initial states?
  99. # (batch_size, seq_len, hidden_dim)
  100. lstm_out, self.hidden = self.lstm(inputs, None)
  101. # batch_size, seq_len, output_dim
  102. y = self.hidden2label(lstm_out)
  103. return y
  104. def init_weight(self):
  105. nn.init.kaiming_uniform_(
  106. self.hidden2label.weight.data,
  107. mode='fan_in',
  108. nonlinearity='relu')
  109. class Model(nn.Module):
  110. def __init__(self, charset_size, char_embedding_size, char_channels,
  111. char_padding_idx, char_kernel_size,
  112. word_embedding, word_embedding_size, word_channels,
  113. word_kernel_size, num_tag, dropout, emb_dropout):
  114. super().__init__()
  115. self.char_encoder = CharEncoder(
  116. charset_size, char_embedding_size, char_channels,
  117. char_kernel_size, char_padding_idx,
  118. dropout=dropout, emb_dropout=emb_dropout)
  119. self.word_encoder = WordEncoder(
  120. word_embedding, word_channels, word_kernel_size,
  121. dropout=dropout, emb_dropout=emb_dropout)
  122. self.drop = nn.Dropout(dropout)
  123. # used to figure out the encoded size
  124. self.char_conv_size = char_channels[-1]
  125. self.word_conv_size = word_channels[-1]
  126. self.word_embedding_size = word_embedding_size
  127. # TODO hidden size(?)
  128. self.decoder = Decoder(self.char_conv_size+self.word_embedding_size+self.word_conv_size,
  129. self.char_conv_size + self.word_embedding_size + self.word_conv_size,
  130. num_tag, num_layers=1)
  131. self.init_weights()
  132. def forward(self, word_input, char_input):
  133. # word input: (batch size, seq_len)
  134. # char input: (batch_size, seq len, word len)
  135. batch_size = word_input.size(0)
  136. seq_len = word_input.size(1)
  137. # (batch_size * seq_len, word_len)
  138. char_input_flattened = char_input.view(-1, char_input.size(2))
  139. # (batch_size * seq_len, char_conv_size)
  140. char_encoding = self.char_encoder(char_input_flattened)
  141. # (batch_size, seq_len, char_conv_size)
  142. char_encoding = char_encoding.view(batch_size, seq_len, -1)
  143. #(batch_size, seq_len, char_encode+word_embed+word_conv)
  144. word_output = self.word_encoder(word_input, char_encoding)
  145. # (batch_size, seq_len, n_tags)
  146. y = self.decoder(word_output)
  147. # TODO do we need this
  148. return F.log_softmax(y, dim=2)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...