forked from mravanelli/pytorch-kaldi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.py
753 lines (654 loc) · 28 KB
/
core.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
##########################################################
# pytorch-kaldi v.0.1
# Mirco Ravanelli, Titouan Parcollet
# Mila, University of Montreal
# October 2018
##########################################################
import sys
import configparser
import os
from utils import is_sequential_dict, model_init, optimizer_init, forward_model, progress
from data_io import load_counts
import numpy as np
import random
import torch
from distutils.util import strtobool
import time
import threading
import torch
from data_io import read_lab_fea, open_or_fd, write_mat
from utils import shift
def read_next_chunk_into_shared_list_with_subprocess(
read_lab_fea, shared_list, cfg_file, is_production, output_folder, wait_for_process
):
p = threading.Thread(target=read_lab_fea, args=(cfg_file, is_production, shared_list, output_folder))
p.start()
if wait_for_process:
p.join()
return None
else:
return p
def extract_data_from_shared_list(shared_list):
data_name = shared_list[0]
data_end_index_fea = shared_list[1]
data_end_index_lab = shared_list[2]
fea_dict = shared_list[3]
lab_dict = shared_list[4]
arch_dict = shared_list[5]
data_set = shared_list[6]
return data_name, data_end_index_fea, data_end_index_lab, fea_dict, lab_dict, arch_dict, data_set
def convert_numpy_to_torch(data_set_dict, save_gpumem, use_cuda):
if not (save_gpumem) and use_cuda:
data_set_inp = torch.from_numpy(data_set_dict["input"]).float().cuda()
data_set_ref = torch.from_numpy(data_set_dict["ref"]).float().cuda()
else:
data_set_inp = torch.from_numpy(data_set_dict["input"]).float()
data_set_ref = torch.from_numpy(data_set_dict["ref"]).float()
data_set_ref = data_set_ref.view((data_set_ref.shape[0], 1))
return data_set_inp, data_set_ref
def run_nn_refac01(
data_name, data_set, data_end_index, fea_dict, lab_dict, arch_dict, cfg_file, processed_first, next_config_file
):
def _read_chunk_specific_config(cfg_file):
if not (os.path.exists(cfg_file)):
sys.stderr.write("ERROR: The config file %s does not exist!\n" % (cfg_file))
sys.exit(0)
else:
config = configparser.ConfigParser()
config.read(cfg_file)
return config
def _get_batch_size_from_config(config, to_do):
if to_do == "train":
batch_size = int(config["batches"]["batch_size_train"])
elif to_do == "valid":
batch_size = int(config["batches"]["batch_size_valid"])
elif to_do == "forward":
batch_size = 1
return batch_size
def _initialize_random_seed(config):
seed = int(config["exp"]["seed"])
torch.manual_seed(seed)
random.seed(seed)
np.random.seed(seed)
def _load_model_and_optimizer(fea_dict, model, config, arch_dict, use_cuda, multi_gpu, to_do):
inp_out_dict = fea_dict
nns, costs = model_init(inp_out_dict, model, config, arch_dict, use_cuda, multi_gpu, to_do)
optimizers = optimizer_init(nns, config, arch_dict)
for net in nns.keys():
pt_file_arch = config[arch_dict[net][0]]["arch_pretrain_file"]
if pt_file_arch != "none":
if use_cuda:
checkpoint_load = torch.load(pt_file_arch)
else:
checkpoint_load = torch.load(pt_file_arch, map_location="cpu")
nns[net].load_state_dict(checkpoint_load["model_par"])
if net in optimizers:
optimizers[net].load_state_dict(checkpoint_load["optimizer_par"])
optimizers[net].param_groups[0]["lr"] = float(
config[arch_dict[net][0]]["arch_lr"]
) # loading lr of the cfg file for pt
if multi_gpu:
nns[net] = torch.nn.DataParallel(nns[net])
return nns, costs, optimizers, inp_out_dict
def _open_forward_output_files_and_get_file_handles(forward_outs, require_decodings, info_file, output_folder):
post_file = {}
for out_id in range(len(forward_outs)):
if require_decodings[out_id]:
out_file = info_file.replace(".info", "_" + forward_outs[out_id] + "_to_decode.ark")
else:
out_file = info_file.replace(".info", "_" + forward_outs[out_id] + ".ark")
post_file[forward_outs[out_id]] = open_or_fd(out_file, output_folder, "wb")
return post_file
def _get_batch_config(data_set_input, seq_model, to_do, data_name, batch_size):
N_snt = None
N_ex_tr = None
N_batches = None
if seq_model or to_do == "forward":
N_snt = len(data_name)
N_batches = int(N_snt / batch_size)
else:
N_ex_tr = data_set_input.shape[0]
N_batches = int(N_ex_tr / batch_size)
return N_snt, N_ex_tr, N_batches
def _prepare_input(
snt_index,
batch_size,
inp_dim,
ref_dim,
beg_snt_fea,
beg_snt_lab,
data_end_index_fea,
data_end_index_lab,
beg_batch,
end_batch,
seq_model,
arr_snt_len_fea,
arr_snt_len_lab,
data_set_inp,
data_set_ref,
use_cuda,
):
def _zero_padding(
inp,
ref,
max_len_fea,
max_len_lab,
data_end_index_fea,
data_end_index_lab,
data_set_inp,
data_set_ref,
beg_snt_fea,
beg_snt_lab,
snt_index,
k,
):
def _input_and_ref_have_same_time_dimension(N_zeros_fea, N_zeros_lab):
if N_zeros_fea == N_zeros_lab:
return True
return False
snt_len_fea = data_end_index_fea[snt_index] - beg_snt_fea
snt_len_lab = data_end_index_lab[snt_index] - beg_snt_lab
N_zeros_fea = max_len_fea - snt_len_fea
N_zeros_lab = max_len_lab - snt_len_lab
if _input_and_ref_have_same_time_dimension(N_zeros_fea, N_zeros_lab):
N_zeros_fea_left = random.randint(0, N_zeros_fea)
N_zeros_lab_left = N_zeros_fea_left
else:
N_zeros_fea_left = 0
N_zeros_lab_left = 0
inp[N_zeros_fea_left : N_zeros_fea_left + snt_len_fea, k, :] = data_set_inp[
beg_snt_fea : beg_snt_fea + snt_len_fea, :
]
ref[N_zeros_lab_left : N_zeros_lab_left + snt_len_lab, k, :] = data_set_ref[
beg_snt_lab : beg_snt_lab + snt_len_lab, :
]
return inp, ref, snt_len_fea, snt_len_lab
if len(data_set_ref.shape) == 1:
data_set_ref = data_set_ref.shape.view((data_set_ref.shape[0], 1))
max_len = 0
if seq_model:
max_len_fea = int(max(arr_snt_len_fea[snt_index : snt_index + batch_size]))
max_len_lab = int(max(arr_snt_len_lab[snt_index : snt_index + batch_size]))
inp = torch.zeros(max_len_fea, batch_size, inp_dim).contiguous()
ref = torch.zeros(max_len_lab, batch_size, ref_dim).contiguous()
for k in range(batch_size):
inp, ref, snt_len_fea, snt_len_lab = _zero_padding(
inp,
ref,
max_len_fea,
max_len_lab,
data_end_index_fea,
data_end_index_lab,
data_set_inp,
data_set_ref,
beg_snt_fea,
beg_snt_lab,
snt_index,
k,
)
beg_snt_fea = data_end_index_fea[snt_index]
beg_snt_lab = data_end_index_lab[snt_index]
snt_index = snt_index + 1
else:
if to_do != "forward":
inp = data_set[beg_batch:end_batch, :].contiguous()
else:
snt_len_fea = data_end_index_fea[snt_index] - beg_snt_fea
snt_len_lab = data_end_index_lab[snt_index] - beg_snt_lab
inp = data_set_inp[beg_snt_fea : beg_snt_fea + snt_len_fea, :].contiguous()
ref = data_set_ref[beg_snt_lab : beg_snt_lab + snt_len_lab, :].contiguous()
beg_snt_fea = data_end_index_fea[snt_index]
beg_snt_lab = data_end_index_lab[snt_index]
snt_index = snt_index + 1
if use_cuda:
inp = inp.cuda()
ref = ref.cuda()
return inp, ref, max_len_fea, max_len_lab, snt_len_fea, snt_len_lab, beg_snt_fea, beg_snt_lab, snt_index
def _optimization_step(optimizers, outs_dict, config, arch_dict):
for opt in optimizers.keys():
optimizers[opt].zero_grad()
outs_dict["loss_final"].backward()
for opt in optimizers.keys():
if not (strtobool(config[arch_dict[opt][0]]["arch_freeze"])):
optimizers[opt].step()
def _update_progress_bar(to_do, i, N_batches, loss_sum):
if to_do == "train":
status_string = (
"Training | (Batch "
+ str(i + 1)
+ "/"
+ str(N_batches)
+ ")"
+ " | L:"
+ str(round(loss_sum.cpu().item() / (i + 1), 3))
)
if i == N_batches - 1:
status_string = "Training | (Batch " + str(i + 1) + "/" + str(N_batches) + ")"
if to_do == "valid":
status_string = "Validating | (Batch " + str(i + 1) + "/" + str(N_batches) + ")"
if to_do == "forward":
status_string = "Forwarding | (Batch " + str(i + 1) + "/" + str(N_batches) + ")"
progress(i, N_batches, status=status_string)
def _write_info_file(info_file, to_do, loss_tot, err_tot, elapsed_time_chunk):
with open(info_file, "w") as text_file:
text_file.write("[results]\n")
if to_do != "forward":
text_file.write("loss=%s\n" % loss_tot.cpu().numpy())
text_file.write("err=%s\n" % err_tot.cpu().numpy())
text_file.write("elapsed_time_chunk=%f\n" % elapsed_time_chunk)
text_file.close()
def _save_model(to_do, nns, multi_gpu, optimizers, info_file, arch_dict):
if to_do == "train":
for net in nns.keys():
checkpoint = {}
if multi_gpu:
checkpoint["model_par"] = nns[net].module.state_dict()
else:
checkpoint["model_par"] = nns[net].state_dict()
if net in optimizers:
checkpoint["optimizer_par"] = optimizers[net].state_dict()
else:
checkpoint["optimizer_par"] = dict()
out_file = info_file.replace(".info", "_" + arch_dict[net][0] + ".pkl")
torch.save(checkpoint, out_file)
def _get_dim_from_data_set(data_set_inp, data_set_ref):
inp_dim = data_set_inp.shape[1]
ref_dim = 1
if len(data_set_ref.shape) > 1:
ref_dim = data_set_ref.shape[1]
return inp_dim, ref_dim
from data_io import read_lab_fea_refac01 as read_lab_fea
from utils import forward_model_refac01 as forward_model
config = _read_chunk_specific_config(cfg_file)
_initialize_random_seed(config)
output_folder = config["exp"]["out_folder"]
use_cuda = strtobool(config["exp"]["use_cuda"])
multi_gpu = strtobool(config["exp"]["multi_gpu"])
to_do = config["exp"]["to_do"]
info_file = config["exp"]["out_info"]
model = config["model"]["model"].split("\n")
forward_outs = config["forward"]["forward_out"].split(",")
forward_normalize_post = list(map(strtobool, config["forward"]["normalize_posteriors"].split(",")))
forward_count_files = config["forward"]["normalize_with_counts_from"].split(",")
require_decodings = list(map(strtobool, config["forward"]["require_decoding"].split(",")))
save_gpumem = strtobool(config["exp"]["save_gpumem"])
is_production = strtobool(config["exp"]["production"])
batch_size = _get_batch_size_from_config(config, to_do)
if processed_first:
shared_list = list()
p = read_next_chunk_into_shared_list_with_subprocess(
read_lab_fea, shared_list, cfg_file, is_production, output_folder, wait_for_process=True
)
data_name, data_end_index_fea, data_end_index_lab, fea_dict, lab_dict, arch_dict, data_set_dict = extract_data_from_shared_list(
shared_list
)
data_set_inp, data_set_ref = convert_numpy_to_torch(data_set_dict, save_gpumem, use_cuda)
else:
data_set_inp = data_set["input"]
data_set_ref = data_set["ref"]
data_end_index_fea = data_end_index["fea"]
data_end_index_lab = data_end_index["lab"]
shared_list = list()
data_loading_process = None
if not next_config_file is None:
data_loading_process = read_next_chunk_into_shared_list_with_subprocess(
read_lab_fea, shared_list, next_config_file, is_production, output_folder, wait_for_process=False
)
nns, costs, optimizers, inp_out_dict = _load_model_and_optimizer(
fea_dict, model, config, arch_dict, use_cuda, multi_gpu, to_do
)
if to_do == "forward":
post_file = _open_forward_output_files_and_get_file_handles(
forward_outs, require_decodings, info_file, output_folder
)
seq_model = is_sequential_dict(config, arch_dict)
N_snt, N_ex_tr, N_batches = _get_batch_config(data_set_inp, seq_model, to_do, data_name, batch_size)
beg_batch = 0
end_batch = batch_size
snt_index = 0
beg_snt_fea = 0
beg_snt_lab = 0
arr_snt_len_fea = shift(shift(data_end_index_fea, -1, 0) - data_end_index_fea, 1, 0)
arr_snt_len_lab = shift(shift(data_end_index_lab, -1, 0) - data_end_index_lab, 1, 0)
arr_snt_len_fea[0] = data_end_index_fea[0]
arr_snt_len_lab[0] = data_end_index_lab[0]
data_set_inp_dim, data_set_ref_dim = _get_dim_from_data_set(data_set_inp, data_set_ref)
inp_dim = data_set_inp_dim + data_set_ref_dim
loss_sum = 0
err_sum = 0
start_time = time.time()
for i in range(N_batches):
inp, ref, max_len_fea, max_len_lab, snt_len_fea, snt_len_lab, beg_snt_fea, beg_snt_lab, snt_index = _prepare_input(
snt_index,
batch_size,
data_set_inp_dim,
data_set_ref_dim,
beg_snt_fea,
beg_snt_lab,
data_end_index_fea,
data_end_index_lab,
beg_batch,
end_batch,
seq_model,
arr_snt_len_fea,
arr_snt_len_lab,
data_set_inp,
data_set_ref,
use_cuda,
)
if to_do == "train":
outs_dict = forward_model(
fea_dict,
lab_dict,
arch_dict,
model,
nns,
costs,
inp,
ref,
inp_out_dict,
max_len_fea,
max_len_lab,
batch_size,
to_do,
forward_outs,
)
_optimization_step(optimizers, outs_dict, config, arch_dict)
else:
with torch.no_grad():
outs_dict = forward_model(
fea_dict,
lab_dict,
arch_dict,
model,
nns,
costs,
inp,
ref,
inp_out_dict,
max_len_fea,
max_len_lab,
batch_size,
to_do,
forward_outs,
)
if to_do == "forward":
for out_id in range(len(forward_outs)):
out_save = outs_dict[forward_outs[out_id]].data.cpu().numpy()
if forward_normalize_post[out_id]:
counts = load_counts(forward_count_files[out_id])
out_save = out_save - np.log(counts / np.sum(counts))
write_mat(output_folder, post_file[forward_outs[out_id]], out_save, data_name[i])
else:
loss_sum = loss_sum + outs_dict["loss_final"].detach()
err_sum = err_sum + outs_dict["err_final"].detach()
beg_batch = end_batch
end_batch = beg_batch + batch_size
_update_progress_bar(to_do, i, N_batches, loss_sum)
elapsed_time_chunk = time.time() - start_time
loss_tot = loss_sum / N_batches
err_tot = err_sum / N_batches
del inp, ref, outs_dict, data_set_inp_dim, data_set_ref_dim
_save_model(to_do, nns, multi_gpu, optimizers, info_file, arch_dict)
if to_do == "forward":
for out_name in forward_outs:
post_file[out_name].close()
_write_info_file(info_file, to_do, loss_tot, err_tot, elapsed_time_chunk)
if not data_loading_process is None:
data_loading_process.join()
data_name, data_end_index_fea, data_end_index_lab, fea_dict, lab_dict, arch_dict, data_set_dict = extract_data_from_shared_list(
shared_list
)
data_set_inp, data_set_ref = convert_numpy_to_torch(data_set_dict, save_gpumem, use_cuda)
data_set = {"input": data_set_inp, "ref": data_set_ref}
data_end_index = {"fea": data_end_index_fea, "lab": data_end_index_lab}
return [data_name, data_set, data_end_index, fea_dict, lab_dict, arch_dict]
else:
return [None, None, None, None, None, None]
def run_nn(
data_name, data_set, data_end_index, fea_dict, lab_dict, arch_dict, cfg_file, processed_first, next_config_file
):
# This function processes the current chunk using the information in cfg_file. In parallel, the next chunk is load into the CPU memory
# Reading chunk-specific cfg file (first argument-mandatory file)
if not (os.path.exists(cfg_file)):
sys.stderr.write("ERROR: The config file %s does not exist!\n" % (cfg_file))
sys.exit(0)
else:
config = configparser.ConfigParser()
config.read(cfg_file)
# Setting torch seed
seed = int(config["exp"]["seed"])
torch.manual_seed(seed)
random.seed(seed)
np.random.seed(seed)
# Reading config parameters
output_folder = config["exp"]["out_folder"]
use_cuda = strtobool(config["exp"]["use_cuda"])
multi_gpu = strtobool(config["exp"]["multi_gpu"])
to_do = config["exp"]["to_do"]
info_file = config["exp"]["out_info"]
model = config["model"]["model"].split("\n")
forward_outs = config["forward"]["forward_out"].split(",")
forward_normalize_post = list(map(strtobool, config["forward"]["normalize_posteriors"].split(",")))
forward_count_files = config["forward"]["normalize_with_counts_from"].split(",")
require_decodings = list(map(strtobool, config["forward"]["require_decoding"].split(",")))
use_cuda = strtobool(config["exp"]["use_cuda"])
save_gpumem = strtobool(config["exp"]["save_gpumem"])
is_production = strtobool(config["exp"]["production"])
if to_do == "train":
batch_size = int(config["batches"]["batch_size_train"])
if to_do == "valid":
batch_size = int(config["batches"]["batch_size_valid"])
if to_do == "forward":
batch_size = 1
# ***** Reading the Data********
if processed_first:
# Reading all the features and labels for this chunk
shared_list = []
p = threading.Thread(target=read_lab_fea, args=(cfg_file, is_production, shared_list, output_folder))
p.start()
p.join()
data_name = shared_list[0]
data_end_index = shared_list[1]
fea_dict = shared_list[2]
lab_dict = shared_list[3]
arch_dict = shared_list[4]
data_set = shared_list[5]
# converting numpy tensors into pytorch tensors and put them on GPUs if specified
if not (save_gpumem) and use_cuda:
data_set = torch.from_numpy(data_set).float().cuda()
else:
data_set = torch.from_numpy(data_set).float()
# Reading all the features and labels for the next chunk
shared_list = []
p = threading.Thread(target=read_lab_fea, args=(next_config_file, is_production, shared_list, output_folder))
p.start()
# Reading model and initialize networks
inp_out_dict = fea_dict
[nns, costs] = model_init(inp_out_dict, model, config, arch_dict, use_cuda, multi_gpu, to_do)
# optimizers initialization
optimizers = optimizer_init(nns, config, arch_dict)
# pre-training and multi-gpu init
for net in nns.keys():
pt_file_arch = config[arch_dict[net][0]]["arch_pretrain_file"]
if pt_file_arch != "none":
if use_cuda:
checkpoint_load = torch.load(pt_file_arch)
else:
checkpoint_load = torch.load(pt_file_arch, map_location="cpu")
nns[net].load_state_dict(checkpoint_load["model_par"])
optimizers[net].load_state_dict(checkpoint_load["optimizer_par"])
optimizers[net].param_groups[0]["lr"] = float(
config[arch_dict[net][0]]["arch_lr"]
) # loading lr of the cfg file for pt
if multi_gpu:
nns[net] = torch.nn.DataParallel(nns[net])
if to_do == "forward":
post_file = {}
for out_id in range(len(forward_outs)):
if require_decodings[out_id]:
out_file = info_file.replace(".info", "_" + forward_outs[out_id] + "_to_decode.ark")
else:
out_file = info_file.replace(".info", "_" + forward_outs[out_id] + ".ark")
post_file[forward_outs[out_id]] = open_or_fd(out_file, output_folder, "wb")
# check automatically if the model is sequential
seq_model = is_sequential_dict(config, arch_dict)
# ***** Minibatch Processing loop********
if seq_model or to_do == "forward":
N_snt = len(data_name)
N_batches = int(N_snt / batch_size)
else:
N_ex_tr = data_set.shape[0]
N_batches = int(N_ex_tr / batch_size)
beg_batch = 0
end_batch = batch_size
snt_index = 0
beg_snt = 0
start_time = time.time()
# array of sentence lengths
arr_snt_len = shift(shift(data_end_index, -1, 0) - data_end_index, 1, 0)
arr_snt_len[0] = data_end_index[0]
loss_sum = 0
err_sum = 0
inp_dim = data_set.shape[1]
for i in range(N_batches):
max_len = 0
if seq_model:
max_len = int(max(arr_snt_len[snt_index : snt_index + batch_size]))
inp = torch.zeros(max_len, batch_size, inp_dim).contiguous()
for k in range(batch_size):
snt_len = data_end_index[snt_index] - beg_snt
N_zeros = max_len - snt_len
# Appending a random number of initial zeros, tge others are at the end.
N_zeros_left = random.randint(0, N_zeros)
# randomizing could have a regularization effect
inp[N_zeros_left : N_zeros_left + snt_len, k, :] = data_set[beg_snt : beg_snt + snt_len, :]
beg_snt = data_end_index[snt_index]
snt_index = snt_index + 1
else:
# features and labels for batch i
if to_do != "forward":
inp = data_set[beg_batch:end_batch, :].contiguous()
else:
snt_len = data_end_index[snt_index] - beg_snt
inp = data_set[beg_snt : beg_snt + snt_len, :].contiguous()
beg_snt = data_end_index[snt_index]
snt_index = snt_index + 1
# use cuda
if use_cuda:
inp = inp.cuda()
if to_do == "train":
# Forward input, with autograd graph active
outs_dict = forward_model(
fea_dict,
lab_dict,
arch_dict,
model,
nns,
costs,
inp,
inp_out_dict,
max_len,
batch_size,
to_do,
forward_outs,
)
for opt in optimizers.keys():
optimizers[opt].zero_grad()
outs_dict["loss_final"].backward()
# Gradient Clipping (th 0.1)
# for net in nns.keys():
# torch.nn.utils.clip_grad_norm_(nns[net].parameters(), 0.1)
for opt in optimizers.keys():
if not (strtobool(config[arch_dict[opt][0]]["arch_freeze"])):
optimizers[opt].step()
else:
with torch.no_grad(): # Forward input without autograd graph (save memory)
outs_dict = forward_model(
fea_dict,
lab_dict,
arch_dict,
model,
nns,
costs,
inp,
inp_out_dict,
max_len,
batch_size,
to_do,
forward_outs,
)
if to_do == "forward":
for out_id in range(len(forward_outs)):
out_save = outs_dict[forward_outs[out_id]].data.cpu().numpy()
if forward_normalize_post[out_id]:
# read the config file
counts = load_counts(forward_count_files[out_id])
out_save = out_save - np.log(counts / np.sum(counts))
# save the output
write_mat(output_folder, post_file[forward_outs[out_id]], out_save, data_name[i])
else:
loss_sum = loss_sum + outs_dict["loss_final"].detach()
err_sum = err_sum + outs_dict["err_final"].detach()
# update it to the next batch
beg_batch = end_batch
end_batch = beg_batch + batch_size
# Progress bar
if to_do == "train":
status_string = (
"Training | (Batch "
+ str(i + 1)
+ "/"
+ str(N_batches)
+ ")"
+ " | L:"
+ str(round(loss_sum.cpu().item() / (i + 1), 3))
)
if i == N_batches - 1:
status_string = "Training | (Batch " + str(i + 1) + "/" + str(N_batches) + ")"
if to_do == "valid":
status_string = "Validating | (Batch " + str(i + 1) + "/" + str(N_batches) + ")"
if to_do == "forward":
status_string = "Forwarding | (Batch " + str(i + 1) + "/" + str(N_batches) + ")"
progress(i, N_batches, status=status_string)
elapsed_time_chunk = time.time() - start_time
loss_tot = loss_sum / N_batches
err_tot = err_sum / N_batches
# clearing memory
del inp, outs_dict, data_set
# save the model
if to_do == "train":
for net in nns.keys():
checkpoint = {}
if multi_gpu:
checkpoint["model_par"] = nns[net].module.state_dict()
else:
checkpoint["model_par"] = nns[net].state_dict()
checkpoint["optimizer_par"] = optimizers[net].state_dict()
out_file = info_file.replace(".info", "_" + arch_dict[net][0] + ".pkl")
torch.save(checkpoint, out_file)
if to_do == "forward":
for out_name in forward_outs:
post_file[out_name].close()
# Write info file
with open(info_file, "w") as text_file:
text_file.write("[results]\n")
if to_do != "forward":
text_file.write("loss=%s\n" % loss_tot.cpu().numpy())
text_file.write("err=%s\n" % err_tot.cpu().numpy())
text_file.write("elapsed_time_chunk=%f\n" % elapsed_time_chunk)
text_file.close()
# Getting the data for the next chunk (read in parallel)
p.join()
data_name = shared_list[0]
data_end_index = shared_list[1]
fea_dict = shared_list[2]
lab_dict = shared_list[3]
arch_dict = shared_list[4]
data_set = shared_list[5]
# converting numpy tensors into pytorch tensors and put them on GPUs if specified
if not (save_gpumem) and use_cuda:
data_set = torch.from_numpy(data_set).float().cuda()
else:
data_set = torch.from_numpy(data_set).float()
return [data_name, data_set, data_end_index, fea_dict, lab_dict, arch_dict]