-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathcode_nlm.py
2331 lines (2104 loc) · 107 KB
/
code_nlm.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
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# some structure based on https://github.com/wpm/tfrnnlm/blob/master/tfrnnlm/rnn.py
#https://github.com/tensorflow/tensorflow/pull/2580/files#diff-083dd112b4600ecbaf63b2070951aad8
from __future__ import print_function
import ast
import time
from datetime import timedelta
import inspect
import math
import json
import os.path
import sys
import shutil
import heapq
import pygtrie as trie
from collections import deque
from itertools import chain
from operator import itemgetter
import numpy as np
import tensorflow as tf
import reader
# BPE imports
# import codecs
# from subword_nmt.apply_bpe import BPE, read_vocabulary
flags = tf.flags
# Path options
flags.DEFINE_string("data_path", None, "Path to folder containing training/test data.")
flags.DEFINE_string("train_dir", None, "Output directory for saving the model.")
# Scenario options. Training is default so, no option for it.
flags.DEFINE_boolean("predict", False, "Set to True for computing predictability.")
flags.DEFINE_boolean("test", False, "Set to True for computing test perplexity.")
flags.DEFINE_boolean("dynamic_test", False, "Set to True for performing dynamic train-testing perplexity calculation (only one train epoch).")
flags.DEFINE_boolean("maintenance_test", False, "Set to True for performing maintenance train-testing perplexity simulation (only one train epoch).")
flags.DEFINE_boolean("completion", False, "Set to True to run code completion experiment.")
flags.DEFINE_boolean("maintenance_completion", False, "Set to True to run maintenance code completion experiment")
flags.DEFINE_boolean("dynamic", False, "Set to True to run dynamic code completion experiment.")
# Filename/path options
flags.DEFINE_string("train_filename", None, "The train file on which to train.")
flags.DEFINE_string("validation_filename", None, "The test file on which to run validation.")
flags.DEFINE_string("test_filename", None, "The test file on which to compute perplexity or predictability.")
flags.DEFINE_string("test_proj_filename", None, "The file that contains the test project name for each test instance.")
flags.DEFINE_string("identifier_map", None, "The file that contains information about which tokens are identifiers.")
flags.DEFINE_boolean("cache_ids", False, "Set to True to cache project identifiers during completion.")
# flags.DEFINE_string("BPE", None, "The file containing the BPE encoding.")
flags.DEFINE_string("subtoken_map", None, "Contains the mapping from heyristic subtokens to tokens.")
# flags.DEFINE_string("output_probs_file", "predictionProbabilities.txt", "The file to store output probabilities.")
# Network architecture/hyper-parameter options
flags.DEFINE_integer("num_layers", 1, "Number of Layers. Using a single layer is advised.")
flags.DEFINE_integer("hidden_size", 512, "Hidden size. Number of dimensions for the embeddings and RNN hidden state.")
flags.DEFINE_float("keep_prob", 0.5, "Keep probability = 1.0 - dropout probability.")
flags.DEFINE_integer("vocab_size", 25000, "Vocabulary size")
flags.DEFINE_boolean("gru", False, "Use a GRU cell. Must be set to True to use a GRU, otherwise an LSTM will be used.")
flags.DEFINE_integer("steps_per_checkpoint", 5000, "Number of steps for printing stats (validation is run) and checkpointing the model. Must be increased by 'a lot' for large training corpora.")
flags.DEFINE_integer("max_epoch", 30, "Max number training epochs to run.")
flags.DEFINE_integer("batch_size", 32, "Batch size")
flags.DEFINE_integer("test_batch_size", 10, "Batch size during predictability test")
flags.DEFINE_integer("num_steps", 200, "Sequence length.")
flags.DEFINE_float("init_scale", 0.05, "Initialization scale.")
flags.DEFINE_float("learning_rate", 0.1, "Learning rate")
flags.DEFINE_float("max_grad_norm", 5.0, "Clip gradients to this norm")
flags.DEFINE_float("lr_decay", 0.5, "Learning rate decay. Default is 0.5 which halves the learning rate.")
# n-gram identifier cache options
flags.DEFINE_float("file_cache_weight", 0.2, "Weight of the file cache.")
flags.DEFINE_integer("cache_order", 6, "n-gram order for the identifier cache")
flags.DEFINE_integer("thresh", 0, "Threshold for vocabulary inclusion.")
flags.DEFINE_boolean("unk", True, "use -UNK- token to model OOV.")
flags.DEFINE_boolean("bidirectional", False, "Bidirectional model.")
flags.DEFINE_boolean("word_level_perplexity", False, "Convert to word level perplexity.")
flags.DEFINE_boolean("cross_entropy", False, "Print cross-entropy for validation/test instead of perplexity.")
flags.DEFINE_boolean("token_model", False, "Whether it is a token level model.")
flags.DEFINE_boolean("completion_unk_wrong", False, "Whether completing -UNK- should contribute in MRR. Set to "
"True for Allamanis et al. heuristic subtoken model.")
flags.DEFINE_boolean("verbose", False, "Verbose for completion.")
FLAGS = flags.FLAGS
def data_type():
"""
Returns the TF floating point type used for operations.
:return: The data type used (tf.float32)
"""
return tf.float32
def get_gpu_config():
gconfig = tf.ConfigProto()
gconfig.gpu_options.per_process_gpu_memory_fraction = 0.975 # Don't take 100% of the memory
gconfig.allow_soft_placement = True # Does not aggressively take all the GPU memory
gconfig.gpu_options.allow_growth = True # Take more memory when necessary
return gconfig
class NLM(object):
def __init__(self, config):
"""
Initializes the neural language model based on the specified configation.
:param config: The configuration to be used for initialization.
"""
self.num_layers = config.num_layers
self.batch_size = batch_size = config.batch_size
self.num_steps = num_steps = config.num_steps
self.hidden_size = hidden_size = config.hidden_size
self.vocab_size = vocab_size = config.vocab_size
#self.predictions_file = config.output_probs_file
self.global_step = tf.Variable(0, trainable=False)
with tf.name_scope("Parameters"):
# Sets dropout and learning rate.
self.learning_rate = tf.placeholder(tf.float32, name="learning_rate")
self.keep_probability = tf.placeholder(tf.float32, name="keep_probability")
with tf.name_scope("Input"):
self.inputd = tf.placeholder(tf.int64, shape=(batch_size, None), name="inputd")
self.targets = tf.placeholder(tf.int64, shape=(batch_size, None), name="targets")
self.target_weights = tf.placeholder(tf.float32, shape=(batch_size, None), name="tgtweights")
with tf.device("/cpu:0"):
with tf.name_scope("Embedding"):
# Initialize embeddings on the CPU and add dropout layer after embeddings.
self.embedding = tf.Variable(tf.random_uniform((vocab_size, hidden_size), -config.init_scale, config.init_scale), dtype=data_type(), name="embedding")
self.embedded_inputds = tf.nn.embedding_lookup(self.embedding, self.inputd, name="embedded_inputds")
self.embedded_inputds = tf.nn.dropout(self.embedded_inputds, self.keep_probability)
with tf.name_scope("RNN"):
# Definitions for the different cells that can be used. Either lstm or GRU which will be wrapped with dropout.
def lstm_cell():
if 'reuse' in inspect.getargspec(tf.contrib.rnn.BasicLSTMCell.__init__).args:
return tf.contrib.rnn.BasicLSTMCell(hidden_size, forget_bias=0.0, state_is_tuple=True, reuse=tf.get_variable_scope().reuse)
else:
return tf.contrib.rnn.BasicLSTMCell(hidden_size, forget_bias=0.0, state_is_tuple=True)
def gru_cell():
if 'reuse' in inspect.getargspec(tf.contrib.rnn.GRUCell.__init__).args:
return tf.contrib.rnn.GRUCell(hidden_size, reuse=tf.get_variable_scope().reuse)
else:
return tf.contrib.rnn.GRUCell(hidden_size)
def drop_cell():
if FLAGS.gru:
return tf.contrib.rnn.DropoutWrapper(gru_cell(), output_keep_prob=self.keep_probability)
else:
return tf.contrib.rnn.DropoutWrapper(lstm_cell(), output_keep_prob=self.keep_probability)
# Allows multiple layers to be used. Not advised though.
rnn_layers = tf.contrib.rnn.MultiRNNCell([drop_cell() for _ in range(self.num_layers)], state_is_tuple=True)
# Initialize the state to zero.
self.reset_state = rnn_layers.zero_state(batch_size, data_type())
self.outputs, self.next_state = tf.nn.dynamic_rnn(rnn_layers, self.embedded_inputds, time_major=False,
initial_state=self.reset_state)
with tf.name_scope("Cost"):
# Output and loss function calculation
self.output = tf.reshape(tf.concat(axis=0, values=self.outputs), [-1, hidden_size])
self.softmax_w = tf.get_variable("softmax_w", [hidden_size, vocab_size], dtype=data_type())
self.softmax_b = tf.get_variable("softmax_b", [vocab_size], dtype=data_type())
self.logits = tf.matmul(self.output, self.softmax_w) + self.softmax_b
self.loss = tf.contrib.legacy_seq2seq.sequence_loss_by_example(
[self.logits], [tf.reshape(self.targets, [-1])], [tf.reshape(self.target_weights, [-1])])
self.cost = tf.div(tf.reduce_sum(self.loss), batch_size, name="cost")
self.final_state = self.next_state
self.norm_logits = tf.nn.softmax(self.logits)
with tf.name_scope("Train"):
self.iteration = tf.Variable(0, dtype=data_type(), name="iteration", trainable=False)
tvars = tf.trainable_variables()
self.gradients, _ = tf.clip_by_global_norm(tf.gradients(self.cost, tvars),
config.max_grad_norm, name="clip_gradients")
optimizer = tf.train.GradientDescentOptimizer(self.learning_rate)
self.train_step = optimizer.apply_gradients(zip(self.gradients, tvars), name="train_step",
global_step=self.global_step)
self.validation_perplexity = tf.Variable(dtype=data_type(), initial_value=float("inf"),
trainable=False, name="validation_perplexity")
tf.summary.scalar(self.validation_perplexity.op.name, self.validation_perplexity)
self.training_epoch_perplexity = tf.Variable(dtype=data_type(), initial_value=float("inf"),
trainable=False, name="training_epoch_perplexity")
tf.summary.scalar(self.training_epoch_perplexity.op.name, self.training_epoch_perplexity)
self.saver = tf.train.Saver(tf.global_variables(), max_to_keep=None)
self.initialize = tf.initialize_all_variables()
self.summary = tf.summary.merge_all()
def get_parameter_count(self, debug=False):
"""
Counts the number of parameters required by the model.
:param debug: Whether debugging information should be printed.
:return: Returns the number of parameters required for the model.
"""
params = tf.trainable_variables()
total_parameters = 0
for variable in params:
shape = variable.get_shape()
variable_parameters = 1
for dim in shape:
variable_parameters *= dim.value
if debug:
print(variable)
print(shape + "\t" + str(len(shape)) + "\t" + str(variable_parameters))
total_parameters += variable_parameters
return total_parameters
@property
def reset_state(self):
return self._reset_state
@reset_state.setter
def reset_state(self, x):
self._reset_state = x
@property
def cost(self):
return self._cost
@cost.setter
def cost(self, y):
self._cost = y
@property
def final_state(self):
return self._final_state
@final_state.setter
def final_state(self, z):
self._final_state = z
@property
def learning_rate(self):
return self._lr
@learning_rate.setter
def learning_rate(self, l):
self._lr = l
@property
def input(self):
return self.data
def train(self, session, config, train_data, exit_criteria, valid_data, summary_dir):
"""
Trains the NLM with the specified configuration, training, and validation data.
Training is terminated when the specified criteria have been satisfied.
:param session: The TF session in which operations should be run.
:param config: The configuration to be used for the model.
:param train_data: The dataset instance to use for training.
:param exit_criteria: The training termination criteria.
:param valid_data: The dataset instance to use for validation.
:param summary_dir: Directory in which summary information will be stored.
"""
summary_writer = tf.summary.FileWriter(summary_dir, session.graph)
previous_valid_log_ppx = []
nglobal_steps = 0
epoch = 1
new_learning_rate = config.learning_rate
state = session.run(self.reset_state)
try:
while True:
epoch_log_perp_unnorm = epoch_total_weights = 0.0
print("Epoch %d Learning rate %0.3f" % (epoch, new_learning_rate))
epoch_start_time = time.time()
# Runs each training step. A step is processing a minibatch of context-target pairs.
for step, (context, target, target_weights) in enumerate(
train_data.batch_producer_memory_efficient(self.batch_size, self.num_steps)):
# Every steps_per_checkpoint steps run validation and print perplexity/entropy.
if step % FLAGS.steps_per_checkpoint == 0:
print('Train steps:', step)
if step >0:
validation_perplexity = self.test(session, config, valid_data)
validation_log_perplexity = math.log(validation_perplexity)
print("global_steps %d learning_rate %.4f valid_perplexity %.2f" % (nglobal_steps, new_learning_rate, validation_perplexity))
sys.stdout.flush()
feed_dict = {self.inputd: context,
self.targets: target,
self.target_weights: target_weights,
self.learning_rate: new_learning_rate,
self.keep_probability: config.keep_prob
}
if FLAGS.gru:
for i, h in enumerate(self.reset_state):
feed_dict[h] = state[i]
else: # LSTM cell
for i, (c, h) in enumerate(self.reset_state):
feed_dict[c] = state[i].c
feed_dict[h] = state[i].h
# Run the actual training step.
_, cost, state, loss, iteration = session.run([self.train_step, self.cost, self.next_state, self.loss, self.iteration], feed_dict)
nglobal_steps += 1
# Add step loss and weights to the total.
epoch_log_perp_unnorm += np.sum(loss)
epoch_total_weights += np.sum(sum(target_weights))
# epoch_total_weights += np.sum(sum(sub_target_weights))
train_log_perplexity = epoch_log_perp_unnorm / epoch_total_weights
train_perplexity = math.exp(train_log_perplexity) if train_log_perplexity < 300 else float("inf")
validation_perplexity = self.test(session, config, valid_data)
validation_log_perplexity = math.log(validation_perplexity)
# Checkpoint and save the model.
checkpoint_path = os.path.join(FLAGS.train_dir, "lm.ckpt.epoch" + str(epoch))
self.saver.save(session, checkpoint_path, global_step=self.global_step)
train_perplexity_summary = tf.Summary()
valid_perplexity_summary = tf.Summary()
train_perplexity_summary.value.add(tag="train_log_ppx", simple_value=train_log_perplexity)
train_perplexity_summary.value.add(tag="train_ppx", simple_value=train_perplexity)
summary_writer.add_summary(train_perplexity_summary, nglobal_steps)
valid_perplexity_summary.value.add(tag="valid_log_ppx", simple_value=validation_log_perplexity)
valid_perplexity_summary.value.add(tag="valid_ppx", simple_value=validation_perplexity)
summary_writer.add_summary(valid_perplexity_summary, nglobal_steps)
# Convert epoch time in minutes and print info on screen.
epoch_time = (time.time() - epoch_start_time) * 1.0 / 60
print("END EPOCH %d global_steps %d learning_rate %.4f time(mins) %.4f train_perplexity %.2f valid_perplexity %.2f" %
(epoch, nglobal_steps, new_learning_rate, epoch_time, train_perplexity, validation_perplexity))
sys.stdout.flush()
if exit_criteria.max_epochs is not None and epoch > exit_criteria.max_epochs:
raise StopTrainingException()
# Decrease learning rate if valid ppx does not decrease
if len(previous_valid_log_ppx) > 1 and validation_log_perplexity >= previous_valid_log_ppx[-1]:
new_learning_rate = new_learning_rate * config.lr_decay
# If validation perplexity has not improved over the last 5 epochs, stop training
if new_learning_rate == 0.0 or (len(previous_valid_log_ppx) > 4 and validation_log_perplexity > max(previous_valid_log_ppx[-5:])):
raise StopTrainingException()
previous_valid_log_ppx.append(validation_log_perplexity)
epoch += 1
except (StopTrainingException, KeyboardInterrupt):
print("Finished training ........")
def test(self, session, config, test_data, ignore_padding=False):
"""
Tests the NLM with the specified configuration and test data.
:param session: The TF session in which operations should be run.
:param config: The configuration to be used for the model.
:param test_data:
:param ignore_padding:
:return:
"""
log_perp_unnorm, total_size = 0.0, 0.0
batch_number = -1
state = session.run(self.reset_state)
for step, (context, target, target_weights, sub_target_weights) in enumerate(
test_data.batch_producer(self.batch_size, self.num_steps, True)):
batch_number += 1
feed_dict = {
self.inputd: context,
self.targets: target,
self.target_weights: target_weights,
self.keep_probability: 1.0 # No dropout should be used for the test!
}
if FLAGS.gru:
for i, h in enumerate(self.reset_state):
feed_dict[h] = state[i]
else:
for i, (c, h) in enumerate(self.reset_state):
feed_dict[c] = state[i].c
feed_dict[h] = state[i].h
# norm_logits, loss, cost, state = session.run([self.norm_logits, self.loss, self.cost, self.next_state], feed_dict)
loss, cost, state = session.run([self.loss, self.cost, self.next_state], feed_dict)
if FLAGS.token_model:
targets = [t for tar in target for t in tar]
voc_size = 10500000
loss = [-math.log(1.0/voc_size, 2) if t == self.train_vocab["-UNK-"] else l
for l,t in zip(loss, targets) ]
log_perp_unnorm += np.sum(loss)
if FLAGS.word_level_perplexity:
total_size += np.sum(sum(sub_target_weights))
else:
total_size += np.sum(sum(target_weights))
if ignore_padding:
paddings = 0
for tok_loss, weight in zip(loss, chain.from_iterable(zip(*target_weights))):
if weight == 0:
log_perp_unnorm -= tok_loss
paddings += 1
total_size += 1e-12
log_ppx = log_perp_unnorm / total_size
ppx = math.exp(float(log_ppx)) if log_ppx < 300 else float("inf")
if FLAGS.cross_entropy:
return log_ppx
return ppx
def dynamic_train_test_file(self, test_lines, train_vocab, train_vocab_rev, test_projects, config, output_path, session):
"""
Tests the NLM on the specified test dataset but also updates its parameters by training on each file
after computing its per token entropy.
The model is restored back to the global model after testing has been completed for a project.
This procedure adapts the model to each project resulting in better performance but also prevents the model from
forgetting information contained in the global model after testing on a plethora of projects.
The per token entropy/perplexity will be calculated and shown on the screen.
This mode should always be run with batch_size=1.
:param test_lines:
:param train_vocab: The word to id mapping.
:param train_vocab_rev: The id to word mapping.
:param test_projects: Names of the projects for each test file instance.
:param config: The configuration to be used for the model.
:param output_path:
:param session: The TF session in which operations should be run.
:return: Average loss per file and not per token.
"""
config.batch_size = 1
ctr = 0
nglobal_steps = 0
state = None
new_learning_rate = config.learning_rate
losses = []
lengths = []
last_test_project = None
for test_line, test_project in zip(test_lines, test_projects):
ctr += 1
if test_project != last_test_project and last_test_project is not None:
# New test project so restore the model back to the global one.
ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir)
if ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path):
self.saver.restore(session, ckpt.model_checkpoint_path)
last_test_project = test_project
# Get the ids for this test instance and calculate entropy/perplexity.
test_line = test_line.replace("\n", (" %s" % "-eod-"))
ids = [train_vocab[word] if word in train_vocab else train_vocab['-UNK-'] for word in test_line.split(' ')]
test_dataset = reader.dataset(ids, train_vocab, train_vocab_rev)
test_loss = self.test(session, config, test_dataset, True)
if FLAGS.cross_entropy:
print('line cross_entropy:', test_loss)
else:
print('line perplexity:', test_loss)
sys.stdout.flush()
losses.append(test_loss)
# Train.
state = session.run(self.reset_state)
try:
epoch_log_perp_unnorm = epoch_total_weights = 0.0
epoch_sub_total_weights = 0.0
# Train on each batch to adapt the model to the new information available.
for step, (context, target, target_weights, sub_target_weights) in enumerate(
test_dataset.batch_producer(self.batch_size, self.num_steps)):
feed_dict = {self.inputd: context,
self.targets: target,
self.target_weights: target_weights,
self.learning_rate: new_learning_rate,
self.keep_probability: config.keep_prob
}
if FLAGS.gru:
for i, h in enumerate(self.reset_state):
feed_dict[h] = state[i]
else: # LSTM
for i, (c, h) in enumerate(self.reset_state):
feed_dict[c] = state[i].c
feed_dict[h] = state[i].h
_, cost, state, loss, iteration = session.run([self.train_step, self.cost, self.next_state, self.loss, self.iteration], feed_dict)
nglobal_steps += 1
epoch_log_perp_unnorm += np.sum(loss)
epoch_total_weights += np.sum(sum(target_weights))
epoch_sub_total_weights += np.sum(sum(sub_target_weights))
train_log_perplexity = epoch_log_perp_unnorm / epoch_total_weights
train_perplexity = math.exp(train_log_perplexity) if train_log_perplexity < 300 else float("inf")
print(train_perplexity)
lengths.append(int(round(epoch_sub_total_weights, 0)))
except (StopTrainingException, KeyboardInterrupt):
print("Finished training ........")
total_len = float(sum(lengths))
len_weights = [length / total_len for length in lengths]
if FLAGS.cross_entropy:
print('Per token entropy:', sum([perp * weight for perp, weight in zip(losses, len_weights)]))
else:
print('Per token perplexity:', sum([perp * weight for perp, weight in zip(losses, len_weights)]))
return sum(losses)/ctr
def dynamic_train_test(self, test_lines, train_vocab, train_vocab_rev, test_projects, config, output_path, session):
"""
Tests the NLM on the specified test dataset but also updates its parameters by training on each batch
after computing its per token entropy first.
The model is restored back to the global model after testing has been completed for a project.
This procedure adapts the model to each project resulting in better performance but also prevents the model from
forgetting information contained in the global model after testing on a plethora of projects.
The per token entropy/perplexity will be calculated and shown on the screen.
This mode should always be run with batch_size=1.
:param test_lines:
:param train_vocab:
:param train_vocab_rev:
:param test_projects:
:param config: The configuration to be used for the model.
:param output_path:
:param session:
:return: Average loss per file and not per token.
"""
config.batch_size = 1
ctr = 0
nglobal_steps = 0
state = None
new_learning_rate = config.learning_rate
losses = []
lengths = []
last_test_project = None
for test_line, test_project in zip(test_lines, test_projects):
ctr += 1
if ctr % 100 == 0:
print("\t %d lines" % ctr)
total_len = float(sum(lengths))
len_weights = [length / total_len for length in lengths]
print('Current per token :', sum([perp * weight for perp, weight in zip(losses, len_weights)]))
print(sum(losses) / ctr)
file_log_perp_unnorm = file_total_weights = 0.0
file_sub_total_weights = 0.0
if test_project != last_test_project and last_test_project is not None:
# New test project so restore the model
ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir)
if ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path):
self.saver.restore(session, ckpt.model_checkpoint_path)
last_test_project = test_project
test_line = test_line.replace("\n", (" %s" % "-eod-"))
ids = [train_vocab[word] if word in train_vocab else train_vocab['-UNK-'] for word in test_line.split(' ')]
test_dataset = reader.dataset(ids, train_vocab, train_vocab_rev)
# Test, Train
state = session.run(self.reset_state)
try:
epoch_log_perp_unnorm = epoch_total_weights = 0.0
epoch_sub_total_weights = 0.0
for step, (context, target, target_weights, sub_target_weights) in enumerate(
test_dataset.batch_producer(self.batch_size, self.num_steps)):
feed_dict = {self.inputd: context,
self.targets: target,
self.target_weights: target_weights,
self.keep_probability: 1.0
}
if FLAGS.gru:
for i, h in enumerate(self.reset_state):
feed_dict[h] = state[i]
else: # LSTM
for i, (c, h) in enumerate(self.reset_state):
feed_dict[c] = state[i].c
feed_dict[h] = state[i].h
loss, cost, state = session.run([self.loss, self.cost, self.next_state], feed_dict)
if FLAGS.token_model:
targets = [t for tar in target for t in tar]
loss = [-math.log(1.0/len(self.train_vocab), 2) if t == self.train_vocab["-UNK-"] else l
for l,t in zip(loss, targets) ]
file_log_perp_unnorm += np.sum(loss)
file_total_weights += np.sum(sum(target_weights))
file_sub_total_weights += np.sum(sum(sub_target_weights))
if True:
for tok_loss, weight in zip(loss, chain.from_iterable(zip(*target_weights))):
if weight == 0:
file_log_perp_unnorm -= tok_loss
feed_dict = {self.inputd: context,
self.targets: target,
self.target_weights: target_weights,
self.learning_rate: new_learning_rate,
self.keep_probability: config.keep_prob
}
if FLAGS.gru:
for i, h in enumerate(self.reset_state):
feed_dict[h] = state[i]
else: # LSTM
for i, (c, h) in enumerate(self.reset_state):
feed_dict[c] = state[i].c
feed_dict[h] = state[i].h
_, cost, state, loss, iteration = session.run([self.train_step, self.cost, self.next_state, self.loss, self.iteration], feed_dict)
nglobal_steps += 1
epoch_log_perp_unnorm += np.sum(loss)
epoch_total_weights += np.sum(sum(target_weights))
epoch_sub_total_weights += np.sum(sum(sub_target_weights))
train_log_perplexity = epoch_log_perp_unnorm / epoch_total_weights
train_perplexity = math.exp(train_log_perplexity) if train_log_perplexity < 300 else float("inf")
print(train_perplexity)
lengths.append(int(round(epoch_sub_total_weights, 0)))
if FLAGS.word_level_perplexity:
test_loss = file_log_perp_unnorm / file_sub_total_weights
else:
test_loss = file_log_perp_unnorm / file_total_weights
if FLAGS.cross_entropy:
print('line cross_entropy:', test_loss)
else:
print('line perplexity:', test_loss)
sys.stdout.flush()
losses.append(test_loss)
except (StopTrainingException, KeyboardInterrupt):
print("Finished training ........")
total_len = float(sum(lengths))
len_weights = [length / total_len for length in lengths]
if FLAGS.cross_entropy:
print('Per token entropy:', sum([perp * weight for perp, weight in zip(losses, len_weights)]))
else:
print('Per token perplexity:', sum([perp * weight for perp, weight in zip(losses, len_weights)]))
return sum(losses)/ctr
def maintenance_test(self, session, config, test_lines, test_projects, train_vocab, train_vocab_rev):
"""
Simulates code maintenance scenario.
For each file in a project the model is first adapted on the rest of the files.
The model is also adapted on encountered sequences of the test file.
The test_projects argument informs the model about which instances belong to which project.
Note: Always use batch_size=1. RNN num_steps=20 is a good value.
:param session: The TF session in which operations will be run.
:param config: The configuration to be used for the model.
:param test_lines: A list containing each test instance as a separate entry. Instances from the same project should be consecutive.
:param test_projects: To which project does each instance belong to. Should be a list of strings.
:param train_vocab: The word to id mapping.
:param train_vocab_rev: The id to word mapping.
:return:
"""
# If checkpoint does not exist throw an exception. A global model must have been pretrained.
ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir)
if not tf.train.checkpoint_exists(ckpt.model_checkpoint_path):
raise Exception('Checkpoint does not exist!')
# Some initializations.
new_learning_rate = config.learning_rate
test_losses = []
test_losses_sum = 0.0
lengths = []
ctr = 0
# First compute which files belong in each project.
project_sizes = []
last_project_name = ''
project_file_size = 0
for test_project in test_projects:
if test_project != last_project_name:
if last_project_name != '':
project_sizes.append(project_file_size)
project_file_size = 0
else:
project_file_size += 1
last_project_name = test_project
print(project_sizes)
print(sum(project_sizes))
print()
# Now distribute test lines based on project size.
project_test_lines = []
files_distributed = 0
for project_file_size in project_sizes:
project_test_lines.append(test_lines[files_distributed : files_distributed + project_file_size])
files_distributed += project_file_size
partitions = 20 # Default number of partitions
for proj_id, test_lines in enumerate(project_test_lines):
print(len(test_lines))
large_project = len(test_lines) > 200
if len(test_lines) > 2000: # Really big projects can have speed benefits from more partitions.
partitions = 50
else:
partitions = 20
if large_project:
# The project is very large so partition it in partition_size parts.
# For each of the 20/50 parts train a model on all the parts excluding itself.
partition_size = len(test_lines) / partitions
for partition in range(partitions):
partition_words = []
for i, line in enumerate(test_lines):
if i / partition_size != partition and not (i / partition_size == partitions + 1 and partition == partitions):
partition_words.extend([word for word in line.split(' ')])
# If checkpoint does not exist throw an exception. A global model should have been trained...
ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir)
if not tf.train.checkpoint_exists(ckpt.model_checkpoint_path):
raise Exception('Checkpoint for global model does not exist!')
self.saver.restore(session, ckpt.model_checkpoint_path)
# Where to save this partition.
partition_path = os.path.join(FLAGS.train_dir, "partition%d" % partition)
if os.path.isdir(partition_path): shutil.rmtree(partition_path)
partition_ids = [train_vocab[word] if word in train_vocab else train_vocab['-UNK-'] for word in partition_words]
partition_dataset = reader.dataset(partition_ids, train_vocab, train_vocab_rev)
# Reset the LSTM state to zeros and train
state = session.run(self.reset_state)
try:
epoch_log_perp_unnorm = epoch_total_weights = 0.0
epoch_sub_total_weights = 0.0
for step, (context, target, target_weights, sub_target_weights) in enumerate(
partition_dataset.batch_producer(self.batch_size, self.num_steps)):
feed_dict = {self.inputd: context,
self.targets: target,
self.target_weights: target_weights,
self.learning_rate: new_learning_rate,
self.keep_probability: config.keep_prob
}
if FLAGS.gru:
for i, h in enumerate(self.reset_state):
feed_dict[h] = state[i]
else:
for i, (c, h) in enumerate(self.reset_state):
feed_dict[c] = state[i].c
feed_dict[h] = state[i].h
_, cost, state, loss, iteration = session.run(
[self.train_step, self.cost, self.next_state, self.loss, self.iteration], feed_dict)
epoch_log_perp_unnorm += np.sum(loss)
epoch_total_weights += np.sum(sum(target_weights))
epoch_sub_total_weights += np.sum(sum(sub_target_weights))
train_log_perplexity = epoch_log_perp_unnorm / epoch_total_weights
train_perplexity = math.exp(train_log_perplexity) if train_log_perplexity < 300 else float("inf")
print(train_perplexity)
checkpoint_path = os.path.join(partition_path, "model")
self.saver.save(session, checkpoint_path, global_step=self.global_step)
except (StopTrainingException, KeyboardInterrupt):
print("Finished training ........")
for lines_done, test_line in enumerate(test_lines):
ctr += 1
# Restore the global model
ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir)
if ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path):
self.saver.restore(session, ckpt.model_checkpoint_path)
if large_project:
# Load pretrained model and only train on the rest of the files from this partition
partition = lines_done / partition_size
partition = min(partitions - 1, partition) # last partition can be bigger
partition_path = os.path.join(FLAGS.train_dir, "partition%d" % partition)
part_ckpt = tf.train.get_checkpoint_state(partition_path)
self.saver.restore(session, part_ckpt.model_checkpoint_path)
train_words = []
if partition < partitions - 1:
partition_lines = zip(range(partition * partition_size, (partition + 1) * partition_size),
test_lines[partition * partition_size : (partition + 1) * partition_size])
else:
partition_lines = zip(range(partition * partition_size, len(test_lines)),
test_lines[partition * partition_size : (partition + 1) * partition_size])
for i, line in partition_lines:
if i != (lines_done % partition_size):
train_words.extend([word for word in line.split(' ')])
else:
# Now for each file in the current test project use the rest as train data
train_words = []
for i, line in enumerate(test_lines):
if i != lines_done:
train_words.extend([word for word in line.split(' ')])
# Convert the train data words to ids
ids = [train_vocab[word] if word in train_vocab else train_vocab['-UNK-'] for word in train_words]
train_dataset = reader.dataset(ids, train_vocab, train_vocab_rev)
# Reset the LSTM state to zeros and train
state = session.run(self.reset_state)
try:
epoch_log_perp_unnorm = epoch_total_weights = 0.0
epoch_sub_total_weights = 0.0
for step, (context, target, target_weights, sub_target_weights) in enumerate(
train_dataset.batch_producer(self.batch_size, self.num_steps)):
feed_dict = {self.inputd: context,
self.targets: target,
self.target_weights: target_weights,
self.learning_rate: new_learning_rate,
self.keep_probability: config.keep_prob
}
if FLAGS.gru:
for i, h in enumerate(self.reset_state):
feed_dict[h] = state[i]
else:
for i, (c, h) in enumerate(self.reset_state):
feed_dict[c] = state[i].c
feed_dict[h] = state[i].h
# print("state number " + str(i))
_, cost, state, loss, iteration = session.run([self.train_step, self.cost, self.next_state, self.loss, self.iteration], feed_dict)
epoch_log_perp_unnorm += np.sum(loss)
epoch_total_weights += np.sum(sum(target_weights))
epoch_sub_total_weights += np.sum(sum(sub_target_weights))
train_log_perplexity = epoch_log_perp_unnorm / epoch_total_weights
train_perplexity = math.exp(train_log_perplexity) if train_log_perplexity < 300 else float("inf")
# lengths.append(int(round(epoch_sub_total_weights, 0)))
# Training done. Now test on test file
ids = [train_vocab[word] if word in train_vocab else train_vocab['-UNK-']
for word in test_lines[lines_done].split(' ')]
# Test on each sequence of tokens and then train on it until the file is done
subtokens_done = 0
tokens_done = 0
instance_losses = []
# Reset the LSTM state to zeros and train
state = session.run(self.reset_state)
test_state = session.run(self.reset_state)
while subtokens_done + config.num_steps < len(ids):
step_end = subtokens_done + config.num_steps
unfinished_token = train_vocab_rev[ids[step_end]].endswith('@@')
while unfinished_token:
step_end += 1
unfinished_token = train_vocab_rev[ids[step_end]].endswith('@@')
try:
context = ids[subtokens_done : step_end]
target = ids[subtokens_done + 1 : step_end + 1]
target_weights = [1] * len(context)
for id in context:
if not train_vocab_rev[id].endswith('@@'):
tokens_done += 1
feed_dict = {self.inputd: np.tile(context, (self.batch_size, 1)),
self.targets: np.tile(target, (self.batch_size, 1)),
self.target_weights: np.tile(target_weights, (self.batch_size, 1)),
self.keep_probability: 1.0
}
if FLAGS.gru:
for i, h in enumerate(self.reset_state):
feed_dict[h] = test_state[i]
else:
for i, (c, h) in enumerate(self.reset_state):
feed_dict[c] = test_state[i].c
feed_dict[h] = test_state[i].h
cost, test_state, loss = session.run([self.cost, self.next_state, self.loss], feed_dict)
if tokens_done > 0:
instance_losses.append((tokens_done, len(context), sum(loss)/tokens_done))
feed_dict = {self.inputd: np.tile(context, (self.batch_size, 1)),
self.targets: np.tile(target, (self.batch_size, 1)),
self.target_weights: np.tile(target_weights, (self.batch_size, 1)),
self.learning_rate: new_learning_rate,
self.keep_probability: config.keep_prob
}
if FLAGS.gru:
for i, h in enumerate(self.reset_state):
feed_dict[h] = state[i]
else: # LSTM
for i, (c, h) in enumerate(self.reset_state):
feed_dict[c] = state[i].c
feed_dict[h] = state[i].h
_, cost, state, loss, iteration = session.run(
[self.train_step, self.cost, self.next_state, self.loss, self.iteration], feed_dict)
except (StopTrainingException, KeyboardInterrupt):
print("Finished training ........")
subtokens_done = step_end
# Test and train on leftover part of the sequence, which has length < step_size.
try:
tokens_done = 0
context = ids[subtokens_done:-1]
target = ids[subtokens_done + 1:]
target_weights = [1] * len(context)
if len(context) == 0 or len(target) == 0: # if there are no actual leftovers stop.
continue
for id in context:
if not train_vocab_rev[id].endswith('@@'):
tokens_done += 1
feed_dict = {self.inputd: np.tile(context, (self.batch_size, 1)),
self.targets: np.tile(target, (self.batch_size, 1)),
self.target_weights: np.tile(target_weights, (self.batch_size, 1)),
self.keep_probability: 1.0
}
if FLAGS.gru:
for i, h in enumerate(self.reset_state):
feed_dict[h] = test_state[i]
else:
for i, (c, h) in enumerate(self.reset_state):
feed_dict[c] = test_state[i].c
feed_dict[h] = test_state[i].h
cost, test_state, loss = session.run([self.cost, self.next_state, self.loss], feed_dict)
if tokens_done > 0:
instance_losses.append((tokens_done, len(context), sum(loss)/tokens_done))
feed_dict = {self.inputd: np.tile(context, (self.batch_size, 1)),
self.targets: np.tile(target, (self.batch_size, 1)),
self.target_weights: np.tile(target_weights, (self.batch_size, 1)),
self.learning_rate: new_learning_rate,
self.keep_probability: config.keep_prob
}
if FLAGS.gru:
for i, h in enumerate(self.reset_state):
feed_dict[h] = state[i]
else: # LSTM
for i, (c, h) in enumerate(self.reset_state):
feed_dict[c] = state[i].c
feed_dict[h] = state[i].h
# print("state number " + str(i))
_, cost, state, loss, iteration = session.run(
[self.train_step, self.cost, self.next_state, self.loss, self.iteration], feed_dict)
except (StopTrainingException, KeyboardInterrupt):
print("Finished training ........")
tokens_done = float(sum([toks for toks, _, _ in instance_losses]))
lengths.append(tokens_done)
weighted_losses = [loss * toks / tokens_done for toks, _, loss in instance_losses]
test_loss = sum(weighted_losses)
test_losses_sum += test_loss
print('line cross_entropy:', test_loss, '--- current average:', test_losses_sum / ctr)
# if FLAGS.cross_entropy:
# print('line cross_entropy:', test_loss, '--- current average:', test_losses_sum / ctr)
# else:
# print('line perplexity:', test_loss)
sys.stdout.flush()
test_losses.append(test_loss)
except (StopTrainingException, KeyboardInterrupt):
print("Finished training ........")
print("Projects Done:", proj_id + 1)
total_len = float(sum(lengths))
len_weights = [length / total_len for length in lengths]
print('Is it correct perplexity:', sum([perp * weight for perp, weight in zip(test_losses, len_weights)]))
return test_losses_sum / ctr
def completion(self, session, config, test_dataset, test_projects, beam_size, dynamic=False, id_map=None, cache_ids=False, token_map=None):
"""
Runs code the code completion scenario. Dynamic update can be performed but by default is turned off.
:param session: The TF session in which operations should be run.
:param config: The configuration to be used for the model.
:param test_dataset:
:param test_projects: To which project does each instance belong to. Should be a list of strings.
:param beam_size: The size of the beam to be used by the search algorithm.
:param dynamic: Whether dynamic adaptation should be performed.
:return:
"""
mrr = 0.0
id_mrr = 0.0
id_acc1 = 0.0
id_acc3 = 0.0
id_acc5 = 0.0
id_acc10 = 0.0
ids_in_cache = 0.0
ids_in_project_cache = 0.0
context_history_in_ngram_cache = 0.0
context_history_in_ngram_project_cache = 0.0
satisfaction_prob = 0.8
top_needed = 10
verbose = FLAGS.verbose
last_test_project = None
train_every = config.num_steps
tokens_done = 0
files_done = 0
identifiers = 0
file_identifiers = 0
state = session.run(self.reset_state)
context_size = FLAGS.cache_order - 1
context_history = deque([None] * context_size, context_size)
ngram_cache = dict()
ngram_project_cache = dict()
# project_context_history = []
id_cache = trie.CharTrie()
project_id_cache = trie.CharTrie()
CACHE_WEIGHT = FLAGS.file_cache_weight
PROJECT_CACHE_WEIGHT = FLAGS.file_cache_weight * 0.5
SKIP_CACHE_PROB_THRESHOLD = 0.0
raw_data = test_dataset.data # is just one long array
data_len = len(raw_data)
print('Data Length:', data_len)
data_covered = 0
end_file_id = test_dataset.vocab["-eod-"]
start_index = 0
file_start_index = 0
while data_covered < data_len:
# Stop when 1000000 test tokens have been scored.
if tokens_done > 1000000:
break
# Create minibatches for the next file
while raw_data[data_covered] != end_file_id:
data_covered += 1
data_covered += 1 # eod symbol
file_identifiers = 0
# Reset identifier cache for each file.
if cache_ids:
id_cache.clear()
ids_in_cache = 0.0
ids_in_project_cache = 0.0
context_history = deque([None] * context_size, context_size)