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

pointer_network.py 13 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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
  1. import torch
  2. import torch.nn as nn
  3. from torch.autograd import Variable
  4. import math
  5. import numpy as np
  6. class Encoder(nn.Module):
  7. """Maps a graph represented as an input sequence
  8. to a hidden vector"""
  9. def __init__(self, input_dim, hidden_dim):
  10. super(Encoder, self).__init__()
  11. self.hidden_dim = hidden_dim
  12. self.lstm = nn.LSTM(input_dim, hidden_dim)
  13. self.init_hx, self.init_cx = self.init_hidden(hidden_dim)
  14. def forward(self, x, hidden):
  15. output, hidden = self.lstm(x, hidden)
  16. return output, hidden
  17. def init_hidden(self, hidden_dim):
  18. """Trainable initial hidden state"""
  19. std = 1. / math.sqrt(hidden_dim)
  20. enc_init_hx = nn.Parameter(torch.FloatTensor(hidden_dim))
  21. enc_init_hx.data.uniform_(-std, std)
  22. enc_init_cx = nn.Parameter(torch.FloatTensor(hidden_dim))
  23. enc_init_cx.data.uniform_(-std, std)
  24. return enc_init_hx, enc_init_cx
  25. class Attention(nn.Module):
  26. """A generic attention module for a decoder in seq2seq"""
  27. def __init__(self, dim, use_tanh=False, C=10):
  28. super(Attention, self).__init__()
  29. self.use_tanh = use_tanh
  30. self.project_query = nn.Linear(dim, dim)
  31. self.project_ref = nn.Conv1d(dim, dim, 1, 1)
  32. self.C = C # tanh exploration
  33. self.tanh = nn.Tanh()
  34. self.v = nn.Parameter(torch.FloatTensor(dim))
  35. self.v.data.uniform_(-(1. / math.sqrt(dim)), 1. / math.sqrt(dim))
  36. def forward(self, query, ref):
  37. """
  38. Args:
  39. query: is the hidden state of the decoder at the current
  40. time step. batch x dim
  41. ref: the set of hidden states from the encoder.
  42. sourceL x batch x hidden_dim
  43. """
  44. # ref is now [batch_size x hidden_dim x sourceL]
  45. ref = ref.permute(1, 2, 0)
  46. q = self.project_query(query).unsqueeze(2) # batch x dim x 1
  47. e = self.project_ref(ref) # batch_size x hidden_dim x sourceL
  48. # expand the query by sourceL
  49. # batch x dim x sourceL
  50. expanded_q = q.repeat(1, 1, e.size(2))
  51. # batch x 1 x hidden_dim
  52. v_view = self.v.unsqueeze(0).expand(
  53. expanded_q.size(0), len(self.v)).unsqueeze(1)
  54. # [batch_size x 1 x hidden_dim] * [batch_size x hidden_dim x sourceL]
  55. u = torch.bmm(v_view, self.tanh(expanded_q + e)).squeeze(1)
  56. if self.use_tanh:
  57. logits = self.C * self.tanh(u)
  58. else:
  59. logits = u
  60. return e, logits
  61. class Decoder(nn.Module):
  62. def __init__(self,
  63. embedding_dim,
  64. hidden_dim,
  65. tanh_exploration,
  66. use_tanh,
  67. n_glimpses=1,
  68. mask_glimpses=True,
  69. mask_logits=True):
  70. super(Decoder, self).__init__()
  71. self.embedding_dim = embedding_dim
  72. self.hidden_dim = hidden_dim
  73. self.n_glimpses = n_glimpses
  74. self.mask_glimpses = mask_glimpses
  75. self.mask_logits = mask_logits
  76. self.use_tanh = use_tanh
  77. self.tanh_exploration = tanh_exploration
  78. self.decode_type = None # Needs to be set explicitly before use
  79. self.lstm = nn.LSTMCell(embedding_dim, hidden_dim)
  80. self.pointer = Attention(hidden_dim, use_tanh=use_tanh, C=tanh_exploration)
  81. self.glimpse = Attention(hidden_dim, use_tanh=False)
  82. self.sm = nn.Softmax(dim=1)
  83. def update_mask(self, mask, selected):
  84. return mask.clone().scatter_(1, selected.unsqueeze(-1), True)
  85. def recurrence(self, x, h_in, prev_mask, prev_idxs, step, context):
  86. logit_mask = self.update_mask(prev_mask, prev_idxs) if prev_idxs is not None else prev_mask
  87. logits, h_out = self.calc_logits(x, h_in, logit_mask, context, self.mask_glimpses, self.mask_logits)
  88. # Calculate log_softmax for better numerical stability
  89. log_p = torch.log_softmax(logits, dim=1)
  90. probs = log_p.exp()
  91. if not self.mask_logits:
  92. # If self.mask_logits, this would be redundant, otherwise we must mask to make sure we don't resample
  93. # Note that as a result the vector of probs may not sum to one (this is OK for .multinomial sampling)
  94. # But practically by not masking the logits, a model is learned over all sequences (also infeasible)
  95. # while only during sampling feasibility is enforced (a.k.a. by setting to 0. here)
  96. probs[logit_mask] = 0.
  97. # For consistency we should also mask out in log_p, but the values set to 0 will not be sampled and
  98. # Therefore not be used by the reinforce estimator
  99. return h_out, log_p, probs, logit_mask
  100. def calc_logits(self, x, h_in, logit_mask, context, mask_glimpses=None, mask_logits=None):
  101. if mask_glimpses is None:
  102. mask_glimpses = self.mask_glimpses
  103. if mask_logits is None:
  104. mask_logits = self.mask_logits
  105. hy, cy = self.lstm(x, h_in)
  106. g_l, h_out = hy, (hy, cy)
  107. for i in range(self.n_glimpses):
  108. ref, logits = self.glimpse(g_l, context)
  109. # For the glimpses, only mask before softmax so we have always an L1 norm 1 readout vector
  110. if mask_glimpses:
  111. logits[logit_mask] = -np.inf
  112. # [batch_size x h_dim x sourceL] * [batch_size x sourceL x 1] =
  113. # [batch_size x h_dim x 1]
  114. g_l = torch.bmm(ref, self.sm(logits).unsqueeze(2)).squeeze(2)
  115. _, logits = self.pointer(g_l, context)
  116. # Masking before softmax makes probs sum to one
  117. if mask_logits:
  118. logits[logit_mask] = -np.inf
  119. return logits, h_out
  120. def forward(self, decoder_input, embedded_inputs, hidden, context, eval_tours=None):
  121. """
  122. Args:
  123. decoder_input: The initial input to the decoder
  124. size is [batch_size x embedding_dim]. Trainable parameter.
  125. embedded_inputs: [sourceL x batch_size x embedding_dim]
  126. hidden: the prev hidden state, size is [batch_size x hidden_dim].
  127. Initially this is set to (enc_h[-1], enc_c[-1])
  128. context: encoder outputs, [sourceL x batch_size x hidden_dim]
  129. """
  130. batch_size = context.size(1)
  131. outputs = []
  132. selections = []
  133. steps = range(embedded_inputs.size(0))
  134. idxs = None
  135. mask = Variable(
  136. embedded_inputs.data.new().byte().new(embedded_inputs.size(1), embedded_inputs.size(0)).zero_(),
  137. requires_grad=False
  138. )
  139. for i in steps:
  140. hidden, log_p, probs, mask = self.recurrence(decoder_input, hidden, mask, idxs, i, context)
  141. # select the next inputs for the decoder [batch_size x hidden_dim]
  142. idxs = self.decode(
  143. probs,
  144. mask
  145. ) if eval_tours is None else eval_tours[:, i]
  146. idxs = idxs.detach() # Otherwise pytorch complains it want's a reward, todo implement this more properly?
  147. # Gather input embedding of selected
  148. decoder_input = torch.gather(
  149. embedded_inputs,
  150. 0,
  151. idxs.contiguous().view(1, batch_size, 1).expand(1, batch_size, *embedded_inputs.size()[2:])
  152. ).squeeze(0)
  153. # use outs to point to next object
  154. outputs.append(log_p)
  155. selections.append(idxs)
  156. return (torch.stack(outputs, 1), torch.stack(selections, 1)), hidden
  157. def decode(self, probs, mask):
  158. if self.decode_type == "greedy":
  159. _, idxs = probs.max(1)
  160. assert not mask.gather(1, idxs.unsqueeze(-1)).data.any(), \
  161. "Decode greedy: infeasible action has maximum probability"
  162. elif self.decode_type == "sampling":
  163. idxs = probs.multinomial(1).squeeze(1)
  164. # Check if sampling went OK, can go wrong due to bug on GPU
  165. while mask.gather(1, idxs.unsqueeze(-1)).data.any():
  166. print(' [!] resampling due to race condition')
  167. idxs = probs.multinomial().squeeze(1)
  168. else:
  169. assert False, "Unknown decode type"
  170. return idxs
  171. class CriticNetworkLSTM(nn.Module):
  172. """Useful as a baseline in REINFORCE updates"""
  173. def __init__(self,
  174. embedding_dim,
  175. hidden_dim,
  176. n_process_block_iters,
  177. tanh_exploration,
  178. use_tanh):
  179. super(CriticNetworkLSTM, self).__init__()
  180. self.hidden_dim = hidden_dim
  181. self.n_process_block_iters = n_process_block_iters
  182. self.encoder = Encoder(embedding_dim, hidden_dim)
  183. self.process_block = Attention(hidden_dim, use_tanh=use_tanh, C=tanh_exploration)
  184. self.sm = nn.Softmax(dim=1)
  185. self.decoder = nn.Sequential(
  186. nn.Linear(hidden_dim, hidden_dim),
  187. nn.ReLU(),
  188. nn.Linear(hidden_dim, 1)
  189. )
  190. def forward(self, inputs):
  191. """
  192. Args:
  193. inputs: [embedding_dim x batch_size x sourceL] of embedded inputs
  194. """
  195. inputs = inputs.transpose(0, 1).contiguous()
  196. encoder_hx = self.encoder.init_hx.unsqueeze(0).repeat(inputs.size(1), 1).unsqueeze(0)
  197. encoder_cx = self.encoder.init_cx.unsqueeze(0).repeat(inputs.size(1), 1).unsqueeze(0)
  198. # encoder forward pass
  199. enc_outputs, (enc_h_t, enc_c_t) = self.encoder(inputs, (encoder_hx, encoder_cx))
  200. # grab the hidden state and process it via the process block
  201. process_block_state = enc_h_t[-1]
  202. for i in range(self.n_process_block_iters):
  203. ref, logits = self.process_block(process_block_state, enc_outputs)
  204. process_block_state = torch.bmm(ref, self.sm(logits).unsqueeze(2)).squeeze(2)
  205. # produce the final scalar output
  206. out = self.decoder(process_block_state)
  207. return out
  208. class PointerNetwork(nn.Module):
  209. def __init__(self,
  210. embedding_dim,
  211. hidden_dim,
  212. problem,
  213. n_encode_layers=None,
  214. tanh_clipping=10.,
  215. mask_inner=True,
  216. mask_logits=True,
  217. normalization=None,
  218. **kwargs):
  219. super(PointerNetwork, self).__init__()
  220. self.problem = problem
  221. assert problem.NAME == "tsp", "Pointer Network only supported for TSP"
  222. self.input_dim = 2
  223. self.encoder = Encoder(
  224. embedding_dim,
  225. hidden_dim)
  226. self.decoder = Decoder(
  227. embedding_dim,
  228. hidden_dim,
  229. tanh_exploration=tanh_clipping,
  230. use_tanh=tanh_clipping > 0,
  231. n_glimpses=1,
  232. mask_glimpses=mask_inner,
  233. mask_logits=mask_logits
  234. )
  235. # Trainable initial hidden states
  236. std = 1. / math.sqrt(embedding_dim)
  237. self.decoder_in_0 = nn.Parameter(torch.FloatTensor(embedding_dim))
  238. self.decoder_in_0.data.uniform_(-std, std)
  239. self.embedding = nn.Parameter(torch.FloatTensor(self.input_dim, embedding_dim))
  240. self.embedding.data.uniform_(-std, std)
  241. def set_decode_type(self, decode_type):
  242. self.decoder.decode_type = decode_type
  243. def forward(self, inputs, eval_tours=None, return_pi=False):
  244. batch_size, graph_size, input_dim = inputs.size()
  245. embedded_inputs = torch.mm(
  246. inputs.transpose(0, 1).contiguous().view(-1, input_dim),
  247. self.embedding
  248. ).view(graph_size, batch_size, -1)
  249. # query the actor net for the input indices
  250. # making up the output, and the pointer attn
  251. _log_p, pi = self._inner(embedded_inputs, eval_tours)
  252. cost, mask = self.problem.get_costs(inputs, pi)
  253. # Log likelyhood is calculated within the model since returning it per action does not work well with
  254. # DataParallel since sequences can be of different lengths
  255. ll = self._calc_log_likelihood(_log_p, pi, mask)
  256. if return_pi:
  257. return cost, ll, pi
  258. return cost, ll
  259. def _calc_log_likelihood(self, _log_p, a, mask):
  260. # Get log_p corresponding to selected actions
  261. log_p = _log_p.gather(2, a.unsqueeze(-1)).squeeze(-1)
  262. # Optional: mask out actions irrelevant to objective so they do not get reinforced
  263. if mask is not None:
  264. log_p[mask] = 0
  265. assert (log_p > -1000).data.all(), "Logprobs should not be -inf, check sampling procedure!"
  266. # Calculate log_likelihood
  267. return log_p.sum(1)
  268. def _inner(self, inputs, eval_tours=None):
  269. encoder_hx = encoder_cx = Variable(
  270. torch.zeros(1, inputs.size(1), self.encoder.hidden_dim, out=inputs.data.new()),
  271. requires_grad=False
  272. )
  273. # encoder forward pass
  274. enc_h, (enc_h_t, enc_c_t) = self.encoder(inputs, (encoder_hx, encoder_cx))
  275. dec_init_state = (enc_h_t[-1], enc_c_t[-1])
  276. # repeat decoder_in_0 across batch
  277. decoder_input = self.decoder_in_0.unsqueeze(0).repeat(inputs.size(1), 1)
  278. (pointer_probs, input_idxs), dec_hidden_t = self.decoder(decoder_input,
  279. inputs,
  280. dec_init_state,
  281. enc_h,
  282. eval_tours)
  283. return pointer_probs, input_idxs
Tip!

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

Comments

Loading...