forked from mravanelli/pytorch-kaldi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
2701 lines (2158 loc) · 98.2 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 math
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 for second level
r2 = re.compile("--.*,.*=.*")
# check if the option is valid for 4 level
r4 = re.compile('--.*,.*,.*,.*=".*"')
if r2.match(args[i]) is None and r4.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].split("=")[0]).group(1))
values.append(re.search("=(.*)", args[i]).group(1))
# parsing command line arguments
for i in range(len(sections)):
# Remove multi level is level >= 2
sections[i] = sections[i].split(",")[0]
if sections[i] in config.sections():
# Case of args level > than 2 like --sec,fields,0,field="value"
if len(fields[i].split(",")) >= 2:
splitted = fields[i].split(",")
# Get the actual fields
field = splitted[0]
number = int(splitted[1])
f_name = splitted[2]
if field in list(config[sections[i]]):
# Get the current string of the corresponding field
current_config_field = config[sections[i]][field]
# Count the number of occurence of the required field
matching = re.findall(f_name + ".", current_config_field)
if number >= len(matching):
sys.stderr.write(
'ERROR: the field number "%s" provided from command line is not valid, we found "%s" "%s" field(s) in section "%s"!\n'
% (number, len(matching), f_name, field)
)
sys.exit(0)
else:
# Now replace
str_to_be_replaced = re.findall(f_name + ".*", current_config_field)[number]
new_str = str(f_name + "=" + values[i])
replaced = nth_replace_string(current_config_field, str_to_be_replaced, new_str, number + 1)
config[sections[i]][field] = replaced
else:
sys.stderr.write(
'ERROR: field "%s" of section "%s" from command line is not valid!")\n' % (field, sections[i])
)
sys.exit(0)
else:
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])
)
sys.exit(0)
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_chunk"]))
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"). Make also sure there aren\'t white spaces between commas.\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"). Make also sure there aren\'t white spaces between commas. \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"). Make also sure there aren\'t white spaces between commas.\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))
sys.exit(0)
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)
# Reload data_name because they might be altered by arguments
name_data = []
for sec in config.sections():
if "dataset" in sec:
name_data.append(config[sec]["data_name"])
# 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
sys.exit(0)
# Set to false the first layer norm layer if the architecture is sequential (to avoid numerical instabilities)
seq_model = False
for sec in config.sections():
if "architecture" in sec:
if strtobool(config[sec]["arch_seq_model"]):
seq_model = True
break
if seq_model:
for item in list(config["architecture1"].items()):
if "use_laynorm" in item[0] and "_inp" not in item[0]:
ln_list = item[1].split(",")
if ln_list[0] == "True":
ln_list[0] = "False"
config["architecture1"][item[0]] = ",".join(ln_list)
# Production case (We don't have the alignement for the forward_with), by default the prod
# Flag is set to False, and the dataset prod number to 1, corresponding to no prod dataset
config["exp"]["production"] = str("False")
prod_dataset_number = "dataset1"
for data in name_data:
[lab_names, _, _] = parse_lab_field(config[cfg_item2sec(config, "data_name", data)]["lab"])
if "none" in lab_names and data == config["data_use"]["forward_with"]:
config["exp"]["production"] = str("True")
prod_data_name = data
for sec in config.sections():
if "dataset" in sec:
if config[sec]["data_name"] == data:
prod_dataset_number = sec
else:
continue
# If production case is detected, remove all the other datasets except production
if config["exp"]["production"] == str("True"):
name_data = [elem for elem in name_data if elem == prod_data_name]
# Parse fea and lab fields in datasets*
cnt = 0
fea_names_lst = []
lab_names_lst = []
for data in name_data:
[lab_names, _, _] = parse_lab_field(config[cfg_item2sec(config, "data_name", data)]["lab"])
if "none" in lab_names:
continue
[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))
# Check that fea_name doesn't contain special characters
for name_features in fea_names_lst[cnt]:
if not (re.match("^[a-zA-Z0-9]*$", name_features)):
sys.stderr.write(
'ERROR: features names (fea_name=) must contain only letters or numbers (no special characters as "_,$,..") \n'
)
sec_parse = False
sys.exit(0)
if cnt > 0:
if fea_names_lst[cnt - 1] != fea_names_lst[cnt]:
sys.stderr.write("ERROR: 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("ERROR: 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[prod_dataset_number]["lab"].replace(" ", "")))
lab_folders = list(re.findall("lab_folder=(.*)\n", config[prod_dataset_number]["lab"].replace(" ", "")))
N_out_lab = ["none"] * len(lab_lst)
if config["exp"]["production"] == str("False"):
for i in range(len(lab_opts)):
# Compute number of monophones if needed
if "ali-to-phones" in lab_opts[i]:
log_file = config["exp"]["out_folder"] + "/log.log"
folder_lab_count = lab_folders[i]
cmd = "hmm-info " + folder_lab_count + "/final.mdl | awk '/phones/{print $4}'"
output = run_shell(cmd, log_file)
if output.decode().rstrip() == "":
sys.stderr.write(
"ERROR: hmm-info command doesn't exist. Make sure your .bashrc contains the Kaldi paths and correctly exports it.\n"
)
sys.exit(0)
N_out = int(output.decode().rstrip())
N_out_lab[i] = N_out
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 "forward_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 "forward_out" 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 "forward_out" not in the right format)\n'
% (forward_norm_lst[i])
)
else:
# Try to automatically retrieve the count file from the config file
# Compute the number of context-dependent phone states
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)
if output.decode().rstrip() == "":
sys.stderr.write(
"ERROR: hmm-info command doesn't exist. Make sure your .bashrc contains the Kaldi paths and correctly exports it.\n"
)
sys.exit(0)
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. Please, 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 get_chunks_after_which_to_validate(N_ck_tr, nr_of_valid_per_epoch):
def _partition_chunks(N_ck_tr, nr_of_valid_per_epoch):
chunk_part = list()
chunk_size = int(np.ceil(N_ck_tr / float(nr_of_valid_per_epoch)))
for i1 in range(nr_of_valid_per_epoch):
chunk_part.append(range(0, N_ck_tr)[i1 * chunk_size : (i1 + 1) * chunk_size])
return chunk_part
part_chunk_ids = _partition_chunks(N_ck_tr, nr_of_valid_per_epoch)
chunk_ids = list()
for l in part_chunk_ids:
chunk_ids.append(l[-1])
return chunk_ids
def do_validation_after_chunk(ck, N_ck_tr, config):
def _get_nr_of_valid_per_epoch_from_config(config):
if not "nr_of_valid_per_epoch" in config["exp"]:
return 1
return int(config["exp"]["nr_of_valid_per_epoch"])
nr_of_valid_per_epoch = _get_nr_of_valid_per_epoch_from_config(config)
valid_chunks = get_chunks_after_which_to_validate(N_ck_tr, nr_of_valid_per_epoch)
if ck in valid_chunks:
return True
else:
return False
def _get_val_file_name_base(dataset, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val):
file_name = "valid_" + dataset + "_ep" + format(ep, N_ep_str_format) + "_trCk" + format(ck, N_ck_str_format)
if ck_val is None:
file_name += "*"
else:
file_name += "_ck" + format(ck_val, N_ck_str_format_val)
return file_name
def get_val_lst_file_path(
out_folder, valid_data, ep, ck, ck_val, fea_name, N_ep_str_format, N_ck_str_format, N_ck_str_format_val
):
def _get_val_lst_file_name(
dataset, ep, ck, ck_val, fea_name, N_ep_str_format, N_ck_str_format, N_ck_str_format_val
):
file_name = _get_val_file_name_base(
dataset, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val
)
file_name += "_"
if not fea_name is None:
file_name += fea_name
else:
file_name += "*"
file_name += ".lst"
return file_name
lst_file_name = _get_val_lst_file_name(
valid_data, ep, ck, ck_val, fea_name, N_ep_str_format, N_ck_str_format, N_ck_str_format_val
)
lst_file = out_folder + "/exp_files/" + lst_file_name
return lst_file
def get_val_info_file_path(
out_folder, valid_data, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val
):
def _get_val_info_file_name(dataset, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val):
file_name = _get_val_file_name_base(
dataset, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val
)
file_name += ".info"
return file_name
info_file_name = _get_val_info_file_name(
valid_data, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val
)
info_file = out_folder + "/exp_files/" + info_file_name
return info_file
def get_val_cfg_file_path(
out_folder, valid_data, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val
):
def _get_val_cfg_file_name(dataset, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val):
file_name = _get_val_file_name_base(
dataset, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val
)
file_name += ".cfg"
return file_name
cfg_file_name = _get_val_cfg_file_name(
valid_data, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val
)
config_chunk_file = out_folder + "/exp_files/" + cfg_file_name
return config_chunk_file
def create_configs(config):
# This function create the chunk-specific config files
cfg_file_proto_chunk = config["cfg_proto"]["cfg_proto_chunk"]
N_ep = int(config["exp"]["N_epochs_tr"])
N_ep_str_format = "0" + str(max(math.ceil(np.log10(N_ep)), 1)) + "d"
tr_data_lst = config["data_use"]["train_with"].split(",")
valid_data_lst = config["data_use"]["valid_with"].split(",")
max_seq_length_train = config["batches"]["max_seq_length_train"]
forward_data_lst = config["data_use"]["forward_with"].split(",")
is_production = strtobool(config["exp"]["production"])
out_folder = config["exp"]["out_folder"]
cfg_file = out_folder + "/conf.cfg"
chunk_lst = out_folder + "/exp_files/list_chunks.txt"
lst_chunk_file = open(chunk_lst, "w")
# Read the batch size string
batch_size_tr_str = config["batches"]["batch_size_train"]
batch_size_tr_arr = expand_str_ep(batch_size_tr_str, "int", N_ep, "|", "*")
# Read the max_seq_length_train
if len(max_seq_length_train.split(",")) == 1:
max_seq_length_tr_arr = expand_str_ep(max_seq_length_train, "int", N_ep, "|", "*")
else:
max_seq_length_tr_arr = [max_seq_length_train] * N_ep
cfg_file_proto = config["cfg_proto"]["cfg_proto"]
[config, name_data, name_arch] = check_cfg(cfg_file, config, cfg_file_proto)
arch_lst = get_all_archs(config)
lr = {}
improvement_threshold = {}
halving_factor = {}
pt_files = {}
drop_rates = {}
for arch in arch_lst:
lr_arr = expand_str_ep(config[arch]["arch_lr"], "float", N_ep, "|", "*")
lr[arch] = lr_arr
improvement_threshold[arch] = float(config[arch]["arch_improvement_threshold"])
halving_factor[arch] = float(config[arch]["arch_halving_factor"])
pt_files[arch] = config[arch]["arch_pretrain_file"]
# Loop over all the sections and look for a "_drop" field (to perform dropout scheduling
for (field_key, field_val) in config.items(arch):
if "_drop" in field_key:
drop_lay = field_val.split(",")
N_lay = len(drop_lay)
drop_rates[arch] = []
for lay_id in range(N_lay):
drop_rates[arch].append(expand_str_ep(drop_lay[lay_id], "float", N_ep, "|", "*"))
# Check dropout factors
for dropout_factor in drop_rates[arch][0]:
if float(dropout_factor) < 0.0 or float(dropout_factor) > 1.0:
sys.stderr.write(
"The dropout rate should be between 0 and 1. Got %s in %s.\n" % (dropout_factor, field_key)
)
sys.exit(0)
# Production case, we don't want to train, only forward without labels
if is_production:
ep = N_ep - 1
N_ep = 0
model_files = {}
max_seq_length_train_curr = max_seq_length_train
for arch in pt_files.keys():
model_files[arch] = out_folder + "/exp_files/final_" + arch + ".pkl"
if strtobool(config["batches"]["increase_seq_length_train"]):
max_seq_length_train_curr = config["batches"]["start_seq_len_train"]
if len(max_seq_length_train.split(",")) == 1:
max_seq_length_train_curr = int(max_seq_length_train_curr)
else:
# TODO: add support for increasing seq length when fea and lab have different time dimensionality
pass
for ep in range(N_ep):
for tr_data in tr_data_lst:
# Compute the total number of chunks for each training epoch
N_ck_tr = compute_n_chunks(out_folder, tr_data, ep, N_ep_str_format, "train")
N_ck_str_format = "0" + str(max(math.ceil(np.log10(N_ck_tr)), 1)) + "d"
# ***Epoch training***
for ck in range(N_ck_tr):
# path of the list of features for this chunk
lst_file = (
out_folder
+ "/exp_files/train_"
+ tr_data
+ "_ep"
+ format(ep, N_ep_str_format)
+ "_ck"
+ format(ck, N_ck_str_format)
+ "_*.lst"
)
# paths of the output files (info,model,chunk_specific cfg file)
info_file = (
out_folder
+ "/exp_files/train_"
+ tr_data
+ "_ep"
+ format(ep, N_ep_str_format)
+ "_ck"
+ format(ck, N_ck_str_format)
+ ".info"
)
if ep + ck == 0:
model_files_past = {}
else:
model_files_past = model_files
model_files = {}
for arch in pt_files.keys():
model_files[arch] = info_file.replace(".info", "_" + arch + ".pkl")
config_chunk_file = (
out_folder
+ "/exp_files/train_"
+ tr_data
+ "_ep"
+ format(ep, N_ep_str_format)
+ "_ck"
+ format(ck, N_ck_str_format)
+ ".cfg"
)
lst_chunk_file.write(config_chunk_file + "\n")
if strtobool(config["batches"]["increase_seq_length_train"]) == False:
if len(max_seq_length_train.split(",")) == 1:
max_seq_length_train_curr = int(max_seq_length_tr_arr[ep])
else:
max_seq_length_train_curr = max_seq_length_tr_arr[ep]
# Write chunk-specific cfg file
write_cfg_chunk(
cfg_file,
config_chunk_file,
cfg_file_proto_chunk,