forked from mravanelli/pytorch-kaldi
/
utils.py
1835 lines (1307 loc) · 67 KB
/
utils.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
##########################################################
# pytorch-kaldi v.0.1
# Mirco Ravanelli, Titouan Parcollet
# Mila, University of Montreal
# October 2018
##########################################################
import configparser
import sys
import os.path
import random
import subprocess
import numpy as np
import re
import glob
from distutils.util import strtobool
import importlib
import torch
import torch.nn as nn
import torch.optim as optim
import matplotlib as mpl
import matplotlib.pyplot as plt
def run_command(cmd):
"""from http://blog.kagesenshi.org/2008/02/teeing-python-subprocesspopen-output.html
"""
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = []
while True:
line = p.stdout.readline()
stdout.append(line)
print(line.decode("utf-8"))
if line == '' and p.poll() != None:
break
return ''.join(stdout)
def run_shell_display(cmd):
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True)
while True:
out = p.stdout.read(1).decode('utf-8')
if out == '' and p.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
return
def run_shell(cmd,log_file):
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True)
(output, err) = p.communicate()
p.wait()
with open(log_file, 'a+') as logfile:
logfile.write(output.decode("utf-8")+'\n')
logfile.write(err.decode("utf-8")+'\n')
#print(output.decode("utf-8"))
return output
def read_args_command_line(args,config):
sections=[]
fields=[]
values=[]
for i in range(2,len(args)):
# check if the option is valid
r=re.compile('--.*,.*=.*')
if r.match(args[i]) is None:
sys.stderr.write('ERROR: option \"%s\" from command line is not valid! (the format must be \"--section,field=value\")\n' %(args[i]))
sys.exit(0)
sections.append(re.search('--(.*),', args[i]).group(1))
fields.append(re.search(',(.*)=', args[i]).group(1))
values.append(re.search('=(.*)', args[i]).group(1))
# parsing command line arguments
for i in range(len(sections)):
if sections[i] in config.sections():
if fields[i] in list(config[sections[i]]):
config[sections[i]][fields[i]]=values[i]
else:
sys.stderr.write('ERROR: field \"%s\" of section \"%s\" from command line is not valid!")\n' %(fields[i],sections[i]))
else:
sys.stderr.write('ERROR: section \"%s\" from command line is not valid!")\n' %(sections[i]))
sys.exit(0)
return [sections,fields,values]
def compute_avg_performance(info_lst):
losses=[]
errors=[]
times=[]
for tr_info_file in info_lst:
config_res = configparser.ConfigParser()
config_res.read(tr_info_file)
losses.append(float(config_res['results']['loss']))
errors.append(float(config_res['results']['err']))
times.append(float(config_res['results']['elapsed_time']))
loss=np.mean(losses)
error=np.mean(errors)
time=np.sum(times)
return [loss,error,time]
def check_field(inp,type_inp,field):
valid_field=True
if inp=='' and field!='cmd':
sys.stderr.write("ERROR: The the field \"%s\" of the config file is empty! \n" % (field))
valid_field=False
sys.exit(0)
if type_inp=='path':
if not(os.path.isfile(inp)) and not(os.path.isdir(inp)) and inp!='none':
sys.stderr.write("ERROR: The path \"%s\" specified in the field \"%s\" of the config file does not exists! \n" % (inp,field))
valid_field=False
sys.exit(0)
if '{' and '}' in type_inp :
arg_list=type_inp[1:-1].split(',')
if inp not in arg_list:
sys.stderr.write("ERROR: The field \"%s\" can only contain %s arguments \n" % (field,arg_list))
valid_field=False
sys.exit(0)
if 'int(' in type_inp:
try:
int(inp)
except ValueError:
sys.stderr.write("ERROR: The field \"%s\" can only contain an integer (got \"%s\") \n" % (field,inp))
valid_field=False
sys.exit(0)
# Check if the value if within the expected range
lower_bound=type_inp.split(',')[0][4:]
upper_bound=type_inp.split(',')[1][:-1]
if lower_bound!="-inf":
if int(inp)<int(lower_bound):
sys.stderr.write("ERROR: The field \"%s\" can only contain an integer greater than %s (got \"%s\") \n" % (field,lower_bound,inp))
valid_field=False
sys.exit(0)
if upper_bound!="inf":
if int(inp)>int(upper_bound):
sys.stderr.write("ERROR: The field \"%s\" can only contain an integer smaller than %s (got \"%s\") \n" % (field,upper_bound,inp))
valid_field=False
sys.exit(0)
if 'float(' in type_inp:
try:
float(inp)
except ValueError:
sys.stderr.write("ERROR: The field \"%s\" can only contain a float (got \"%s\") \n" % (field,inp))
valid_field=False
sys.exit(0)
# Check if the value if within the expected range
lower_bound=type_inp.split(',')[0][6:]
upper_bound=type_inp.split(',')[1][:-1]
if lower_bound!="-inf":
if float(inp)<float(lower_bound):
sys.stderr.write("ERROR: The field \"%s\" can only contain a float greater than %s (got \"%s\") \n" % (field,lower_bound,inp))
valid_field=False
sys.exit(0)
if upper_bound!="inf":
if float(inp)>float(upper_bound):
sys.stderr.write("ERROR: The field \"%s\" can only contain a float smaller than %s (got \"%s\") \n" % (field,upper_bound,inp))
valid_field=False
sys.exit(0)
if type_inp=='bool':
lst={'True','true','1','False','false','0'}
if not(inp in lst):
sys.stderr.write("ERROR: The field \"%s\" can only contain a boolean (got \"%s\") \n" % (field,inp))
valid_field=False
sys.exit(0)
if 'int_list(' in type_inp:
lst=inp.split(',')
try:
list(map(int,lst))
except ValueError:
sys.stderr.write("ERROR: The field \"%s\" can only contain a list of integer (got \"%s\") \n" % (field,inp))
valid_field=False
sys.exit(0)
# Check if the value if within the expected range
lower_bound=type_inp.split(',')[0][9:]
upper_bound=type_inp.split(',')[1][:-1]
for elem in lst:
if lower_bound!="-inf":
if int(elem)<int(lower_bound):
sys.stderr.write("ERROR: The field \"%s\" can only contain an integer greater than %s (got \"%s\") \n" % (field,lower_bound,elem))
valid_field=False
sys.exit(0)
if upper_bound!="inf":
if int(elem)>int(upper_bound):
sys.stderr.write("ERROR: The field \"%s\" can only contain an integer smaller than %s (got \"%s\") \n" % (field,upper_bound,elem))
valid_field=False
sys.exit(0)
if 'float_list(' in type_inp:
lst=inp.split(',')
try:
list(map(float,lst))
except ValueError:
sys.stderr.write("ERROR: The field \"%s\" can only contain a list of floats (got \"%s\") \n" % (field,inp))
valid_field=False
sys.exit(0)
# Check if the value if within the expected range
lower_bound=type_inp.split(',')[0][11:]
upper_bound=type_inp.split(',')[1][:-1]
for elem in lst:
if lower_bound!="-inf":
if float(elem)<float(lower_bound):
sys.stderr.write("ERROR: The field \"%s\" can only contain a float greater than %s (got \"%s\") \n" % (field,lower_bound,elem))
valid_field=False
sys.exit(0)
if upper_bound!="inf":
if float(elem)>float(upper_bound):
sys.stderr.write("ERROR: The field \"%s\" can only contain a float smaller than %s (got \"%s\") \n" % (field,upper_bound,elem))
valid_field=False
sys.exit(0)
if type_inp=='bool_list':
lst={'True','true','1','False','false','0'}
inps=inp.split(',')
for elem in inps:
if not(elem in lst):
sys.stderr.write("ERROR: The field \"%s\" can only contain a list of boolean (got \"%s\") \n" % (field,inp))
valid_field=False
sys.exit(0)
return valid_field
def get_all_archs(config):
arch_lst=[]
for sec in config.sections():
if 'architecture' in sec:
arch_lst.append(sec)
return arch_lst
def expand_section(config_proto,config):
# expands config_proto with fields in prototype files
name_data=[]
name_arch=[]
for sec in config.sections():
if 'dataset' in sec:
config_proto.add_section(sec)
config_proto[sec]=config_proto['dataset']
name_data.append(config[sec]['data_name'])
if 'architecture' in sec:
name_arch.append(config[sec]['arch_name'])
config_proto.add_section(sec)
config_proto[sec]=config_proto['architecture']
proto_file=config[sec]['arch_proto']
# Reading proto file (architecture)
config_arch = configparser.ConfigParser()
config_arch.read(proto_file)
# Reading proto options
fields_arch=list(dict(config_arch.items('proto')).keys())
fields_arch_type=list(dict(config_arch.items('proto')).values())
for i in range(len(fields_arch)):
config_proto.set(sec,fields_arch[i],fields_arch_type[i])
# Reading proto file (architecture_optimizer)
opt_type=config[sec]['arch_opt']
if opt_type=='sgd':
proto_file='proto/sgd.proto'
if opt_type=='rmsprop':
proto_file='proto/rmsprop.proto'
if opt_type=='adam':
proto_file='proto/adam.proto'
config_arch = configparser.ConfigParser()
config_arch.read(proto_file)
# Reading proto options
fields_arch=list(dict(config_arch.items('proto')).keys())
fields_arch_type=list(dict(config_arch.items('proto')).values())
for i in range(len(fields_arch)):
config_proto.set(sec,fields_arch[i],fields_arch_type[i])
config_proto.remove_section('dataset')
config_proto.remove_section('architecture')
return [config_proto,name_data,name_arch]
def expand_section_proto(config_proto,config):
# Read config proto file
config_proto_optim_file=config['optimization']['opt_proto']
config_proto_optim = configparser.ConfigParser()
config_proto_optim.read(config_proto_optim_file)
for optim_par in list(config_proto_optim['proto']):
config_proto.set('optimization',optim_par,config_proto_optim['proto'][optim_par])
def check_cfg_fields(config_proto,config,cfg_file):
# Check mandatory sections and fields
sec_parse=True
for sec in config_proto.sections():
if any(sec in s for s in config.sections()):
# Check fields
for field in list(dict(config_proto.items(sec)).keys()):
if not(field in config[sec]):
sys.stderr.write("ERROR: The confg file %s does not contain the field \"%s=\" in section \"[%s]\" (mandatory)!\n" % (cfg_file,field,sec))
sec_parse=False
else:
field_type=config_proto[sec][field]
if not(check_field(config[sec][field],field_type,field)):
sec_parse=False
# If a mandatory section doesn't exist...
else:
sys.stderr.write("ERROR: The confg file %s does not contain \"[%s]\" section (mandatory)!\n" % (cfg_file,sec))
sec_parse=False
if sec_parse==False:
sys.stderr.write("ERROR: Revise the confg file %s \n" % (cfg_file))
return sec_parse
def check_consistency_with_proto(cfg_file,cfg_file_proto):
sec_parse=True
# Check if cfg file exists
try:
open(cfg_file, 'r')
except IOError:
sys.stderr.write("ERROR: The confg file %s does not exist!\n" % (cfg_file))
sys.exit(0)
# Check if cfg proto file exists
try:
open(cfg_file_proto, 'r')
except IOError:
sys.stderr.write("ERROR: The confg file %s does not exist!\n" % (cfg_file_proto))
sys.exit(0)
# Parser Initialization
config = configparser.ConfigParser()
# Reading the cfg file
config.read(cfg_file)
# Reading proto cfg file
config_proto = configparser.ConfigParser()
config_proto.read(cfg_file_proto)
# Adding the multiple entries in data and architecture sections
[config_proto,name_data,name_arch]=expand_section(config_proto,config)
# Check mandatory sections and fields
sec_parse=check_cfg_fields(config_proto,config,cfg_file)
if sec_parse==False:
sys.exit(0)
return [config_proto,name_data,name_arch]
def check_cfg(cfg_file,config,cfg_file_proto):
# Check consistency between cfg_file and cfg_file_proto
[config_proto,name_data,name_arch]=check_consistency_with_proto(cfg_file,cfg_file_proto)
# check consistency between [data_use] vs [data*]
sec_parse=True
data_use_with=[]
for data in list(dict(config.items('data_use')).values()):
data_use_with.append(data.split(','))
data_use_with=sum(data_use_with, [])
if not(set(data_use_with).issubset(name_data)):
sys.stderr.write("ERROR: in [data_use] you are using a dataset not specified in [dataset*] %s \n" % (cfg_file))
sec_parse=False
# Parse fea and lab fields in datasets*
cnt=0
fea_names_lst=[]
lab_names_lst=[]
for data in name_data:
[fea_names,fea_lsts,fea_opts,cws_left,cws_right]=parse_fea_field(config[cfg_item2sec(config,'data_name',data)]['fea'])
[lab_names,lab_folders,lab_opts]=parse_lab_field(config[cfg_item2sec(config,'data_name',data)]['lab'])
fea_names_lst.append(sorted(fea_names))
lab_names_lst.append(sorted(lab_names))
if cnt>0:
if fea_names_lst[cnt-1]!=fea_names_lst[cnt]:
sys.stderr.write("features name (fea_name) must be the same of all the datasets! \n" )
sec_parse=False
sys.exit(0)
if lab_names_lst[cnt-1]!=lab_names_lst[cnt]:
sys.stderr.write("labels name (lab_name) must be the same of all the datasets! \n" )
sec_parse=False
sys.exit(0)
cnt=cnt+1
# Create the output folder
out_folder=config['exp']['out_folder']
if not os.path.exists(out_folder) or not(os.path.exists(out_folder+'/exp_files')) :
os.makedirs(out_folder+'/exp_files')
# Parsing forward field
model=config['model']['model']
possible_outs=list(re.findall('(.*)=',model.replace(' ','')))
forward_out_lst=config['forward']['forward_out'].split(',')
forward_norm_lst=config['forward']['normalize_with_counts_from'].split(',')
forward_norm_bool_lst=config['forward']['normalize_posteriors'].split(',')
lab_lst=list(re.findall('lab_name=(.*)\n',config['dataset1']['lab'].replace(' ','')))
lab_folders=list(re.findall('lab_folder=(.*)\n',config['dataset1']['lab'].replace(' ','')))
N_out_lab=['none'] * len(lab_lst)
for i in range(len(forward_out_lst)):
if forward_out_lst[i] not in possible_outs:
sys.stderr.write('ERROR: the output \"%s\" in the section \"forwad_out\" is not defined in section model)\n' %(forward_out_lst[i]))
sys.exit(0)
if strtobool(forward_norm_bool_lst[i]):
if forward_norm_lst[i] not in lab_lst:
if not os.path.exists(forward_norm_lst[i]):
sys.stderr.write('ERROR: the count_file \"%s\" in the section \"forwad_out\" is does not exist)\n' %(forward_norm_lst[i]))
sys.exit(0)
else:
# Check if the specified file is in the right format
f = open(forward_norm_lst[i],"r")
cnts = f.read()
if not(bool(re.match("(.*)\[(.*)\]", cnts))):
sys.stderr.write('ERROR: the count_file \"%s\" in the section \"forwad_out\" is not in the right format)\n' %(forward_norm_lst[i]))
else:
# Try to automatically retrieve the config file
if "ali-to-pdf" in lab_opts[lab_lst.index(forward_norm_lst[i])]:
log_file=config['exp']['out_folder']+'/log.log'
folder_lab_count=lab_folders[lab_lst.index(forward_norm_lst[i])]
cmd="hmm-info "+folder_lab_count+"/final.mdl | awk '/pdfs/{print $4}'"
output=run_shell(cmd,log_file)
N_out=int(output.decode().rstrip())
N_out_lab[lab_lst.index(forward_norm_lst[i])]=N_out
count_file_path=out_folder+'/exp_files/forward_'+forward_out_lst[i]+'_'+forward_norm_lst[i]+'.count'
cmd="analyze-counts --print-args=False --verbose=0 --binary=false --counts-dim="+str(N_out)+" \"ark:ali-to-pdf "+folder_lab_count+"/final.mdl \\\"ark:gunzip -c "+folder_lab_count+"/ali.*.gz |\\\" ark:- |\" "+ count_file_path
run_shell(cmd,log_file)
forward_norm_lst[i]=count_file_path
else:
sys.stderr.write('ERROR: Not able to automatically retrieve count file for the label \"%s\". Please add a valid count file path in \"normalize_with_counts_from\" or set normalize_posteriors=False \n' %(forward_norm_lst[i]))
sys.exit(0)
# Update the config file with the count_file paths
config['forward']['normalize_with_counts_from']=",".join(forward_norm_lst)
# When possible replace the pattern "N_out_lab*" with the detected number of output
for sec in config.sections():
for field in list(config[sec]):
for i in range(len(lab_lst)):
pattern='N_out_'+lab_lst[i]
if pattern in config[sec][field]:
if N_out_lab[i]!='none':
config[sec][field]=config[sec][field].replace(pattern,str(N_out_lab[i]))
else:
sys.stderr.write('ERROR: Cannot automatically retrieve the number of output in %s. Plese, add manually the number of outputs \n' %(pattern))
sys.exit(0)
# Check the model field
parse_model_field(cfg_file)
# Create block diagram picture of the model
create_block_diagram(cfg_file)
if sec_parse==False:
sys.exit(0)
return [config,name_data,name_arch]
def cfg_item2sec(config,field,value):
for sec in config.sections():
if field in list(dict(config.items(sec)).keys()):
if value in list(dict(config.items(sec)).values()):
return sec
sys.stderr.write("ERROR: %s=%s not found in config file \n" % (field,value))
sys.exit(0)
return -1
def split_chunks(seq, size):
newseq = []
splitsize = 1.0/size*len(seq)
for i in range(size):
newseq.append(seq[int(round(i*splitsize)):int(round((i+1)*splitsize))])
return newseq
def create_chunks(config):
# splitting data into chunks (see out_folder/additional_files)
out_folder=config['exp']['out_folder']
seed=int(config['exp']['seed'])
N_ep=int(config['exp']['N_epochs_tr'])
# Setting the random seed
random.seed(seed)
# training chunk lists creation
tr_data_name=config['data_use']['train_with'].split(',')
# Reading validation feature lists
for dataset in tr_data_name:
sec_data=cfg_item2sec(config,'data_name',dataset)
[fea_names,list_fea,fea_opts,cws_left,cws_right]=parse_fea_field(config[cfg_item2sec(config,'data_name',dataset)]['fea'])
N_chunks= int(config[sec_data]['N_chunks'])
full_list=[]
for i in range(len(fea_names)):
full_list.append([line.rstrip('\n')+',' for line in open(list_fea[i])])
full_list[i]=sorted(full_list[i])
# concatenating all the featues in a single file (useful for shuffling consistently)
full_list_fea_conc=full_list[0]
for i in range(1,len(full_list)):
full_list_fea_conc=list(map(str.__add__,full_list_fea_conc,full_list[i]))
for ep in range(N_ep):
# randomize the list
random.shuffle(full_list_fea_conc)
tr_chunks_fea=list(split_chunks(full_list_fea_conc,N_chunks))
tr_chunks_fea.reverse()
for ck in range(N_chunks):
for i in range(len(fea_names)):
tr_chunks_fea_split=[];
for snt in tr_chunks_fea[ck]:
#print(snt.split(',')[i])
tr_chunks_fea_split.append(snt.split(',')[i])
output_lst_file=out_folder+'/exp_files/train_'+dataset+'_ep'+format(ep, "03d")+'_ck'+format(ck, "02d")+'_'+fea_names[i]+'.lst'
f=open(output_lst_file,'w')
tr_chunks_fea_wr=map(lambda x:x+'\n', tr_chunks_fea_split)
f.writelines(tr_chunks_fea_wr)
f.close()
#Training chunk lists creation
# tr_data_name=config['data_use']['train_with'].split(',')
# [fea_names,fea_lsts,fea_opts,cws_left,cws_right]=parse_fea_field(config[cfg_item2sec(config,'data_name',tr_data_name[0])]['fea'])
#
# full_list_fea=[]
# for i in range(len(fea_names)):
# full_list=[]
# N_chunks_tr=0
#
# # Reading training feature lists
# for dataset in tr_data_name:
# sec_data=cfg_item2sec(config,'data_name',dataset)
# [fea_lst,list_fea,fea_opts,cws_left,cws_right]=parse_fea_field(config[cfg_item2sec(config,'data_name',dataset)]['fea'])
# N_chunks_tr= N_chunks_tr+int(config[sec_data]['N_chunks'])
# full_list.append([line.rstrip('\n')+',' for line in open(list_fea[i])])
#
# full_list=sum(full_list, [])
# full_list=sorted(full_list)
# full_list_fea.append(full_list)
#
#
# # concatenating all the featues in a single file (useful for shuffling consistently)
# full_list_fea_conc=full_list_fea[0]
# for i in range(1,len(full_list_fea)):
# full_list_fea_conc=list(map(str.__add__,full_list_fea_conc,full_list_fea[i]))
#
#
# for ep in range(N_ep):
#
# # randomize the list
# random.shuffle(full_list_fea_conc)
#
# tr_chunks_fea=list(split_chunks(full_list_fea_conc,N_chunks_tr))
# tr_chunks_fea.reverse()
# # Note: without reverse the shortest chunk is the last one.
# # With reverse I process the shortest chunk first (it is more safe)
#
# # Writing the lst files for each chunk/epoch
# for ck in range(N_chunks_tr):
# #print(tr_chunks_fea[ck])
# for i in range(len(fea_names)):
#
# tr_chunks_fea_split=[];
# for snt in tr_chunks_fea[ck]:
# #print(snt.split(',')[i])
# tr_chunks_fea_split.append(snt.split(',')[i])
#
# output_lst_file=out_folder+'/exp_files/train_'+config['data_use']['train_with'].replace(',','+')+'_ep'+format(ep, "03d")+'_ck'+format(ck, "02d")+'_'+fea_names[i]+'.lst'
# f=open(output_lst_file,'w')
# tr_chunks_fea_wr=map(lambda x:x+'\n', tr_chunks_fea_split)
# f.writelines(tr_chunks_fea_wr)
# f.close()
# Validation chunk lists creation
valid_data_name=config['data_use']['valid_with'].split(',')
# Reading validation feature lists
for dataset in valid_data_name:
sec_data=cfg_item2sec(config,'data_name',dataset)
[fea_names,list_fea,fea_opts,cws_left,cws_right]=parse_fea_field(config[cfg_item2sec(config,'data_name',dataset)]['fea'])
N_chunks= int(config[sec_data]['N_chunks'])
full_list=[]
for i in range(len(fea_names)):
full_list.append([line.rstrip('\n')+',' for line in open(list_fea[i])])
full_list[i]=sorted(full_list[i])
# concatenating all the featues in a single file (useful for shuffling consistently)
full_list_fea_conc=full_list[0]
for i in range(1,len(full_list)):
full_list_fea_conc=list(map(str.__add__,full_list_fea_conc,full_list[i]))
# randomize the list
random.shuffle(full_list_fea_conc)
valid_chunks_fea=list(split_chunks(full_list_fea_conc,N_chunks))
for ep in range(N_ep):
for ck in range(N_chunks):
for i in range(len(fea_names)):
valid_chunks_fea_split=[];
for snt in valid_chunks_fea[ck]:
#print(snt.split(',')[i])
valid_chunks_fea_split.append(snt.split(',')[i])
output_lst_file=out_folder+'/exp_files/valid_'+dataset+'_ep'+format(ep, "03d")+'_ck'+format(ck, "02d")+'_'+fea_names[i]+'.lst'
f=open(output_lst_file,'w')
valid_chunks_fea_wr=map(lambda x:x+'\n', valid_chunks_fea_split)
f.writelines(valid_chunks_fea_wr)
f.close()
# forward chunk lists creation
forward_data_name=config['data_use']['forward_with'].split(',')
# Reading validation feature lists
for dataset in forward_data_name:
sec_data=cfg_item2sec(config,'data_name',dataset)
[fea_names,list_fea,fea_opts,cws_left,cws_right]=parse_fea_field(config[cfg_item2sec(config,'data_name',dataset)]['fea'])
N_chunks= int(config[sec_data]['N_chunks'])
full_list=[]
for i in range(len(fea_names)):
full_list.append([line.rstrip('\n')+',' for line in open(list_fea[i])])
full_list[i]=sorted(full_list[i])
# concatenating all the featues in a single file (useful for shuffling consistently)
full_list_fea_conc=full_list[0]
for i in range(1,len(full_list)):
full_list_fea_conc=list(map(str.__add__,full_list_fea_conc,full_list[i]))
# randomize the list
random.shuffle(full_list_fea_conc)
forward_chunks_fea=list(split_chunks(full_list_fea_conc,N_chunks))
for ck in range(N_chunks):
for i in range(len(fea_names)):
forward_chunks_fea_split=[];
for snt in forward_chunks_fea[ck]:
#print(snt.split(',')[i])
forward_chunks_fea_split.append(snt.split(',')[i])
output_lst_file=out_folder+'/exp_files/forward_'+dataset+'_ep'+format(ep, "03d")+'_ck'+format(ck, "02d")+'_'+fea_names[i]+'.lst'
f=open(output_lst_file,'w')
forward_chunks_fea_wr=map(lambda x:x+'\n', forward_chunks_fea_split)
f.writelines(forward_chunks_fea_wr)
f.close()
def write_cfg_chunk(cfg_file,config_chunk_file,cfg_file_proto_chunk,pt_files,lst_file,info_file,to_do,data_set_name,lr,max_seq_length_train_curr,name_data,ep,ck):
# writing the chunk-specific cfg file
config = configparser.ConfigParser()
config.read(cfg_file)
config_chunk = configparser.ConfigParser()
config_chunk.read(cfg_file)
# Exp section
config_chunk['exp']['to_do']=to_do
config_chunk['exp']['out_info']=info_file
# change seed for randomness
config_chunk['exp']['seed']=str(int(config_chunk['exp']['seed'])+ep+ck)
for arch in pt_files.keys():
config_chunk[arch]['arch_pretrain_file']=pt_files[arch]
# writing the current learning rate
for lr_arch in lr.keys():
config_chunk[lr_arch ]['arch_lr']=str(lr[lr_arch])
# Data_chunk section
config_chunk.add_section('data_chunk')
config_chunk['data_chunk']=config[cfg_item2sec(config,'data_name',data_set_name)]
lst_files=sorted(glob.glob(lst_file))
current_fea=config_chunk['data_chunk']['fea']
list_current_fea=re.findall('fea_name=(.*)\nfea_lst=(.*)\n', current_fea)
for (fea, path) in list_current_fea:
for path_cand in lst_files:
fea_type_cand=re.findall('_(.*).lst', path_cand)[0].split('_')[-1]
if fea_type_cand==fea:
config_chunk['data_chunk']['fea']=config_chunk['data_chunk']['fea'].replace(path,path_cand)
config_chunk.remove_option('data_chunk','data_name')
config_chunk.remove_option('data_chunk','N_chunks')
config_chunk.remove_section('decoding')
config_chunk.remove_section('data_use')
for dataset in name_data:
config_chunk.remove_section(cfg_item2sec(config_chunk,'data_name',dataset))
# Create batche section
config_chunk.remove_option('batches','increase_seq_length_train')
config_chunk.remove_option('batches','start_seq_len_train')
config_chunk.remove_option('batches','multply_factor_seq_len_train')
config_chunk['batches']['max_seq_length_train']=str(max_seq_length_train_curr)
# Write cfg_file_chunk
with open(config_chunk_file, 'w') as configfile:
config_chunk.write(configfile)
# Check cfg_file_chunk
[config_proto_chunk,name_data_ck,name_arch_ck]=check_consistency_with_proto(config_chunk_file,cfg_file_proto_chunk)
def parse_fea_field(fea):
# Adding the required fields into a list
fea_names=[]
fea_lsts=[]
fea_opts=[]
cws_left=[]
cws_right=[]
for line in fea.split('\n'):
line=re.sub(' +',' ',line)
if 'fea_name=' in line:
fea_names.append(line.split('=')[1])
if 'fea_lst=' in line:
fea_lsts.append(line.split('=')[1])
if 'fea_opts=' in line:
fea_opts.append(line.split('fea_opts=')[1])
if 'cw_left=' in line:
cws_left.append(line.split('=')[1])
if not(check_field(line.split('=')[1],'int(0,inf)','cw_left')):
sys.exit(0)
if 'cw_right=' in line:
cws_right.append(line.split('=')[1])
if not(check_field(line.split('=')[1],'int(0,inf)','cw_right')):
sys.exit(0)
# Check features names
if not(sorted(fea_names)==sorted(list(set(fea_names)))):
sys.stderr.write('ERROR fea_names must be different! (got %s)' %(fea_names))
sys.exit(0)
snt_lst=[]
cnt=0
# Check consistency of feature lists
for fea_lst in fea_lsts:
if not(os.path.isfile(fea_lst)):
sys.stderr.write("ERROR: The path \"%s\" specified in the field \"fea_lst\" of the config file does not exists! \n" % (fea_lst))
else:
snts = sorted([line.rstrip('\n').split(' ')[0] for line in open(fea_lst)])
snt_lst.append(snts)
# Check if all the sentences are present in all the list files
if cnt>0:
if snt_lst[cnt-1]!=snt_lst[cnt]:
sys.stderr.write("ERROR: the files %s in fea_lst contain a different set of sentences! \n" % (fea_lst))
cnt=cnt+1
return [fea_names,fea_lsts,fea_opts,cws_left,cws_right]
def parse_lab_field(lab):
# Adding the required fields into a list
lab_names=[]
lab_folders=[]
lab_opts=[]
for line in lab.split('\n'):
line=re.sub(' +',' ',line)
if 'lab_name=' in line:
lab_names.append(line.split('=')[1])
if 'lab_folder=' in line:
lab_folders.append(line.split('=')[1])
if 'lab_opts=' in line:
lab_opts.append(line.split('lab_opts=')[1])
# Check features names
if not(sorted(lab_names)==sorted(list(set(lab_names)))):
sys.stderr.write('ERROR lab_names must be different! (got %s)' %(lab_names))
sys.exit(0)
# Check consistency of feature lists
for lab_fold in lab_folders:
if not(os.path.isdir(lab_fold)):
sys.stderr.write("ERROR: The path \"%s\" specified in the field \"lab_folder\" of the config file does not exists! \n" % (lab_fold))
return [lab_names,lab_folders,lab_opts]
def compute_n_chunks(out_folder,data_list,ep,step):
list_ck=sorted(glob.glob(out_folder+'/exp_files/'+step+'_'+data_list+'_ep'+format(ep, "03d")+'*.lst'))
last_ck=list_ck[-1]
N_ck=int(re.findall('_ck(.+)_', last_ck)[-1].split('_')[0])+1
return N_ck
def parse_model_field(cfg_file):
# Reading the config file
config = configparser.ConfigParser()
config.read(cfg_file)
# reading the proto file
model_proto_file=config['model']['model_proto']
f = open(model_proto_file,"r")
proto_model = f.read()
# readiing the model string
model=config['model']['model']
# Reading fea,lab arch architectures from the cfg file
fea_lst=list(re.findall('fea_name=(.*)\n',config['dataset1']['fea'].replace(' ','')))
lab_lst=list(re.findall('lab_name=(.*)\n',config['dataset1']['lab'].replace(' ','')))
arch_lst=list(re.findall('arch_name=(.*)\n',open(cfg_file, 'r').read().replace(' ','')))
possible_operations=re.findall('(.*)\((.*),(.*)\)\n',proto_model)
possible_inputs=fea_lst
model_arch=list(filter(None, model.replace(' ','').split('\n')))
# Reading the model field line by line
for line in model_arch:
pattern='(.*)=(.*)\((.*),(.*)\)'
if not re.match(pattern,line):
sys.stderr.write('ERROR: all the entries must be of the following type: output=operation(str,str), got (%s)\n'%(line))
sys.exit(0)
else:
# Analyze line and chech if it is compliant with proto_model
[out_name,operation,inp1,inp2]=list(re.findall(pattern,line)[0])
inps=[inp1,inp2]
found=False
for i in range(len(possible_operations)):
if operation==possible_operations[i][0]:
found=True
for k in range(1,3):
if possible_operations[i][k]=='architecture':
if inps[k-1] not in arch_lst:
sys.stderr.write('ERROR: the architecture \"%s\" is not in the architecture lists of the config file (possible architectures are %s)\n' %(inps[k-1],arch_lst))
sys.exit(0)
if possible_operations[i][k]=='label':
if inps[k-1] not in lab_lst:
sys.stderr.write('ERROR: the label \"%s\" is not in the label lists of the config file (possible labels are %s)\n' %(inps[k-1],lab_lst))
sys.exit(0)
if possible_operations[i][k]=='input':
if inps[k-1] not in possible_inputs:
sys.stderr.write('ERROR: the input \"%s\" is not defined before (possible inputs are %s)\n' %(inps[k-1],possible_inputs))
sys.exit(0)
if possible_operations[i][k]=='float':
try:
float(inps[k-1])
except ValueError: