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

tensorflow_model.py 29 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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
  1. import tensorflow as tf
  2. import numpy as np
  3. import time
  4. from typing import Dict, Optional, List, Iterable
  5. from collections import Counter
  6. from functools import partial
  7. from path_context_reader import PathContextReader, ModelInputTensorsFormer, ReaderInputTensors, EstimatorAction
  8. from common import common
  9. from vocabularies import VocabType
  10. from config import Config
  11. from model_base import Code2VecModelBase, ModelEvaluationResults, ModelPredictionResults
  12. tf.compat.v1.disable_eager_execution()
  13. class Code2VecModel(Code2VecModelBase):
  14. def __init__(self, config: Config):
  15. self.sess = tf.compat.v1.Session()
  16. self.saver = None
  17. self.eval_reader = None
  18. self.eval_input_iterator_reset_op = None
  19. self.predict_reader = None
  20. # self.eval_placeholder = None
  21. self.predict_placeholder = None
  22. self.eval_top_words_op, self.eval_top_values_op, self.eval_original_names_op, self.eval_code_vectors = None, None, None, None
  23. self.predict_top_words_op, self.predict_top_values_op, self.predict_original_names_op = None, None, None
  24. self.vocab_type_to_tf_variable_name_mapping: Dict[VocabType, str] = {
  25. VocabType.Token: 'WORDS_VOCAB',
  26. VocabType.Target: 'TARGET_WORDS_VOCAB',
  27. VocabType.Path: 'PATHS_VOCAB'
  28. }
  29. super(Code2VecModel, self).__init__(config)
  30. def train(self):
  31. self.log('Starting training')
  32. start_time = time.time()
  33. batch_num = 0
  34. sum_loss = 0
  35. multi_batch_start_time = time.time()
  36. num_batches_to_save_and_eval = max(int(self.config.train_steps_per_epoch * self.config.SAVE_EVERY_EPOCHS), 1)
  37. train_reader = PathContextReader(vocabs=self.vocabs,
  38. model_input_tensors_former=_TFTrainModelInputTensorsFormer(),
  39. config=self.config, estimator_action=EstimatorAction.Train)
  40. input_iterator = tf.compat.v1.data.make_initializable_iterator(train_reader.get_dataset())
  41. input_iterator_reset_op = input_iterator.initializer
  42. input_tensors = input_iterator.get_next()
  43. optimizer, train_loss = self._build_tf_training_graph(input_tensors)
  44. self.saver = tf.compat.v1.train.Saver(max_to_keep=self.config.MAX_TO_KEEP)
  45. self.log('Number of trainable params: {}'.format(
  46. np.sum([np.prod(v.get_shape().as_list()) for v in tf.compat.v1.trainable_variables()])))
  47. for variable in tf.compat.v1.trainable_variables():
  48. self.log("variable name: {} -- shape: {} -- #params: {}".format(
  49. variable.name, variable.get_shape(), np.prod(variable.get_shape().as_list())))
  50. self._initialize_session_variables()
  51. if self.config.MODEL_LOAD_PATH:
  52. self._load_inner_model(self.sess)
  53. self.sess.run(input_iterator_reset_op)
  54. time.sleep(1)
  55. self.log('Started reader...')
  56. # run evaluation in a loop until iterator is exhausted.
  57. try:
  58. while True:
  59. # Each iteration = batch. We iterate as long as the tf iterator (reader) yields batches.
  60. batch_num += 1
  61. # Actual training for the current batch.
  62. _, batch_loss = self.sess.run([optimizer, train_loss])
  63. sum_loss += batch_loss
  64. if batch_num % self.config.NUM_BATCHES_TO_LOG_PROGRESS == 0:
  65. self._trace_training(sum_loss, batch_num, multi_batch_start_time)
  66. # Uri: the "shuffle_batch/random_shuffle_queue_Size:0" op does not exist since the migration to the new reader.
  67. # self.log('Number of waiting examples in queue: %d' % self.sess.run(
  68. # "shuffle_batch/random_shuffle_queue_Size:0"))
  69. sum_loss = 0
  70. multi_batch_start_time = time.time()
  71. if batch_num % num_batches_to_save_and_eval == 0:
  72. epoch_num = int((batch_num / num_batches_to_save_and_eval) * self.config.SAVE_EVERY_EPOCHS)
  73. model_save_path = self.config.MODEL_SAVE_PATH + '_iter' + str(epoch_num)
  74. self.save(model_save_path)
  75. self.log('Saved after %d epochs in: %s' % (epoch_num, model_save_path))
  76. evaluation_results = self.evaluate()
  77. evaluation_results_str = (str(evaluation_results).replace('topk', 'top{}'.format(
  78. self.config.TOP_K_WORDS_CONSIDERED_DURING_PREDICTION)))
  79. self.log('After {nr_epochs} epochs -- {evaluation_results}'.format(
  80. nr_epochs=epoch_num,
  81. evaluation_results=evaluation_results_str
  82. ))
  83. except tf.errors.OutOfRangeError:
  84. pass # The reader iterator is exhausted and have no more batches to produce.
  85. self.log('Done training')
  86. if self.config.MODEL_SAVE_PATH:
  87. self._save_inner_model(self.config.MODEL_SAVE_PATH)
  88. self.log('Model saved in file: %s' % self.config.MODEL_SAVE_PATH)
  89. elapsed = int(time.time() - start_time)
  90. self.log("Training time: %sH:%sM:%sS\n" % ((elapsed // 60 // 60), (elapsed // 60) % 60, elapsed % 60))
  91. def evaluate(self) -> Optional[ModelEvaluationResults]:
  92. eval_start_time = time.time()
  93. if self.eval_reader is None:
  94. self.eval_reader = PathContextReader(vocabs=self.vocabs,
  95. model_input_tensors_former=_TFEvaluateModelInputTensorsFormer(),
  96. config=self.config, estimator_action=EstimatorAction.Evaluate)
  97. input_iterator = tf.compat.v1.data.make_initializable_iterator(self.eval_reader.get_dataset())
  98. self.eval_input_iterator_reset_op = input_iterator.initializer
  99. input_tensors = input_iterator.get_next()
  100. self.eval_top_words_op, self.eval_top_values_op, self.eval_original_names_op, _, _, _, _, \
  101. self.eval_code_vectors = self._build_tf_test_graph(input_tensors)
  102. self.saver = tf.compat.v1.train.Saver()
  103. if self.config.MODEL_LOAD_PATH and not self.config.TRAIN_DATA_PATH_PREFIX:
  104. self._initialize_session_variables()
  105. self._load_inner_model(self.sess)
  106. if self.config.RELEASE:
  107. release_name = self.config.MODEL_LOAD_PATH + '.release'
  108. self.log('Releasing model, output model: %s' % release_name)
  109. self.saver.save(self.sess, release_name)
  110. return None # FIXME: why do we return none here?
  111. with open('log.txt', 'w') as log_output_file:
  112. if self.config.EXPORT_CODE_VECTORS:
  113. code_vectors_file = open(self.config.TEST_DATA_PATH + '.vectors', 'w')
  114. total_predictions = 0
  115. total_prediction_batches = 0
  116. subtokens_evaluation_metric = SubtokensEvaluationMetric(
  117. partial(common.filter_impossible_names, self.vocabs.target_vocab.special_words))
  118. topk_accuracy_evaluation_metric = TopKAccuracyEvaluationMetric(
  119. self.config.TOP_K_WORDS_CONSIDERED_DURING_PREDICTION,
  120. partial(common.get_first_match_word_from_top_predictions, self.vocabs.target_vocab.special_words))
  121. start_time = time.time()
  122. self.sess.run(self.eval_input_iterator_reset_op)
  123. self.log('Starting evaluation')
  124. # Run evaluation in a loop until iterator is exhausted.
  125. # Each iteration = batch. We iterate as long as the tf iterator (reader) yields batches.
  126. try:
  127. while True:
  128. top_words, top_scores, original_names, code_vectors = self.sess.run(
  129. [self.eval_top_words_op, self.eval_top_values_op,
  130. self.eval_original_names_op, self.eval_code_vectors],
  131. )
  132. # shapes:
  133. # top_words: (batch, top_k); top_scores: (batch, top_k)
  134. # original_names: (batch, ); code_vectors: (batch, code_vector_size)
  135. top_words = common.binary_to_string_matrix(top_words) # (batch, top_k)
  136. original_names = common.binary_to_string_list(original_names) # (batch,)
  137. self._log_predictions_during_evaluation(zip(original_names, top_words), log_output_file)
  138. topk_accuracy_evaluation_metric.update_batch(zip(original_names, top_words))
  139. subtokens_evaluation_metric.update_batch(zip(original_names, top_words))
  140. total_predictions += len(original_names)
  141. total_prediction_batches += 1
  142. if self.config.EXPORT_CODE_VECTORS:
  143. self._write_code_vectors(code_vectors_file, code_vectors)
  144. if total_prediction_batches % self.config.NUM_BATCHES_TO_LOG_PROGRESS == 0:
  145. elapsed = time.time() - start_time
  146. # start_time = time.time()
  147. self._trace_evaluation(total_predictions, elapsed)
  148. except tf.errors.OutOfRangeError:
  149. pass # reader iterator is exhausted and have no more batches to produce.
  150. self.log('Done evaluating, epoch reached')
  151. log_output_file.write(str(topk_accuracy_evaluation_metric.topk_correct_predictions) + '\n')
  152. if self.config.EXPORT_CODE_VECTORS:
  153. code_vectors_file.close()
  154. elapsed = int(time.time() - eval_start_time)
  155. self.log("Evaluation time: %sH:%sM:%sS" % ((elapsed // 60 // 60), (elapsed // 60) % 60, elapsed % 60))
  156. return ModelEvaluationResults(
  157. topk_acc=topk_accuracy_evaluation_metric.topk_correct_predictions,
  158. subtoken_precision=subtokens_evaluation_metric.precision,
  159. subtoken_recall=subtokens_evaluation_metric.recall,
  160. subtoken_f1=subtokens_evaluation_metric.f1)
  161. def _build_tf_training_graph(self, input_tensors):
  162. # Use `_TFTrainModelInputTensorsFormer` to access input tensors by name.
  163. input_tensors = _TFTrainModelInputTensorsFormer().from_model_input_form(input_tensors)
  164. # shape of (batch, 1) for input_tensors.target_index
  165. # shape of (batch, max_contexts) for others:
  166. # input_tensors.path_source_token_indices, input_tensors.path_indices,
  167. # input_tensors.path_target_token_indices, input_tensors.context_valid_mask
  168. with tf.compat.v1.variable_scope('model'):
  169. tokens_vocab = tf.compat.v1.get_variable(
  170. self.vocab_type_to_tf_variable_name_mapping[VocabType.Token],
  171. shape=(self.vocabs.token_vocab.size, self.config.TOKEN_EMBEDDINGS_SIZE), dtype=tf.float32,
  172. initializer=tf.compat.v1.initializers.variance_scaling(scale=1.0, mode='fan_out', distribution="uniform"))
  173. targets_vocab = tf.compat.v1.get_variable(
  174. self.vocab_type_to_tf_variable_name_mapping[VocabType.Target],
  175. shape=(self.vocabs.target_vocab.size, self.config.TARGET_EMBEDDINGS_SIZE), dtype=tf.float32,
  176. initializer=tf.compat.v1.initializers.variance_scaling(scale=1.0, mode='fan_out', distribution="uniform"))
  177. attention_param = tf.compat.v1.get_variable(
  178. 'ATTENTION',
  179. shape=(self.config.CODE_VECTOR_SIZE, 1), dtype=tf.float32)
  180. paths_vocab = tf.compat.v1.get_variable(
  181. self.vocab_type_to_tf_variable_name_mapping[VocabType.Path],
  182. shape=(self.vocabs.path_vocab.size, self.config.PATH_EMBEDDINGS_SIZE), dtype=tf.float32,
  183. initializer=tf.compat.v1.initializers.variance_scaling(scale=1.0, mode='fan_out', distribution="uniform"))
  184. code_vectors, _ = self._calculate_weighted_contexts(
  185. tokens_vocab, paths_vocab, attention_param, input_tensors.path_source_token_indices,
  186. input_tensors.path_indices, input_tensors.path_target_token_indices, input_tensors.context_valid_mask)
  187. logits = tf.matmul(code_vectors, targets_vocab, transpose_b=True)
  188. batch_size = tf.cast(tf.shape(input_tensors.target_index)[0], dtype=tf.float32)
  189. loss = tf.reduce_sum(tf.nn.sparse_softmax_cross_entropy_with_logits(
  190. labels=tf.reshape(input_tensors.target_index, [-1]),
  191. logits=logits)) / batch_size
  192. optimizer = tf.compat.v1.train.AdamOptimizer().minimize(loss)
  193. return optimizer, loss
  194. def _calculate_weighted_contexts(self, tokens_vocab, paths_vocab, attention_param, source_input, path_input,
  195. target_input, valid_mask, is_evaluating=False):
  196. source_word_embed = tf.nn.embedding_lookup(params=tokens_vocab, ids=source_input) # (batch, max_contexts, dim)
  197. path_embed = tf.nn.embedding_lookup(params=paths_vocab, ids=path_input) # (batch, max_contexts, dim)
  198. target_word_embed = tf.nn.embedding_lookup(params=tokens_vocab, ids=target_input) # (batch, max_contexts, dim)
  199. context_embed = tf.concat([source_word_embed, path_embed, target_word_embed],
  200. axis=-1) # (batch, max_contexts, dim * 3)
  201. if not is_evaluating:
  202. context_embed = tf.nn.dropout(context_embed, rate=1-self.config.DROPOUT_KEEP_RATE)
  203. flat_embed = tf.reshape(context_embed, [-1, self.config.context_vector_size]) # (batch * max_contexts, dim * 3)
  204. transform_param = tf.compat.v1.get_variable(
  205. 'TRANSFORM', shape=(self.config.context_vector_size, self.config.CODE_VECTOR_SIZE), dtype=tf.float32)
  206. flat_embed = tf.tanh(tf.matmul(flat_embed, transform_param)) # (batch * max_contexts, dim * 3)
  207. contexts_weights = tf.matmul(flat_embed, attention_param) # (batch * max_contexts, 1)
  208. batched_contexts_weights = tf.reshape(
  209. contexts_weights, [-1, self.config.MAX_CONTEXTS, 1]) # (batch, max_contexts, 1)
  210. mask = tf.math.log(valid_mask) # (batch, max_contexts)
  211. mask = tf.expand_dims(mask, axis=2) # (batch, max_contexts, 1)
  212. batched_contexts_weights += mask # (batch, max_contexts, 1)
  213. attention_weights = tf.nn.softmax(batched_contexts_weights, axis=1) # (batch, max_contexts, 1)
  214. batched_embed = tf.reshape(flat_embed, shape=[-1, self.config.MAX_CONTEXTS, self.config.CODE_VECTOR_SIZE])
  215. code_vectors = tf.reduce_sum(tf.multiply(batched_embed, attention_weights), axis=1) # (batch, dim * 3)
  216. return code_vectors, attention_weights
  217. def _build_tf_test_graph(self, input_tensors, normalize_scores=False):
  218. with tf.compat.v1.variable_scope('model', reuse=self.get_should_reuse_variables()):
  219. tokens_vocab = tf.compat.v1.get_variable(
  220. self.vocab_type_to_tf_variable_name_mapping[VocabType.Token],
  221. shape=(self.vocabs.token_vocab.size, self.config.TOKEN_EMBEDDINGS_SIZE),
  222. dtype=tf.float32, trainable=False)
  223. targets_vocab = tf.compat.v1.get_variable(
  224. self.vocab_type_to_tf_variable_name_mapping[VocabType.Target],
  225. shape=(self.vocabs.target_vocab.size, self.config.TARGET_EMBEDDINGS_SIZE),
  226. dtype=tf.float32, trainable=False)
  227. attention_param = tf.compat.v1.get_variable(
  228. 'ATTENTION', shape=(self.config.context_vector_size, 1),
  229. dtype=tf.float32, trainable=False)
  230. paths_vocab = tf.compat.v1.get_variable(
  231. self.vocab_type_to_tf_variable_name_mapping[VocabType.Path],
  232. shape=(self.vocabs.path_vocab.size, self.config.PATH_EMBEDDINGS_SIZE),
  233. dtype=tf.float32, trainable=False)
  234. targets_vocab = tf.transpose(targets_vocab) # (dim * 3, target_word_vocab)
  235. # Use `_TFEvaluateModelInputTensorsFormer` to access input tensors by name.
  236. input_tensors = _TFEvaluateModelInputTensorsFormer().from_model_input_form(input_tensors)
  237. # shape of (batch, 1) for input_tensors.target_string
  238. # shape of (batch, max_contexts) for the other tensors
  239. code_vectors, attention_weights = self._calculate_weighted_contexts(
  240. tokens_vocab, paths_vocab, attention_param, input_tensors.path_source_token_indices,
  241. input_tensors.path_indices, input_tensors.path_target_token_indices,
  242. input_tensors.context_valid_mask, is_evaluating=True)
  243. scores = tf.matmul(code_vectors, targets_vocab) # (batch, target_word_vocab)
  244. topk_candidates = tf.nn.top_k(scores, k=tf.minimum(
  245. self.config.TOP_K_WORDS_CONSIDERED_DURING_PREDICTION, self.vocabs.target_vocab.size))
  246. top_indices = topk_candidates.indices
  247. top_words = self.vocabs.target_vocab.lookup_word(top_indices)
  248. original_words = input_tensors.target_string
  249. top_scores = topk_candidates.values
  250. if normalize_scores:
  251. top_scores = tf.nn.softmax(top_scores)
  252. return top_words, top_scores, original_words, attention_weights, input_tensors.path_source_token_strings, \
  253. input_tensors.path_strings, input_tensors.path_target_token_strings, code_vectors
  254. def predict(self, predict_data_lines: Iterable[str]) -> List[ModelPredictionResults]:
  255. if self.predict_reader is None:
  256. self.predict_reader = PathContextReader(vocabs=self.vocabs,
  257. model_input_tensors_former=_TFEvaluateModelInputTensorsFormer(),
  258. config=self.config, estimator_action=EstimatorAction.Predict)
  259. self.predict_placeholder = tf.compat.v1.placeholder(tf.string)
  260. reader_output = self.predict_reader.process_input_row(self.predict_placeholder)
  261. self.predict_top_words_op, self.predict_top_values_op, self.predict_original_names_op, \
  262. self.attention_weights_op, self.predict_source_string, self.predict_path_string, \
  263. self.predict_path_target_string, self.predict_code_vectors = \
  264. self._build_tf_test_graph(reader_output, normalize_scores=True)
  265. self._initialize_session_variables()
  266. self.saver = tf.compat.v1.train.Saver()
  267. self._load_inner_model(sess=self.sess)
  268. prediction_results: List[ModelPredictionResults] = []
  269. for line in predict_data_lines:
  270. batch_top_words, batch_top_scores, batch_original_name, batch_attention_weights, batch_path_source_strings,\
  271. batch_path_strings, batch_path_target_strings, batch_code_vectors = self.sess.run(
  272. [self.predict_top_words_op, self.predict_top_values_op, self.predict_original_names_op,
  273. self.attention_weights_op, self.predict_source_string, self.predict_path_string,
  274. self.predict_path_target_string, self.predict_code_vectors],
  275. feed_dict={self.predict_placeholder: line})
  276. # shapes:
  277. # batch_top_words, top_scores: (batch, top_k)
  278. # batch_original_name: (batch, )
  279. # batch_attention_weights: (batch, max_context, 1)
  280. # batch_path_source_strings, batch_path_strings, batch_path_target_strings: (batch, max_context)
  281. # batch_code_vectors: (batch, code_vector_size)
  282. # remove first axis: (batch=1, ...)
  283. assert all(tensor.shape[0] == 1 for tensor in (batch_top_words, batch_top_scores, batch_original_name,
  284. batch_attention_weights, batch_path_source_strings,
  285. batch_path_strings, batch_path_target_strings,
  286. batch_code_vectors))
  287. top_words = np.squeeze(batch_top_words, axis=0)
  288. top_scores = np.squeeze(batch_top_scores, axis=0)
  289. original_name = batch_original_name[0]
  290. attention_weights = np.squeeze(batch_attention_weights, axis=0)
  291. path_source_strings = np.squeeze(batch_path_source_strings, axis=0)
  292. path_strings = np.squeeze(batch_path_strings, axis=0)
  293. path_target_strings = np.squeeze(batch_path_target_strings, axis=0)
  294. code_vectors = np.squeeze(batch_code_vectors, axis=0)
  295. top_words = common.binary_to_string_list(top_words)
  296. original_name = common.binary_to_string(original_name)
  297. attention_per_context = self._get_attention_weight_per_context(
  298. path_source_strings, path_strings, path_target_strings, attention_weights)
  299. prediction_results.append(ModelPredictionResults(
  300. original_name=original_name,
  301. topk_predicted_words=top_words,
  302. topk_predicted_words_scores=top_scores,
  303. attention_per_context=attention_per_context,
  304. code_vector=(code_vectors if self.config.EXPORT_CODE_VECTORS else None)
  305. ))
  306. return prediction_results
  307. def _save_inner_model(self, path: str):
  308. self.saver.save(self.sess, path)
  309. def _load_inner_model(self, sess=None):
  310. if sess is not None:
  311. self.log('Loading model weights from: ' + self.config.MODEL_LOAD_PATH)
  312. self.saver.restore(sess, self.config.MODEL_LOAD_PATH)
  313. self.log('Done loading model weights')
  314. def _get_vocab_embedding_as_np_array(self, vocab_type: VocabType) -> np.ndarray:
  315. assert vocab_type in VocabType
  316. vocab_tf_variable_name = self.vocab_type_to_tf_variable_name_mapping[vocab_type]
  317. if self.eval_reader is None:
  318. self.eval_reader = PathContextReader(vocabs=self.vocabs,
  319. model_input_tensors_former=_TFEvaluateModelInputTensorsFormer(),
  320. config=self.config, estimator_action=EstimatorAction.Evaluate)
  321. input_iterator = tf.compat.v1.data.make_initializable_iterator(self.eval_reader.get_dataset())
  322. _, _, _, _, _, _, _, _ = self._build_tf_test_graph(input_iterator.get_next())
  323. if vocab_type is VocabType.Token:
  324. shape = (self.vocabs.token_vocab.size, self.config.TOKEN_EMBEDDINGS_SIZE)
  325. elif vocab_type is VocabType.Target:
  326. shape = (self.vocabs.target_vocab.size, self.config.TARGET_EMBEDDINGS_SIZE)
  327. elif vocab_type is VocabType.Path:
  328. shape = (self.vocabs.path_vocab.size, self.config.PATH_EMBEDDINGS_SIZE)
  329. with tf.compat.v1.variable_scope('model', reuse=True):
  330. embeddings = tf.compat.v1.get_variable(vocab_tf_variable_name, shape=shape)
  331. self.saver = tf.compat.v1.train.Saver()
  332. self._initialize_session_variables()
  333. self._load_inner_model(self.sess)
  334. vocab_embedding_matrix = self.sess.run(embeddings)
  335. return vocab_embedding_matrix
  336. def get_should_reuse_variables(self):
  337. if self.config.TRAIN_DATA_PATH_PREFIX:
  338. return True
  339. else:
  340. return None
  341. def _log_predictions_during_evaluation(self, results, output_file):
  342. for original_name, top_predicted_words in results:
  343. found_match = common.get_first_match_word_from_top_predictions(
  344. self.vocabs.target_vocab.special_words, original_name, top_predicted_words)
  345. if found_match is not None:
  346. prediction_idx, predicted_word = found_match
  347. if prediction_idx == 0:
  348. output_file.write('Original: ' + original_name + ', predicted 1st: ' + predicted_word + '\n')
  349. else:
  350. output_file.write('\t\t predicted correctly at rank: ' + str(prediction_idx + 1) + '\n')
  351. else:
  352. output_file.write('No results for predicting: ' + original_name)
  353. def _trace_training(self, sum_loss, batch_num, multi_batch_start_time):
  354. multi_batch_elapsed = time.time() - multi_batch_start_time
  355. avg_loss = sum_loss / (self.config.NUM_BATCHES_TO_LOG_PROGRESS * self.config.TRAIN_BATCH_SIZE)
  356. throughput = self.config.TRAIN_BATCH_SIZE * self.config.NUM_BATCHES_TO_LOG_PROGRESS / \
  357. (multi_batch_elapsed if multi_batch_elapsed > 0 else 1)
  358. self.log('Average loss at batch %d: %f, \tthroughput: %d samples/sec' % (
  359. batch_num, avg_loss, throughput))
  360. def _trace_evaluation(self, total_predictions, elapsed):
  361. state_message = 'Evaluated %d examples...' % total_predictions
  362. throughput_message = "Prediction throughput: %d samples/sec" % int(
  363. total_predictions / (elapsed if elapsed > 0 else 1))
  364. self.log(state_message)
  365. self.log(throughput_message)
  366. def close_session(self):
  367. self.sess.close()
  368. def _initialize_session_variables(self):
  369. self.sess.run(tf.group(
  370. tf.compat.v1.global_variables_initializer(),
  371. tf.compat.v1.local_variables_initializer(),
  372. tf.compat.v1.tables_initializer()))
  373. self.log('Initalized variables')
  374. class SubtokensEvaluationMetric:
  375. def __init__(self, filter_impossible_names_fn):
  376. self.nr_true_positives: int = 0
  377. self.nr_false_positives: int = 0
  378. self.nr_false_negatives: int = 0
  379. self.nr_predictions: int = 0
  380. self.filter_impossible_names_fn = filter_impossible_names_fn
  381. def update_batch(self, results):
  382. for original_name, top_words in results:
  383. prediction = self.filter_impossible_names_fn(top_words)[0]
  384. original_subtokens = Counter(common.get_subtokens(original_name))
  385. predicted_subtokens = Counter(common.get_subtokens(prediction))
  386. self.nr_true_positives += sum(count for element, count in predicted_subtokens.items()
  387. if element in original_subtokens)
  388. self.nr_false_positives += sum(count for element, count in predicted_subtokens.items()
  389. if element not in original_subtokens)
  390. self.nr_false_negatives += sum(count for element, count in original_subtokens.items()
  391. if element not in predicted_subtokens)
  392. self.nr_predictions += 1
  393. @property
  394. def true_positive(self):
  395. return self.nr_true_positives / self.nr_predictions
  396. @property
  397. def false_positive(self):
  398. return self.nr_false_positives / self.nr_predictions
  399. @property
  400. def false_negative(self):
  401. return self.nr_false_negatives / self.nr_predictions
  402. @property
  403. def precision(self):
  404. return self.nr_true_positives / (self.nr_true_positives + self.nr_false_positives)
  405. @property
  406. def recall(self):
  407. return self.nr_true_positives / (self.nr_true_positives + self.nr_false_negatives)
  408. @property
  409. def f1(self):
  410. return 2 * self.precision * self.recall / (self.precision + self.recall)
  411. class TopKAccuracyEvaluationMetric:
  412. def __init__(self, top_k: int, get_first_match_word_from_top_predictions_fn):
  413. self.top_k = top_k
  414. self.nr_correct_predictions = np.zeros(self.top_k)
  415. self.nr_predictions: int = 0
  416. self.get_first_match_word_from_top_predictions_fn = get_first_match_word_from_top_predictions_fn
  417. def update_batch(self, results):
  418. for original_name, top_predicted_words in results:
  419. self.nr_predictions += 1
  420. found_match = self.get_first_match_word_from_top_predictions_fn(original_name, top_predicted_words)
  421. if found_match is not None:
  422. suggestion_idx, _ = found_match
  423. self.nr_correct_predictions[suggestion_idx:self.top_k] += 1
  424. @property
  425. def topk_correct_predictions(self):
  426. return self.nr_correct_predictions / self.nr_predictions
  427. class _TFTrainModelInputTensorsFormer(ModelInputTensorsFormer):
  428. def to_model_input_form(self, input_tensors: ReaderInputTensors):
  429. return input_tensors.target_index, input_tensors.path_source_token_indices, input_tensors.path_indices, \
  430. input_tensors.path_target_token_indices, input_tensors.context_valid_mask
  431. def from_model_input_form(self, input_row) -> ReaderInputTensors:
  432. return ReaderInputTensors(
  433. target_index=input_row[0],
  434. path_source_token_indices=input_row[1],
  435. path_indices=input_row[2],
  436. path_target_token_indices=input_row[3],
  437. context_valid_mask=input_row[4]
  438. )
  439. class _TFEvaluateModelInputTensorsFormer(ModelInputTensorsFormer):
  440. def to_model_input_form(self, input_tensors: ReaderInputTensors):
  441. return input_tensors.target_string, input_tensors.path_source_token_indices, input_tensors.path_indices, \
  442. input_tensors.path_target_token_indices, input_tensors.context_valid_mask, \
  443. input_tensors.path_source_token_strings, input_tensors.path_strings, \
  444. input_tensors.path_target_token_strings
  445. def from_model_input_form(self, input_row) -> ReaderInputTensors:
  446. return ReaderInputTensors(
  447. target_string=input_row[0],
  448. path_source_token_indices=input_row[1],
  449. path_indices=input_row[2],
  450. path_target_token_indices=input_row[3],
  451. context_valid_mask=input_row[4],
  452. path_source_token_strings=input_row[5],
  453. path_strings=input_row[6],
  454. path_target_token_strings=input_row[7]
  455. )
Tip!

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

Comments

Loading...