forked from cupslab/neural_network_cracking
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pwd_guess.py
2585 lines (2236 loc) · 97.7 KB
/
pwd_guess.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
# -*- coding: utf-8 -*-
# author: William Melicher
from __future__ import print_function
import argparse
import bisect
import cProfile
import collections
import csv
import gzip
import itertools
import json
import logging
import math
import os
import os.path
import random
import re
import string
import subprocess as subp
import sys
import tempfile
import time
# This is a hack to support multiple versions of the keras library.
# It would be better to use a solution like virtualenv.
if 'KERAS_PATH' in os.environ:
sys.path.insert(0, os.environ['KERAS_PATH'])
import keras
try:
sys.stderr.write('Using keras version %s\n' % (keras.__version__))
except AttributeError:
pass
from keras.models import Sequential, model_from_json
from keras.layers.core import Activation, Dense, Dropout
from keras.layers import TimeDistributed, Flatten, Conv1D, recurrent, Embedding
import keras.utils
from keras.callbacks import TensorBoard
from sklearn.utils import shuffle
import numpy as np
import tensorflow as tf
from enum import IntEnum
import pylru
import generator
PASSWORD_END = '\n'
PASSWORD_START = '\t'
SYMBOLS = '~!@#$%^&*(),.<>/?\'"{}[]\\|-_=+;: `'
FNAME_PREFIX_SUBPROCESS_CONFIG = 'child_process.'
FNAME_PREFIX_PROCESS_LOG = 'log.child_process.'
FNAME_PREFIX_PROCESS_OUT = 'out.child_process.'
MEMORY_ONLY = ':memory:'
class Sequence(IntEnum):
MANY_TO_ONE = 0
many_to_one = 0
MANY_TO_MANY = 1
many_to_many = 1
# From: https://docs.python.org/3.4/library/itertools.html
def grouper(iterable, num, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * num
return map(lambda x: filter(lambda y: y, x),
# pylint: disable=E1101
itertools.zip_longest(*args, fillvalue=fillvalue))
class CharacterTable():
def __init__(self, chars, maxlen, embedding=False, padding_character=False,
sequence_model=Sequence.MANY_TO_ONE):
self.chars = sorted(set(chars))
self.char_indices = dict((c, i) for i, c in enumerate(self.chars))
self.indices_char = dict((i, c) for i, c in enumerate(self.chars))
self.maxlen = maxlen
self.vocab_size = len(self.chars)
self.char_list = self.chars
self.padding_character = padding_character
self.embedding = embedding
self.sequence_model = sequence_model
def pad_to_len(self, astring, maxlen=None):
maxlen = maxlen if maxlen else self.maxlen
if len(astring) > maxlen:
return astring[len(astring) - maxlen:]
if self.padding_character:
return astring + (PASSWORD_END * (maxlen - len(astring)))
return astring
def encode_many(self, string_list, maxlen=None, y_vec=False):
maxlen = maxlen if maxlen else self.maxlen
x_str_list = map(lambda x: self.pad_to_len(x, maxlen), string_list)
if self.embedding and not y_vec:
x_vec = np.zeros(shape=(len(string_list), maxlen), dtype=np.int8)
else:
x_vec = np.zeros((len(string_list), maxlen, self.vocab_size),
dtype=np.bool)
for i, xstr in enumerate(x_str_list):
self.encode_into(x_vec[i], xstr)
return x_vec
def encode_many_chunks(self, string_list, max_input_str_len, maxlen=None, y_vec=False):
maxlen = maxlen if maxlen else self.maxlen
chunks_str_list = []
iters = list(range(maxlen, max_input_str_len, maxlen // 2))
iters.append(max_input_str_len)
for a_string in string_list:
prev_iter = 0
for i in iters:
if prev_iter >= len(a_string) and (len(a_string) != 0) or\
(len(a_string) == 0 and prev_iter != 0):
break
chunk = a_string[i-maxlen:i]
chunks_str_list.append(chunk)
prev_iter = i
return self.encode_many(chunks_str_list, maxlen, y_vec=y_vec), chunks_str_list
def y_encode_into(self, Y, C):
for i, c in enumerate(C):
Y[i, self.char_indices[c]] = 1
def encode_into(self, X, C):
for i, c in enumerate(C):
if len(X.shape) == 1:
X[i] = self.char_indices[c]
elif len(X.shape) == 2:
X[i, self.char_indices[c]] = 1
else:
raise Exception("Code should never reach here, dimension of X can only be 1 or 2")
def encode(self, C, maxlen=None):
maxlen = maxlen if maxlen else self.maxlen
if self.embedding:
X = np.zeros((maxlen), dtype=np.int8)
else:
X = np.zeros((maxlen, len(self.chars)))
self.encode_into(X, C)
return X
def get_char_index(self, character):
return self.char_indices[character]
def translate(self, astring):
return astring
@staticmethod
def fromConfig(config):
if (config.uppercase_character_optimization or
config.rare_character_optimization):
return OptimizingCharacterTable(
config.char_bag, config.context_length,
config.get_intermediate_info('rare_character_bag'),
config.uppercase_character_optimization,
padding_character=config.padding_character,
embedding=config.embedding_layer)
return CharacterTable(config.char_bag, config.context_length,
padding_character=config.padding_character,
embedding=config.embedding_layer,
sequence_model=config.sequence_model)
class OptimizingCharacterTable(CharacterTable):
def __init__(self, chars, maxlen, rare_characters, uppercase,
embedding=False, padding_character=None):
# pylint: disable=too-many-branches
if uppercase:
self.rare_characters = ''.join(
c for c in rare_characters if (
c not in string.ascii_uppercase
and c not in string.ascii_lowercase))
else:
self.rare_characters = rare_characters
char_bag = chars
for r in self.rare_characters:
char_bag = char_bag.replace(r, '')
if len(rare_characters):
char_bag += self.rare_characters[0]
self.rare_dict = {
char : self.rare_characters[0] for char in self.rare_characters}
self.rare_character_preimage = {
self.rare_characters[0] : list(self.rare_characters)}
else:
self.rare_character_preimage = {}
self.rare_dict = {}
if uppercase:
for c in string.ascii_uppercase:
if c not in chars:
continue
self.rare_dict[c] = c.lower()
char_bag = char_bag.replace(c, '')
if c.lower() not in char_bag:
raise ValueError(
"expected %s to be in %s" % (c.lower(), chars))
self.rare_character_preimage[c.lower()] = [c, c.lower()]
super().__init__(char_bag, maxlen, embedding, padding_character)
for key in self.rare_dict:
self.char_indices[key] = self.char_indices[self.rare_dict[key]]
translate_table = {}
for c in chars:
if c in self.rare_dict:
translate_table[c] = self.rare_dict[c]
else:
translate_table[c] = c
# pylint: disable=no-member
#
# maketrans is a member of the string class
self.translate_table = ''.maketrans(translate_table)
self.rare_character_postimage = {}
for key in self.rare_character_preimage:
for item in self.rare_character_preimage[key]:
self.rare_character_postimage[item] = key
def translate(self, astring):
return astring.translate(self.translate_table)
class ModelSerializer():
def __init__(self,
archfile=None,
weightfile=None,
versioned=False,
multi_gpu=1):
self.archfile = archfile
self.weightfile = weightfile
self.model_creator_from_json = model_from_json
self.versioned = versioned
self.saved_counter = 0
self.multi_gpu = multi_gpu
def save_model(self, model):
if self.archfile is None or self.weightfile is None:
logging.info(
'Cannot save model because file arguments were not provided')
return
logging.info('Saving model architecture')
with open(self.archfile, 'w') as arch:
arch.write(model.to_json())
logging.info('Saving model weights')
self.saved_counter += 1
weight_fname = self.weightfile
if self.versioned:
weight_fname += '.' + str(self.saved_counter)
model.save_weights(weight_fname, overwrite=True)
logging.info('Done saving model')
def load_model(self):
logging.info('Loading model architecture')
with open(self.archfile, 'r') as arch:
arch_data = arch.read()
model = self.model_creator_from_json(arch_data)
logging.info('Loading model weights')
model.load_weights(self.weightfile)
logging.info('Done loading model')
if self.multi_gpu > 1:
model = keras.utils.multi_gpu_model(model, gpus=self.multi_gpu)
return model
class ConfigurationException(Exception):
pass
def read_config_file(afile):
_, fileext = os.path.splitext(afile)
if fileext == '.json':
file_format = json.load
elif fileext == '.yaml':
try:
import yaml
except ImportError:
logging.error(
'python yaml library is required for yaml configs. '
'Run: pip install yaml')
raise
file_format = yaml.safe_load
else:
logging.warning(
'Unknown config format: %s. Defaulting to JSON', fileext)
file_format = json.load
with open(afile, 'r') as f:
answer = file_format(f)
return answer
class ModelDefaults():
char_bag = (
string.ascii_lowercase + string.ascii_uppercase + string.digits +
SYMBOLS + PASSWORD_END)
model_type = 'LSTM'
sequence_model = Sequence.MANY_TO_ONE
hidden_size = 128
layers = 1
max_len = 40
min_len = 4
training_chunk = 128
generations = 20
chunk_print_interval = 1000
lower_probability_threshold = 10**-5
relevel_not_matching_passwords = True
training_accuracy_threshold = -1.0
train_test_ratio = 10
rare_character_optimization = False
rare_character_optimization_guessing = False
uppercase_character_optimization = False
rare_character_lowest_threshold = 20
guess_serialization_method = 'human'
simulated_frequency_optimization = False
intermediate_fname = MEMORY_ONLY
save_always = True
save_model_versioned = False
randomize_training_order = True
model_optimizer = 'adam'
guesser_intermediate_directory = 'guesser_files'
cleanup_guesser_files = True
early_stopping = False
early_stopping_patience = 10000
compute_stats = False
password_test_fname = ""
chunk_size_guesser = 1000
random_walk_seed_num = 1000
max_gpu_prediction_size = 25000
cpu_limit = 8
random_walk_confidence_bound_z_value = 1.96
random_walk_confidence_percent = 5
random_walk_upper_bound = 10
no_end_word_cache = False
enforced_policy = 'basic'
pwd_list_weights = {}
dropouts = False
dropout_ratio = .25
tensorboard = False
tensorboard_dir = "."
context_length = None
train_backwards = False
dense_layers = 0
dense_hidden_size = 128
secondary_training = False
secondary_train_sets = {}
training_main_memory_chunksize = 1000000
probability_steps = False
freeze_feature_layers_during_secondary_training = True
secondary_training_save_freqs = False
guessing_secondary_training = False
guesser_class = None
freq_format = 'hex'
padding_character = False
convolutional_kernel_size = 3
embedding_layer = False
embedding_size = 8
previous_probability_mapping_file = None
probability_calculator_cache_size = 0
def __init__(self, adict=None, **kwargs):
self.adict = adict if adict is not None else dict()
for k in kwargs:
self.adict[k] = kwargs[k]
if self.context_length is None:
self.context_length = self.max_len
if isinstance(self.sequence_model, str):
self.sequence_model = Sequence[self.sequence_model]
self._read_intermediate_data_time = None
self._intermediate_data = self._read_intermediate_data()
def _read_intermediate_data(self):
self._read_intermediate_data_time = time.time()
if self.intermediate_fname == MEMORY_ONLY:
return {}
if not os.path.exists(self.intermediate_fname):
return {}
with open(self.intermediate_fname, 'r') as info:
info_as_str = info.read()
if not info_as_str:
return {}
return json.loads(info_as_str)
def _write_intermediate_data(self):
if self.intermediate_fname == MEMORY_ONLY:
return
self._read_intermediate_data_time = time.time()
with open(self.intermediate_fname, 'w') as info:
json.dump(self._intermediate_data, info)
def _check_if_should_reload(self):
if self.intermediate_fname == MEMORY_ONLY:
return
if not os.path.exists(self.intermediate_fname):
return
mod_time = os.path.getmtime(self.intermediate_fname)
assert self._read_intermediate_data_time is not None
if mod_time >= self._read_intermediate_data_time:
self._intermediate_data = self._read_intermediate_data()
def __getattribute__(self, name):
if name != 'adict' and name in self.adict:
return self.adict[name]
return super().__getattribute__(name)
def __setattr__(self, name, value):
if name != 'adict' and not name.startswith("_"):
self.adict[name] = value
else:
super().__setattr__(name, value)
@staticmethod
def fromFile(afile):
if afile is None:
return ModelDefaults()
return ModelDefaults(read_config_file(afile))
def validate(self):
if self.max_len > 255:
raise ConfigurationException('expected max_len <= 255')
if self.password_test_fname:
if not os.path.exists(self.password_test_fname):
raise ConfigurationException(
'password_test_fname with value "%s" does not exist' %
self.password_test_fname)
if self.rare_character_optimization_guessing:
if not (self.rare_character_optimization or
self.uppercase_character_optimization):
raise ConfigurationException(
'rare_character_optimization_guessing should not be true '
'when neither uppercase_character_optimization or '
'uppercase_character_optimization are true')
elif (self.rare_character_optimization or
self.uppercase_character_optimization):
logging.warning(
'Without rare_character_optimization_guessing setting,'
' output guesses may ignore case or special characters')
if self.embedding_layer:
if not self.embedding_size:
raise ConfigurationException(
'Expected embedding_size when using embedding_layer=True')
if self.guess_serialization_method not in serializer_type_list:
raise ConfigurationException(
'unknown guess_serialization_method: %s' %
self.guess_serialization_method)
if self.context_length > self.max_len:
raise ConfigurationException('Expected context_length <= max_len')
if self.training_main_memory_chunksize <= self.training_chunk:
raise ConfigurationException(
'Expected training_main_memory_chunksize > training_chunk')
if self.guessing_secondary_training:
if ((not self.secondary_training) or
(not self.secondary_training_save_freqs)):
raise ConfigurationException(
'Expected secondary_training and secondary_training_save_freqs')
if self.sequence_model != Sequence.MANY_TO_MANY and\
self.sequence_model != Sequence.MANY_TO_ONE:
raise ConfigurationException(
"Configuration parameter 'sequence_model' can only be "
"'many_to_many' or 'many_to_one'")
def as_dict(self):
answer = dict(vars(ModelDefaults).copy())
answer.update(self.adict)
return {
key: value for key, value in answer.items() if (
key[0] != '_' and not hasattr(value, '__call__')
and not isinstance(value, staticmethod))}
def set_intermediate_info(self, key, value):
self._intermediate_data[key] = value
self._write_intermediate_data()
def get_intermediate_info(self, key):
self._check_if_should_reload()
try:
return self._intermediate_data[key]
except KeyError as e:
logging.error('Cannot find intermediate data %s. Looking in %s',
str(e), self.intermediate_fname)
raise
def override_from_commandline(self, cmdline):
answer = {}
for keyval in cmdline.split(';'):
if not keyval:
continue
key, _, value = keyval.partition('=')
answer[key] = type(getattr(self, key))(value)
self.adict.update(answer)
def sequence_model_updates(self):
if self.sequence_model == Sequence.MANY_TO_MANY:
self.char_bag += PASSWORD_START
class BasePreprocessor():
def __init__(self, config=ModelDefaults()):
self.config = config
def begin(self, pwd_list):
raise NotImplementedError()
def begin_resetable(self, resetable):
self.begin(resetable.create_new())
def next_chunk(self):
raise NotImplementedError()
def reset(self):
raise NotImplementedError()
def stats(self):
self.reset()
x_vec, _, _ = self.next_chunk()
count_instances = 0
while len(x_vec) != 0:
count_instances += len(x_vec)
x_vec, _, _ = self.next_chunk()
logging.info('Number of training instances %s', count_instances)
return count_instances
@staticmethod
def fromConfig(config):
if config.sequence_model == Sequence.MANY_TO_MANY:
return ManyToManyPreprocessor(config)
if config.sequence_model == Sequence.MANY_TO_ONE:
return Preprocessor(config)
raise ValueError('unknown sequence model: %s' % config.sequence_model)
class Preprocessor(BasePreprocessor):
def __init__(self, config=ModelDefaults()):
super().__init__(config)
self.chunk = 0
self.resetable_pwd_list = None
self.pwd_whole_list = None
self.pwd_freqs = None
self.chunked_pwd_list = None
def begin(self, pwd_list):
self.pwd_whole_list = list(pwd_list)
def begin_resetable(self, resetable):
self.resetable_pwd_list = resetable
self.reset()
def all_prefixes(self, pwd):
return [pwd[:i] for i in range(len(pwd))] + [pwd]
def all_suffixes(self, pwd):
return [pwd[i] for i in range(len(pwd))] + [PASSWORD_END]
def repeat_weight(self, pwd):
return [self.password_weight(pwd) for _ in range(len(pwd) + 1)]
def train_from_pwds(self, pwd_tuples):
self.pwd_freqs = dict(pwd_tuples)
pwds = list(map(lambda x: x[0], pwd_tuples))
return (itertools.chain.from_iterable(map(self.all_prefixes, pwds)),
itertools.chain.from_iterable(map(self.all_suffixes, pwds)),
itertools.chain.from_iterable(map(self.repeat_weight, pwds)))
def next_chunk(self):
if self.chunk * self.config.training_chunk >= len(self.pwd_whole_list):
if self.resetable_pwd_list is None:
return [], [], []
try:
new_iterator = self.chunked_pwd_list.__next__()
except StopIteration:
return [], [], []
self.begin(new_iterator)
self.reset_subiterator()
return self.next_chunk()
pwd_list = self.pwd_whole_list[
self.chunk * self.config.training_chunk:
min((self.chunk + 1) * self.config.training_chunk,
len(self.pwd_whole_list))]
self.chunk += 1
pwd_input, output, weight = self.train_from_pwds(pwd_list)
return (list(pwd_input), list(output), list(weight))
def password_weight(self, pwd):
if isinstance(pwd, tuple):
pwd = ''.join(pwd)
if pwd in self.pwd_freqs:
return self.pwd_freqs[pwd]
assert False, 'Cannot find frequency for password'
return 0.0
def reset(self):
if self.resetable_pwd_list is None:
self.reset_subiterator()
return
self.chunked_pwd_list = iter(grouper(
self.resetable_pwd_list.as_iterator(),
self.config.training_main_memory_chunksize))
try:
self.begin(self.chunked_pwd_list.__next__())
except StopIteration:
logging.warning('Password list has no passwords?')
self.pwd_whole_list = []
self.reset_subiterator()
def reset_subiterator(self):
self.chunk = 0
if self.config.randomize_training_order:
random.shuffle(self.pwd_whole_list)
class Trainer():
def __init__(self, pwd_list, config=ModelDefaults(), multi_gpu=1):
self.config = config
self.chunk = 0
self.generation = 0
self.model = None
self.model_to_save = None
self.multi_gpu = multi_gpu
self.pwd_list = pwd_list
self.cumulative_chunks = 0
self.min_loss_early_stopping = float("inf")
self.poor_batches_early_stopping = 0
self.smoothened_loss = collections.deque(maxlen=int(config.chunk_print_interval))
if config.tensorboard:
self.callback = TensorBoard(config.tensorboard_dir)
self.train_log_names = []
self.test_log_names = []
else:
self.callback = None
self.train_log_names = None
self.test_log_names = None
self.ctable = CharacterTable.fromConfig(self.config)
self.feature_layers = []
self.classification_layers = []
def next_train_set_as_np(self):
x_strs, y_str_list, weight_list = self.pwd_list.next_chunk()
x_vec = self.prepare_x_data(x_strs)
y_vec = self.prepare_y_data(y_str_list)
weight_vec = np.zeros((len(weight_list)))
for i, weight in enumerate(weight_list):
weight_vec[i] = weight
return shuffle(x_vec, y_vec, weight_vec)
def prepare_x_data(self, x_strs):
return self.ctable.encode_many(x_strs)
def prepare_y_data(self, y_str_list):
y_vec = np.zeros((len(y_str_list), self.ctable.vocab_size),
dtype=np.bool)
self.ctable.y_encode_into(y_vec, y_str_list)
return y_vec
def _make_layer(self, **kwargs):
recurrent_train_backwards = self.config.train_backwards
model_type = self.config.model_type
hidden_size = self.config.hidden_size
if model_type == 'GRU':
return recurrent.GRU(
hidden_size,
return_sequences=True,
go_backwards=recurrent_train_backwards,
**kwargs)
if model_type == 'LSTM':
return recurrent.LSTM(
hidden_size,
return_sequences=True,
go_backwards=recurrent_train_backwards,
**kwargs)
if model_type == 'Conv1D':
return Conv1D(
hidden_size,
self.config.convolutional_kernel_size,
**kwargs)
raise ConfigurationException('Unknown model_type: %s' % model_type)
def _return_model(self):
model = Sequential()
# Add the first input layer. If embedding is enabled, we add a different
# layer which does not have the input_shape defined
if self.config.embedding_layer:
self.feature_layers.append(
Embedding(
self.ctable.vocab_size,
self.config.embedding_size,
input_length=self.config.context_length))
self.feature_layers.append(self._make_layer())
else:
self.feature_layers.append(
self._make_layer(
input_shape=(
self.config.context_length, self.ctable.vocab_size)))
# Add the main model layers. These layers will not be trainable during
# secondary training.
for _ in range(self.config.layers):
if self.config.dropouts:
self.feature_layers.append(Dropout(self.config.dropout_ratio))
self.feature_layers.append(self._make_layer())
self.feature_layers.append(Flatten())
# Add any additional classification layers. These layers may be
# trainable during secondary training.
for _ in range(self.config.dense_layers):
self.classification_layers.append(
Dense(self.config.dense_hidden_size))
# Append the final layer which has the correct dimensions for the output
self.classification_layers.append(
Dense(self.ctable.vocab_size, activation='softmax'))
# Actually build the model
for layer in self.feature_layers + self.classification_layers:
try:
model.add(layer)
except Exception as e:
logging.error('Error when adding layer %s: %s', layer, e)
raise
return model
def build_model(self, model=None):
if self.multi_gpu >= 2:
with tf.device('/cpu:0'):
if model is None:
model = self._return_model()
self.model_to_save = model
model = keras.utils.multi_gpu_model(model, gpus=self.multi_gpu)
else:
if model is None:
model = self._return_model()
self.model_to_save = model
metrics = ['accuracy']
if self.config.tensorboard:
tensorboard_metrics = ['loss'] + metrics
self.train_log_names = ['train_' + name for name in tensorboard_metrics]
self.test_log_names = ['test_' + name for name in tensorboard_metrics]
model.compile(loss='categorical_crossentropy',
optimizer=self.config.model_optimizer,
metrics=metrics)
self.model = model
def init_layers(self):
assert self.model is not None
assert len(self.classification_layers) == 0
assert len(self.feature_layers) == 0
for layer in self.model.layers:
if isinstance(layer, (TimeDistributed, Activation, Dense)):
self.classification_layers.append(layer)
else:
self.feature_layers.append(layer)
def train_model(self, serializer):
prev_accuracy = 0
max_accuracy = 0
if self.config.tensorboard:
self.callback.set_model(self.model)
for gen in range(self.config.generations):
self.generation = gen + 1
logging.info('Generation %d', gen + 1)
accuracy, early_stop = self.train_model_generation(serializer)
logging.info('Generation accuracy: %s', accuracy)
if early_stop:
break
if not self.config.early_stopping and \
(accuracy > max_accuracy or self.config.save_always):
max_accuracy = accuracy
serializer.save_model(self.model_to_save)
if ((accuracy - prev_accuracy) <
self.config.training_accuracy_threshold):
logging.info('Accuracy diff of %s is less than threshold.',
accuracy - prev_accuracy)
break
prev_accuracy = accuracy
def test_set(self, x_all, y_all, w_all):
split_at = len(x_all) - max(
int(len(x_all) / self.config.train_test_ratio), 1)
x_train = x_all[0:split_at, :]
x_val = x_all[split_at:, :]
y_train, y_val = (y_all[:split_at], y_all[split_at:])
w_train, w_val = (w_all[:split_at], w_all[split_at:])
return x_train, x_val, y_train, y_val, w_train, w_val
def training_step(self, x_all, y_all, w_all):
x_train, x_val, y_train, y_val, w_train, w_val = self.test_set(
x_all, y_all, w_all)
train_loss, train_accuracy = self.model.train_on_batch(
x_train, y_train, sample_weight=w_train)
test_loss, test_accuracy = self.model.test_on_batch(
x_val, y_val, sample_weight=w_val)
return (train_loss, train_accuracy, test_loss, test_accuracy)
def early_stopping(self, smooth_loss, serializer):
stop = False
if self.min_loss_early_stopping > smooth_loss:
self.min_loss_early_stopping = smooth_loss
serializer.save_model(self.model_to_save)
self.poor_batches_early_stopping = 0
elif self.poor_batches_early_stopping < self.config.early_stopping_patience:
self.poor_batches_early_stopping += 1
else:
stop = True
return stop
def train_model_generation(self, serializer=None):
if self.config.early_stopping:
assert serializer, "Need to specify serializer with early_stopping"
self.chunk = 0
self.pwd_list.reset()
accuracy_accum = []
x_all, y_all, w_all = self.next_train_set_as_np()
chunk = 0
early_stop = False
while len(x_all) != 0:
assert len(x_all) == len(y_all)
tr_loss, tr_acc, te_loss, te_acc = self.training_step(
x_all, y_all, w_all)
accuracy_accum += [(len(x_all), te_acc)]
self.smoothened_loss.append((len(x_all), te_loss))
if self.config.tensorboard:
self.write_log(self.train_log_names, [tr_loss, tr_acc], self.cumulative_chunks)
self.write_log(self.test_log_names, [te_loss, te_acc], self.cumulative_chunks)
if chunk % self.config.chunk_print_interval == 0:
#Finding weighted average to get the right loss value over batches
# of unequal sizes
instances_smoothened = map(lambda x: x[0], self.smoothened_loss)
loss_smoothened = sum(map(lambda x: x[0] * x[1], self.smoothened_loss)
) / sum(instances_smoothened)
logging.info('Chunk %s. Each chunk is size %s',
chunk, len(x_all))
logging.info('Train loss %s. Test loss %s. Test accuracy %s. Averaged loss %s',
tr_loss, te_loss, te_acc, loss_smoothened)
if self.config.tensorboard:
self.callback.writer.flush()
if self.config.early_stopping and \
self.cumulative_chunks >= self.config.early_stopping_patience and \
self.cumulative_chunks % self.config.chunk_print_interval == 0:
#Second condition so that the model doesn't start saving \
# very early in the training process
#Third condition to prevent evaluation of accuracy too frequently
instances_smoothened = map(lambda x: x[0], self.smoothened_loss)
loss_smoothened = sum(map(lambda x: x[0] * x[1], self.smoothened_loss)
) / sum(instances_smoothened)
early_stop = self.early_stopping(loss_smoothened, serializer)
if early_stop:
instances = map(lambda x: x[0], accuracy_accum)
return sum(map(lambda x: x[0] * x[1], accuracy_accum)
) / sum(instances), early_stop
x_all, y_all, w_all = self.next_train_set_as_np()
chunk += 1
self.cumulative_chunks += 1
instances = map(lambda x: x[0], accuracy_accum)
return sum(map(lambda x: x[0] * x[1], accuracy_accum)) / sum(instances), early_stop
def train(self, serializer):
logging.info('Building model...')
self.build_model(self.model)
logging.info('Done compiling model. Beginning training...')
self.train_model(serializer)
def freeze_feature_layers(self):
for layer in self.feature_layers:
layer.trainable = False
def retrain_classification(self, preprocessor, serializer):
assert self.model is not None
assert len(self.feature_layers) != 0
if self.config.freeze_feature_layers_during_secondary_training:
logging.info('Freezing feature layers...')
self.freeze_feature_layers()
logging.info('Retraining...')
self.pwd_list = preprocessor
self.train(serializer)
def write_log(self, names, logs, batch_no):
assert self.callback
for name, value in zip(names, logs):
summary = tf.Summary()
summary_value = summary.value.add()
summary_value.simple_value = value
summary_value.tag = name
self.callback.writer.add_summary(summary, batch_no)
class ManyToManyTrainer(Trainer):
def _return_model(self):
model = Sequential()
# Add the first input layer. If embedding is enabled, we add a different
# layer which does not have the input_shape defined
if self.config.embedding_layer:
self.feature_layers.append(
Embedding(
self.ctable.vocab_size,
self.config.embedding_size,
input_length=self.config.context_length))
self.feature_layers.append(self._make_layer())
else:
self.feature_layers.append(
self._make_layer(
input_shape=(
self.config.context_length, self.ctable.vocab_size)))
# Add the main model layers. These layers will not be trainable during
# secondary training.
for _ in range(self.config.layers):
if self.config.dropouts:
self.feature_layers.append(Dropout(self.config.dropout_ratio))
self.feature_layers.append(self._make_layer())
# Add any additional classification layers. These layers may be
# trainable during secondary training.
for _ in range(self.config.dense_layers):
self.classification_layers.append(TimeDistributed(Dense(
self.config.hidden_size)))
self.classification_layers.append(TimeDistributed(Dense(
self.ctable.vocab_size, activation="softmax")))
# Actually build the model
for layer in self.feature_layers + self.classification_layers:
try:
model.add(layer)
except Exception as e:
logging.error('Error when adding layer %s: %s', layer, e)
raise
return model
def next_train_set_as_np(self):
x_strs, y_str_list, weight_list = self.pwd_list.next_chunk()
x_vec = self.prepare_x_data(x_strs)
y_vec = self.prepare_y_data(y_str_list)
weight_vec = np.zeros((len(weight_list)))
for i, weight in enumerate(weight_list):
weight_vec[i] = weight
return shuffle(x_vec, y_vec, weight_vec)
def prepare_y_data(self, y_str_list):
y_vec = self.ctable.encode_many(y_str_list, y_vec=True)
return y_vec
class ManyToManyPreprocessor(Preprocessor):
def all_prefixes(self, pwd):
return [PASSWORD_START + pwd]
def all_suffixes(self, pwd):
return [pwd + PASSWORD_END]
def repeat_weight(self, pwd):
return [self.password_weight(pwd)]