-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforward-selection
More file actions
executable file
·1573 lines (1401 loc) · 58.5 KB
/
forward-selection
File metadata and controls
executable file
·1573 lines (1401 loc) · 58.5 KB
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
#!/usr/bin/env python
import collections
import heapq
import itertools
import json
import math
import numpy as np
import operator
import os
import pickle
import random
import redis
import scipy
from sklearn.linear_model import Ridge
import signal
import socket
import subprocess
import sys
import time
import uuid
import xml.etree.ElementTree as ET
FAILED_SCORE = 0.0
REUSE_STATELESS_PARAMS = True
class CommonEqualityMixin(object):
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not self.__eq__(other)
class Feature(CommonEqualityMixin):
def __init__(self, stage, syntax_mode, label, templates=[]):
''' label is just a priveledged template that has high selectivitity and must be there '''
if type(templates) is str:
templates = [templates]
assert type(label) is str
assert type(syntax_mode) is str
assert type(stage) is str
assert type(templates) is list # of strinsgs
self.stage = stage
self.syntax_mode = syntax_mode
self.label = label
self.templates = templates
self.templates.sort()
def __str__(self):
if self.stage == 'NullStage':
return '*'.join([self.label] + self.templates)
st = self.stage + '-' + self.syntax_mode
return "*".join([st, self.label] + self.templates)
def estimate_cardinality(self, template_info):
c = 1
for t in self.templates:
c *= template_info.cardinality(self.stage, self.syntax_mode, self.label, t)
assert type(c) is int or type(c) is long
return c
def propose_modification(self, template_info):
def helper():
# the higher the estimated cardinality, the greater the chance of
# removing a template
# e.g. cardinality = 100 -> p(shrink) = 0.500
# cardinality = 4 -> p(shrink) = 0.167
# cardinality = 400 -> p(shrink) = 0.667
# cardinality = 4000 -> p(shrink) = 0.863 (only if #templates > 1 though)
card = pow(self.estimate_cardinality(template_info), 0.5)
p_shrink = card / (card + 10.0)
if len(self.templates) > 1 and random.random() < p_shrink:
# remove a template
tmpl = random.sample(self.templates, len(self.templates) - 1)
return Feature(self.stage, self.syntax_mode, self.label, tmpl)
else:
# add a new template
xs = [x for x in template_info.basic_templates() if x not in self.templates]
if len(xs) > 0:
return Feature(self.stage, self.syntax_mode, self.label, self.templates + [random.choice(xs)])
else:
raise Exception('cant extend this Feature any further')
for i in range(500):
f = helper()
if f.estimate_cardinality(template_info) > 0:
return f
assert False, 'couldn\'t make a new feature with card>0'
return None
class FeatureSet(object):
def __init__(self, features=[], labels=None, syntax_mode=None, only_emit_diff=False, derived_from=None):
'''
If only_emit_diff=True, then calls to config_string() will only return the Features
which appear in this feature set and NOT in derived_from. For the purpose of storing
the full feature set for modifications, the features list will still contain Features
from derived_from.
'''
self.features = features
self.derived_from = derived_from
self.__syntax_mode = syntax_mode
self.__labels = labels
self.only_emit_diff = only_emit_diff
if derived_from and syntax_mode is None and derived_from.__syntax_mode:
self.__syntax_mode = derived_from.__syntax_mode
if derived_from and labels is None and derived_from.__labels:
self.__labels = derived_from.__labels
def __eq__(self, other):
return isinstance(other, self.__class__) and self.features == other.features
def __ne__(self, other):
return not self.__eq__(other)
def copy(self):
return FeatureSet(self.features[:], self.derived_from)
def restrict_to(self, stages):
n = len(self.features)
fs = []
for f in self.features:
if f.stage in stages:
fs.append(f)
self.features = fs
print "[FeatureSet restrict_to] only including stages: %s, %d => %d" \
% (str(stages), n, len(self.features))
def trim(self, template_info):
''' Removes any features in this set which have cardinality 0 '''
n = len(self.features)
fs = []
for f in self.features:
if f.estimate_cardinality(template_info) > 0:
fs.append(f)
else:
print '[FeatureSet trim] removing:', f
self.features = fs
print "[FeatureSet trim] %d => %d" % (n, len(self.features))
def estimate_cardinality(self, template_info, stage=None):
''' Returns a dict with stage names as keys and int/long values '''
cards = collections.defaultdict(lambda: 1)
for f in self.features:
cards[f.stage] = cards[f.stage] * f.estimate_cardinality(template_info)
if stage:
return cards[stage]
else:
return cards
def stages(self):
s = set()
for f in self.features:
s.add(f.stage)
return list(s)
def labels(self, stage=None):
''' If a stage is not provided, we union over stages '''
labs = set()
for f in self.features:
if stage is None or f.stage == stage:
labs.add(f.label)
return list(labs)
def __count_feats_for_stage(self, stage):
c = 0
for f in self.features:
if f.stage == stage:
c += 1
return c
def propose_modification(self, template_info, ignore_stage=False, only_add=False):
'''
Returns a new FeatureSet derived from this feature set.
If ignore_stage=true, then this will produce Features with stage='NullStage',
which should have corresponding rows in the TemplateInfo file (which say what
templates/labels/syntax_modes can be used with 'NullStage').
'''
# a few options for mutation:
# 1) add a Feature
# 2) remove a Feature
# 3) mutate a Feature
debug = True
if ignore_stage:
stage = 'NullStage'
else:
rel_stages = set(template_info.stages()) & set(self.stages())
if len(rel_stages) == 0:
print 'self.stages', self.stages()
print 'template_info.stages', template_info.stages()
assert False
stage = random.choice(list(rel_stages))
relevant_feats = [f for f in self.features if f.stage == stage]
card = 1
#card = self.estimate_cardinality(template_info, stage)
#l = 0.3 # interpolation between cardinality (1) and #features (0)
#alpha = 0.2
#beta = 500.0
#gamma = 15.0
#p_add_feature = l * beta / (beta + pow(card, alpha)) \
# + (1.0 - l) * (gamma / (gamma + len(self.features)))
p_add_feature = 0.4
p_remove_feature = 0.3 if len(relevant_feats) > 0 else 0.0
p_mutate_feature = 0.3
# re-normalize
z = p_add_feature + p_remove_feature + p_mutate_feature
p_add_feature /= z
p_remove_feature /= z
p_mutate_feature /= z
if debug:
print '[FeatureSet propose_modification] len(self.features) =', \
len(self.features), 'stage =', stage, 'cardinality =', card, \
'p_add_features =', p_add_feature, \
'p_remove_feature =', p_remove_feature, \
'p_mutate_feature =', p_mutate_feature
r = random.random()
if r < p_add_feature or only_add:
# Make a new feature and add it to this set
f = self.new_feature(template_info, stage)
if debug:
print '[FeatureSet propose_modification] adding:', f
return FeatureSet(self.features + [f], derived_from=self)
elif r >= p_add_feature and r < p_add_feature + p_remove_feature:
# Remove a feature from this set
f = random.choice(relevant_feats)
if debug:
print '[FeatureSet propose_modification] removing:', f
i = self.features.index(f)
return FeatureSet(self.features[:i] + self.features[i+1:], derived_from=self)
else:
# Modify and replace a feature that is already in this feature set
try:
i = random.randrange(len(self.features))
f = self.features[i].propose_modification(template_info)
if debug:
print '[FeatureSet propose_modification] mutating:', self.features[i]
return FeatureSet([f] + self.features[:i] + self.features[i+1:], derived_from=self)
except:
return self.propose_modification(template_info, ignore_stage)
def new_feature(self, template_info, stage):
''' Creates a feature that is not already in this feature set '''
# prefer adding features with small number of templates
syntax_mode = self.syntax_mode()
label_template, basic_template = random.choice(template_info.labels_for(stage, syntax_mode))
f = Feature(stage, syntax_mode, label_template, basic_template)
if f in self.features or f.estimate_cardinality(template_info) == 0:
return self.new_feature(template_info, stage)
else:
print '[new_feature] stage =', stage
print '[new_feature] syntax_mode =', syntax_mode
print '[new_feature] label_template =', label_template
print '[new_feature] basic_template =', basic_template
return f
def syntax_mode(self):
if self.__syntax_mode:
return self.__syntax_mode
assert len(self.features) > 0
return self.features[0].syntax_mode
def __str__(self):
return "<FeatureSet %s>" % (', '.join([str(x) for x in self.features]))
def config_string(self):
rel = self.features
if self.only_emit_diff and self.derived_from:
# Only keep features not in derived_from
old = set()
for f in self.derived_from.features:
old.add(str(f))
rel = []
for f in self.features:
if str(f) not in old:
rel.append(f)
return "+".join([str(x) for x in rel])
class Config(CommonEqualityMixin):
''' A full specification of a FN parsing model '''
def __init__(self, feature_set, settings_dict, regularizer_dict, batch_size_dict, passes_dict, derived_from=None):
self.feature_set = feature_set
# Score of this configuration once evaluated (e.g. an F1 score)
# This value is not set by this class
self.score = None
self.derived_from = derived_from
self.regularizer_dict = regularizer_dict
for k, v in regularizer_dict.iteritems():
assert type(k) is str # Name of the stage
assert type(v) is int # Natural log of the regularizer
self.batch_size_dict = batch_size_dict
for k, v in batch_size_dict.iteritems():
assert type(k) is str # Name of the stage
assert type(v) is int # Batch size
self.passes_dict = passes_dict
for k, v in passes_dict.iteritems():
assert type(k) is str # Name of the stage
assert type(v) is int # Number of training passes
self.params = {}
self.params['randomSeed'] = '9001'
self.params.update(settings_dict)
def stages(self):
s1 = set(self.regularizer_dict.keys())
s2 = set(self.features.stages())
assert s1.issuperset(s2)
return list(s1)
def __str__(self):
return "<Config features=%s regularizer=%s params=%s>" % \
(str(self.feature_set), str(self.regularizer_dict), str(self.params))
def copy(self):
r = {}
r.update(self.regularizer_dict)
b = {}
b.update(self.batch_size_dict)
p = {}
p.update(self.passes_dict)
x = {}
x.update(self.params)
fs = self.feature_set.copy()
return Config(fs, x, r, b, p)
# NOTE: This is only here because pickle doesn't work on instance methods...
# need to do the 'kingdom of nouns' thing and make an object to make pickle work.
class Mutator(object):
def mutate(self, item):
''' return a list of items derived from the given item '''
raise NotImplementedError()
class ConfigMutator(Mutator):
def __init__(self, template_info, ignore_stages=False, emit_feature_diffs=False):
'''
If emit_feature_diffs=True, then this class will return mutated FeatureSets with
fs.only_emit_diff=True, which means that anyone who calls fs.config_string() will
only see the diffs between fs and fs.derived_from.
NOTE: I put this here instead of in ConfigJobStarter because it doesn't really
belong there.
'''
self.__template_info = template_info
self.ignore_stages = ignore_stages
self.emit_feature_diffs = emit_feature_diffs
def mutate(self, config):
''' Config -> [Config] '''
# TODO keep track of how many results we've seen so far
# every K feature sets we get results for, the training set size should be increased by a factor of G
# try K=50, G=3
# this would take 5 iterations if N_0=1000 to get the full train set of 169k, 250 jobs (most of which would be quite big)
# every time N*=G, consider lowering each stages regularizer (cross prod)
# TODO does this mean that we need to block between hitting the limit (#feature-sets per N_train) and receiving all of the results?
# could have a var that keeps track of the partition of jobs with the relevant N_train that we're submitting
# still wouldn't fix the case of having the best (N-1)_train job occur at the end (we would have started N_train jobs already, which would have better perf... but wouldn't show up until later)
# 1) hit num_jobs_at_this_train_size limit
# 2) mutate_num_jobs_parent += 1
# 3) start mutated jobs coming from *new* n_train limit pool
# self.n_train_cur = only mutate configs that have n_train == this
# self.n_jobs_dispatched = number of jobs submitted with the current setting self.n_train_cur
# self.n_jobs_received = number of jobs submitted with the current setting self.n_train_cur
### OBSERVE_SCORE
# if self.n_jobs_at_n_train_cur >= K:
# self.n_jobs_at_n_train_cur = 0
# self.n_train_cur *= G
### MUTATE
# find the pool of jobs which match self.n_train_cur
# choose one, mutate it, return it
# self.n_jobs_at_n_train_cur += 1
# CONSTRAINT:
# We want to have had the chance to mutate every config in a given partition of n_train.
# (or almost, we need to be failure resiliant)
# if we assume that time(N_0 * G^{n+1}) >> time(N_0 * G^{n})
# SOLUTION:
# have a set of 'configs we havent tried mutating'
# every time we attempt to mutate, we remove all the ones we considered
# every time we receive a new score, we add it to this set
# these set(s) are indexed by n_train
# always try to select from smallest n_train bucket if its not empty
# when one is not empty, we consider that example as well as any that we know about that have the same n_train
# TODO this should not go here, it should go into a new Queue implementation
# mutate just mutates, this new queue implementation will tell it what to mutate
if self.ignore_stages:
next_fs = config.feature_set.propose_modification(self.__template_info, ignore_stage=True)
else:
next_fs = config.feature_set.propose_modification(self.__template_info)
if self.emit_feature_diffs:
print '[mutate_config] only emitting FeatureSet diffs'
next_fs.only_emit_diff = True
cur_card = config.feature_set.estimate_cardinality(self.__template_info)
next_card = next_fs.estimate_cardinality(self.__template_info)
print '[mutate_config] cardinality: ', cur_card, ' => ', next_card
# cardinality is now a dict with stages as keys
# regularizer is too
# for each stage, decide if you want to change the regularizer or not
alpha = 15000
beta = 1.5
gamma = 0.25 # p(change regularizer irrespective of cardinality)
children = [Config(next_fs, config.params, config.regularizer_dict, config.batch_size_dict, config.passes_dict, derived_from=config)]
stages = set(self.__template_info.stages()) & set(next_fs.stages())
for stage in stages:
cc = cur_card[stage]
nc = next_card[stage]
dc = nc - cc
try:
if dc > alpha or (cc > 0 and dc / cc > beta) or random.random() < gamma:
# stronger regularizer
reg = {}
reg.update(config.regularizer_dict)
reg[stage] = reg[stage] + 1
c = Config(next_fs, config.params, reg, config.batch_size_dict, \
config.passes_dict, derived_from=config)
children.append(c)
print '[mutate] upping regularizer for', stage, 'to', reg[stage]
if dc < -alpha or (cc > 0 and dc / cc < -beta) or random.random() < gamma:
# weaker regularizer
reg = {}
reg.update(config.regularizer_dict)
reg[stage] = reg[stage] - 1
c = Config(next_fs, config.params, reg, config.batch_size_dict, \
config.passes_dict, derived_from=config)
children.append(c)
print '[mutate] downing regularizer for', stage, 'to', reg[stage]
except:
print '[mutate] WARNING: goofed for stage', stage
pass
# Carry over stateless params learned at the previous iteration
if REUSE_STATELESS_PARAMS:
for c in children:
if c.derived_from and 'workingDir' in c.derived_from.params:
wd = c.derived_from.params['workingDir']
f = os.path.join(wd, 'statelessParams.jser.gz')
if not os.path.isfile(f):
print 'look for', f, 'in', wd
#raise Exception('templated stateless params not saved!')
print 'WARNING: templated stateless params not saved!'
else:
c.params['fixedStatelessParamsJserFile'] = f
print 'setting fixedStatelessParamsJserFile =', f
else:
print 'cant set fixedStatelessParamsJserFile because no derived_from'
# TODO try increasing/decreasing the number of passes
return children
class Queue(object):
def observe_score(self, score, name, item):
''' Receive a message about the final score of an item running '''
#raise NotImplementedError()
pass
def pop(self):
raise NotImplementedError()
class ExplicitQueue(Queue):
''' Takes a list of items to pop in order '''
def __init__(self, items):
self.items = items
def pop(self):
if self.items:
r = self.items[0]
self.items = self.items[1:]
return r
else:
return None
class MutatorQueue(Queue):
'''
An infinite queue of items. A seed set of items should be pushed onto the queue
to begin with, but after that this queue will generate new items by calling
propose_modification on existing items. Remember to call observe_score to let this
queue know what are good items and which are bad.
'''
def __init__(self, mutator, greediness=1.0, max_pops=0):
self.__mutator = mutator # see Mutator.mutate, item -> [item]
self.greediness = greediness
self.item2score = {} # item -> score for popped items
self.waiting = [] # List of items that should be popped before mutating scored items
self.__max_pops = max_pops
self.__pop_count = 0
self.stopped = False
def _pick(self, greediness):
debug = len(self.item2score) < 25
# Sort the items by score, and find the max score
weights = []
items = []
x = sorted(self.item2score.items(), key=lambda kv: kv[1], reverse=True)
m = x[0][1]
z = 0.0
rank = 0
for item, s in x:
regret_a = (m - s) * 10.0
regret_b = math.sqrt(rank) / 10.0
w = math.exp(-greediness * (regret_a + regret_b))
weights.append(w)
items.append(item)
z += w
rank += 1
t = random.random() * z
if debug:
print '[pick] z =', z, 't =', t
# Randomly sample
c = 0.0
for i in range(len(weights)):
c += weights[i]
if debug:
print '[pick]', items[i], 'has score', c
if c >= t:
print '[pick] chose', items[i]
return items[i]
# Should never get here
print '[pick] scored_feature_sets:', self.item2score
print '[pick] weights:', weights
assert False
def message(self, message):
if message == 'stop':
self.stopped = True
else:
print '[MutatorQueue message] unknown message:', message
def show_state(self, k=10):
print '[show_state]', len(self.item2score), 'observations'
print '[show_state] stopped:', self.stopped
best = sorted(self.item2score.items(), key=operator.itemgetter(1), reverse=True)
i = 1
for item, score in best[:k]:
print "[show_state] %dth best\t%.3f\t%s" % (i, score, item)
i += 1
def observe_score(self, score, name, item):
''' Record the score of a given config/item '''
print '[observe_score] score =', score, 'item =', item
assert type(score) is float
assert type(name) is str
assert type(item) is not str # TODO for debugging, in the future this could technically be a string
try:
item.score = score
except:
print '[observe_score] this item type does not have a score attribute:', type(item)
if item in self.item2score:
if self.item2score[item] == FAILED_SCORE:
print ("[observe_score] WARN: may need to sleep longer, " \
"%s/%s was originally deemed failed but later reported a score of %f") \
% (item, name, score)
else:
raise Exception(str(item) + '/' + name + ' had a score of ' \
+ str(self.item2score[item]) \
+ ' but you tried to observe the score ' + str(score))
self.item2score[item] = score
# print the biggest weights
if len(self.item2score) % 50 == 0:
self.show_state()
def seed(self, item):
''' Like push, but this item is special in that we will use it as the seed
for all items until we start receiving scores back '''
print '[seed] seeding', item, 'with score', FAILED_SCORE
self.push(item)
self.observe_score(FAILED_SCORE, 'seed' + str(len(self.item2score)), item)
def push(self, item):
''' Push an item onto the queue which must be run before
propose_modification's are considered '''
self.waiting.append(item)
def pop(self):
''' Returns a pushed item if there is one, otherwise chooses
a scored item and mutates it with propose_modification '''
if self.stopped:
print '[pop] MutatorQueue is stopped, returning None'
return None
if self.__max_pops > 0 and self.__pop_count >= self.__max_pops:
print '[pop]', str(self), 'hit max pops:', self.__max_pops
return None
self.__pop_count += 1
if self.waiting:
print '[pop] from waiting'
return self.waiting.pop()
else:
if len(self.item2score) == 0:
raise Exception('you must seed some items using push so there is something to mutate')
tries = 0
max_tries = 100
while tries < max_tries:
# g->0 as we run out of tries
g = self.greediness * (max_tries - tries) / float(max_tries)
parent = self._pick(g)
children = self.__mutator.mutate(parent)
dont_generate = set(self.waiting + self.item2score.keys())
feasible = [c for c in children if c not in dont_generate]
if len(feasible) < len(children):
for c in (set(children) - set(feasible)):
print '[pop] pruned', c
if feasible:
random.shuffle(feasible)
while len(feasible) > 1:
self.push(feasible.pop())
print '[pop] after', tries, 'tries'
return feasible.pop()
else:
tries += 1
print '[pop] couldn\'t generate a new configuration'
return None
class MultiQueue(object):
''' Muxes multiple Queues into one Queue '''
def __init__(self):
self.__item2qn = {}
self.__name2q = {}
self.__q_names = []
self.__on_deck = 0
self.__stopped = set() # names of queues that are paused/stopped
self.__all_stopped = False
def add_queue(self, name, queue):
assert name not in self.__name2q
self.__name2q[name] = queue
self.__q_names.append(name)
def message(self, message):
print '[MultiQueue message]', message
if message == 'list' or message == 'info':
if self.__all_stopped:
print '[MultiQueue message list] all stopped:', self.__q_names
elif self.__q_names:
for q in self.__q_names:
r = 'stopped' if q in self.__stopped else 'running'
print '[MultiQueue message list]', q, 'is', r
else:
print '[MultiQueue message list] no queues!'
elif message == 'stop':
self.__all_stopped = True
elif message == 'start':
self.__all_stopped = False
elif message == 'help':
print '[MultiQueue message help] allowable commands:'
print 'list: list all queues'
print 'help: this command'
print 'stop: pause all queues'
print 'start: resume all queues'
print '[queue_name] [command]: dispatch command to queue_name'
else:
# queue-specific message
try:
qn, msg = message.split(' ', 1)
if msg == 'stop':
print '[MultiQueue message] stopping', qn
self.__stopped.add(qn)
elif msg == 'start':
print '[MultiQueue message] starting', qn
self.__stopped.remove(qn)
else:
print '[MultiQueue message] forwarding', msg, 'to', qn
q = self.__name2q[qn]
q.message(msg)
except:
print '[MultiQueue message] failed to handle message:', message
def observe_score(self, score, name, item):
# parse name, lookup queue, forward call
qn = self.__item2qn[item]
q = self.__name2q[qn]
q.observe_score(score, name, item)
def __nextq(self):
n = len(self.__q_names)
if self.__on_deck == n - 1:
self.__on_deck = 0
else:
self.__on_deck += 1
def pop(self):
if self.__all_stopped:
print '[MultiQueue pop] stopped, returning None'
return None
n = len(self.__q_names)
assert self.__on_deck < n
for i in range(n):
qn = self.__q_names[self.__on_deck]
if qn in self.__stopped:
self.__nextq()
else:
q = self.__name2q[qn]
p = q.pop()
self.__nextq()
if p:
self.__item2qn[p] = qn
return p
print '[MultiQueue pop] returning None', len(self.__stopped), 'stopped queues'
return None
class SgeJobTracker(object):
''' A job tracker that asks qstat for the jobs that are
running and spawns jobs with qsub '''
def __init__(self, logging_dir=None):
self.logging_dir = logging_dir
if logging_dir and not os.path.isdir(logging_dir):
os.makedirs(logging_dir)
def can_submit_more_jobs(self):
try:
return len(self.jobs_queued()) < 10
except subprocess.CalledProcessError:
return False
def jobs(self):
'''
name_predicate should be a lambda that takes a string (name)
and returns true if the job should be kept.
This method skips over any jobs that are marked as QLOGIN,
so name_predicate need not filter those out.
Returns a list of job names.
'''
xml = subprocess.check_output(['qstat', '-u', 'twolfe', '-xml'])
xml = ET.fromstring(xml)
assert xml.tag == 'job_info'
# NOTE: wow this is really bad...
# SGE reports *running* jobs in a list called 'queue_info'
# and reports *queued* jobs in a list called 'job_info'
for info_name in ['job_info', 'queue_info']:
info = xml.find(info_name)
assert info is not None
# NOTE: each 'job_list' is actually a job
# not a list of jobs as the name would suggest
for j in info.findall('job_list'):
#print 'j.tag', j.tag
state = j.find('state').text # e.g. 'r' or 'qw'
name = j.find('JB_name').text
#print '[sge jobs]', state, name
if name == 'QLOGIN':
continue
yield (state, name)
def jobs_running(self):
''' returns a list of job names '''
return [name for state, name in self.jobs() if state == 'r']
def jobs_queued(self):
''' returns a list of job names '''
return [name for state, name in self.jobs() if state == 'qw']
def spawn(self, name, args):
cmd = ['qsub', '-N', name]
if self.logging_dir:
print 'spawning with logging dir:', self.logging_dir
cmd += ['-o', self.logging_dir]
# TODO add this as an option!
#cmd += ['ForwardSelectionWorker.qsub', name]
#cmd += ['FinalResults', '-1']
cmd += ['scripts/propbank-feature-selection.sh', name]
for k, v in args.iteritems():
cmd += [k, v]
print '[sge spawn] cmd =', cmd
subprocess.Popen(cmd)
time.sleep(0.2)
class LocalJobTracker(object):
'''
mock job tracker which uses redis instead of qsub
if debug is true, this will call scripts/dummy-forward-selection-job
else this will call the actual experiment
'''
def __init__(self, debug=False, max_concurrent_jobs=2):
self.key = 'dummy-job-tracker.jobs'
self.redis = redis.StrictRedis(host='localhost', port=6379, db=0)
self.debug = debug
self.max_concurrent_jobs = max_concurrent_jobs
def remove_all_jobs(self):
''' ensures that there are no jobs running (for testing) '''
self.redis.delete(self.key)
def can_submit_more_jobs(self):
return len(self.jobs_running()) < self.max_concurrent_jobs
def jobs_running(self):
# TODO this won't work in cases where jobs die!
# qsub can handle this, but to remove from redis queue, we've been assuming things finish
return self.redis.lrange(self.key, 0, -1)
def set_job_done(self, name):
print '[set_job_done] name=' + name
self.redis.lrem(self.key, 0, name)
def jobs_queued(self):
return []
# NOTE this implementation is a bit annoying because stdout from the spawned process
# dumps into the main process's stdout, BUT this is only a problem locally. This appears
# difficult to solve in python because there is no way to properly close the file that
# you would route stdout to.
def spawn(self, name, args):
''' args should be a dictionary of values to pass to grid.Runner '''
self.redis.rpush(self.key, name)
if self.debug:
raise Exception('need to update args for dummy-forward-selection-job')
subprocess.Popen(['scripts/dummy-forward-selection-job'] + args)
else:
cp = subprocess.check_output(['find', 'target/', '-iname', '*.jar']).strip()
cp = ':'.join([x.strip() for x in cp.split('\n')])
#cp = 'target/classes:' + cp
cmd = ['java', '-Xmx4G', '-ea', '-server', '-cp', cp]
#cmd += ['-XX:+UseG1GC', '-XX:G1ReservePercent=2', '-XX:ConcGCThreads=1', '-XX:ParallelGCThreads=1']
cmd += ['-XX:+UseSerialGC']
#cmd.append('edu.jhu.hlt.fnparse.experiment.grid.Runner')
cmd.append('edu.jhu.hlt.fnparse.rl.rerank.RerankerTrainer')
cmd.append(name)
for k, v in args.iteritems():
cmd += [k, v]
print '[spawn] about to spawn:', ' '.join(["'" + x + "'" for x in cmd])
subprocess.Popen(cmd)
# JobEngine: listens to messages, pops items from a Queue, names jobs, and asks the JobTracker to start the job
# JobTracker: reports the state of the computation resource (grid), w.r.t. a user (possibly including items from multiple Queues)
# JobStarter: given a (name, item, JobTracker) start a job
class ConfigJobStarter:
''' A job starter for items that are Configs '''
def __init__(self, working_dir, redis_config):
self.working_dir = working_dir
self.redis_config = redis_config
def start_job(self, name, config, job_tracker):
''' Just a function that adds arguments that are not Config-specific,
but constitute more information than a general JobTracker should know '''
assert isinstance(config, Config), "%s has type %s" % (config, type(config))
cmd = {}
wd = os.path.join(self.working_dir, 'wd-' + name)
rf = os.path.join(wd, 'results.txt')
cmd['resultReporter'] = "redis:%s,%s,%s\tfile:%s" % \
(self.redis_config['host'], self.redis_config['channel'], self.redis_config['port'], rf)
cmd['workingDir'] = wd
config.params['workingDir'] = wd
cmd['features'] = config.feature_set.config_string()
for stage, regularizer in config.regularizer_dict.iteritems():
cmd['regularizer.' + stage] = str(math.exp(regularizer))
for stage, batch_size in config.batch_size_dict.iteritems():
cmd['batchSize.' + stage] = str(batch_size)
for stage, passes in config.passes_dict.iteritems():
cmd['passes.' + stage] = str(passes)
# pull out the score of the previous config, and tell the job not to save its
# model if the score is lower than that.
if config.derived_from and config.derived_from.score:
cmd['scoreToBeat'] = str(config.derived_from.score)
latent_stages = set()
for f in config.feature_set.features:
if f.syntax_mode == 'latent':
latent_stages.add(f.stage)
for s in latent_stages:
key = 'bpIters.' + s
if key not in cmd:
cmd[key] = '5'
cmd.update(config.params)
job_tracker.spawn(name, cmd)
class JobEngine:
def __init__(self, name, job_tracker, config_q, job_starter, redis_config, poll_interval=8.0):
print '[JobEngine] attempting to use redis server at', redis_config
if not config_q:
raise Exception('you cant give a None config_q')
self.name = name
self.job_tracker = job_tracker # talks to qsub
self.config_q = config_q # provides pop() and observe_score(score, name, item)
self.job_starter = job_starter # has start_job(name, item, job_tracker)
self.redis_config = redis_config
self.name2item = {}
self.poll_interval = poll_interval
self.dispatched = set() # names of the jobs that (should be) running
def parse_message(self, data):
'''
parses a message from the experiment over redis pubsub
and returns a tuple of (config, score)
'''
toks = data.split('\t', 2)
assert len(toks) == 3
score = float(toks[0])
name = toks[1]
config = toks[2]
return (score, name, config)
def start_job(self):
''' returns a unique job name and updates self.name2item '''
# TODO move this to a separate method that is passed in, like mutate
item = self.config_q.pop()
if item:
# TODO this name needs to start with the queue name so MultiQueue knows
# what to do when you call .observe_score()
name = "fs-%s-%d" % (self.name, len(self.name2item))
assert name not in self.name2item
self.name2item[name] = item
self.job_starter.start_job(name, item, self.job_tracker)
self.dispatched.add(name)
print '[start_job] name =', name
print '[start_job] params =', item.params
return name
else:
print '[start_job] there are no more jobs, returning None'
return None
def __handle_message(self, message, perf_file):
''' NOTE there is no command for 'stop'. This is because you should use 'messageQ',
tell it to 'stop', and then this loop will exit when all the jobs are done. '''
toks = message.split(' ', 1)
if len(toks) == 1:
print '[__handle_message] unknown message type:', message
return
m_type, rest = toks
if m_type == 'result':
# parse out (score, name, config), do what we were doing before
score, name, config = rest.split('\t', 2)
score = float(score)
item = self.name2item[name]
print '[__handle_message]', name, '/', config, 'finished successfully with a score', score
perf_file.write("%f\t%s\t%s\n" % (score, name, config))
perf_file.flush()
self.config_q.observe_score(score, name, item)
# Remove this jobs from dispatched
print '[__handle_message] about to print job tracker'
print '[__handle_message]', self.job_tracker
if type(self.job_tracker) is LocalJobTracker: # for debugging
print '[__handle_message] stopping', name, 'on local job tracker'
self.job_tracker.set_job_done(name)
try:
self.dispatched.remove(name)
print '[__handle_message] removed', name, 'from dispatched,', len(self.dispatched), 'still dispatched'
except:
print '[__handle_message]', name, 'was not in dispatched, we gave up on this job as failed previously'
elif m_type == 'messageQ':
# check for a queue name argument, forward to q.message(remaining_message)
try:
self.config_q.message(rest)
except (AttributeError, TypeError) as e:
print '[__handle_message] this queue does not support messages:', rest
print e
elif m_type == 'saveQ':
# parse out file, pickle the queue to that
print '[__handle_message] saving queue to', rest
with open(rest, 'wb') as f:
pickle.dump(self.config_q, f)
elif m_type == 'loadQ':
# parse out file, unpickle the queue from that
print '[__handle_message] loading queue from', rest
with open(rest, 'rb') as f:
self.config_q = pickle.load(f)
self.config_q.show_state()
else:
print '[__handle_message] unknown message:', message
def run(self, perf_file_name):
r = redis.StrictRedis(host=self.redis_config['host'], port=self.redis_config['port'], db=self.redis_config['db'])
p = r.pubsub(ignore_subscribe_messages=True)
p.subscribe(self.redis_config['channel'])
print '[run] writing results to', perf_file_name
perf_file = open(perf_file_name, 'w')
self.num_jobs = 0
while True:
# Try to dispatch new jobs
can_sub = self.job_tracker.can_submit_more_jobs()
if can_sub and self.start_job():
self.num_jobs += 1
else:
# Check for results
if can_sub: