-
Notifications
You must be signed in to change notification settings - Fork 0
/
ex_stage2.py
2747 lines (2411 loc) · 114 KB
/
ex_stage2.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
import functools
import os
import sys
from munch import DefaultMunch
import wandb
import random
import numpy as np
from copy import deepcopy
import pandas as pd
from pathlib import Path
from collections import defaultdict
import math
# torch, lightning, huggingface
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torch import autocast
from helpers.scaler import TorchScaler
from torchaudio.transforms import AmplitudeToDB, MelSpectrogram
import torchmetrics
import lightning as L
from lightning.pytorch.loggers import WandbLogger
from lightning.pytorch.callbacks import ModelCheckpoint
import transformers
# models
from models.atst.atst_model_wrapper import ATSTWrapper, ATSTMel
from models.fpasst import fpasst
from models.beats.BEATs_wrapper import BEATsWrapper
from models import preprocess
from models.wrapper import Task4CRNNEmbeddingsWrapper
from helpers.encoder import get_encoder
# data & augmentations
from data_util import t4_24_datasets
from helpers.workersinit import worker_init_fn
from helpers.augment import mixup, frame_shift, gain_augment, time_mask, feature_transformation, mixstyle, RandomResizeCrop
from data_util.classes_dict import classes_labels_desed, classes_labels_maestro_real, \
classes_labels_maestro_real_eval
# config & logging
from configs import add_configs, PRETRAINED_MODELS, DATASET_PATH
from helpers.utils import config_call, register_print_hooks
from sacred import Experiment
from sacred.config_helpers import CMD
from codecarbon import OfflineEmissionsTracker
# evaluation
import sed_scores_eval
from helpers.metrics import (
batched_decode_preds,
compute_per_intersection_macro_f1,
compute_psds_from_operating_points,
compute_psds_from_scores,
log_sedeval_metrics
)
from sed_scores_eval.base_modules.scores import create_score_dataframe, validate_score_dataframe
from helpers.postprocess import ClassWiseMedianFilter
ex = Experiment("dcase24_t4_desed")
# define datasets config
get_training_dataset = ex.command(
t4_24_datasets.get_training_dataset,
prefix="training",
audio_length=10.0,
sample_rate=16000,
weak_split=0.9,
maestro_split=0.9,
seed=42
)
# define datasets config
get_validation_dataset = ex.command(
t4_24_datasets.get_validation_dataset,
prefix="validation",
audio_length=10.0,
sample_rate=16000,
weak_split=0.9,
maestro_split=0.9,
seed=42
)
# define datasets config
get_test_dataset = ex.command(
t4_24_datasets.get_test_dataset,
prefix="test",
audio_length=10.0,
sample_rate=16000
)
get_sampler = ex.command(
t4_24_datasets.get_sampler, prefix="training", batch_sizes=(7, 5, 5, 9, 9)
)
# Define loaders
get_train_loader = ex.command(
DataLoader,
prefix="training",
static_args=dict(worker_init_fn=worker_init_fn),
train=True,
num_workers=16,
shuffle=None,
)
get_validate_loader = ex.command(
DataLoader,
prefix="validation",
static_args=dict(worker_init_fn=worker_init_fn),
batch_size=20,
validate=True,
shuffle=False,
drop_last=False,
num_workers=16,
dataset=CMD("/get_validation_dataset"),
)
get_test_loader = ex.command(
DataLoader,
prefix="test",
static_args=dict(worker_init_fn=worker_init_fn),
batch_size=20,
test=True,
shuffle=False,
drop_last=False,
num_workers=16,
dataset=CMD("/get_test_dataset"),
)
# the config is automatically passed to the objects we create in the following
# this happens via the commands
Trainer = ex.command(L.Trainer, prefix="trainer")
many_hot_encoder = ex.command(get_encoder, prefix="encoder")
## atst
atst_mel = ex.command(ATSTMel, prefix="atst_mel")
## fPaSST
passt_mel = ex.command(preprocess.AugmentMelSTFT, prefix="passt_mel")
passt_net = ex.command(fpasst.get_model, prefix="fpasst")
## crnn
MelSpectrogram = ex.command(MelSpectrogram, prefix="mel")
Task4CRNNEmbeddingsWrapper = ex.command(Task4CRNNEmbeddingsWrapper, prefix="t4_wrapper")
@ex.config
def default_conf():
cmd = " ".join(sys.argv) # command line arguments
process_id = os.getpid()
debug_shapes = 2 # print shapes of in step, 0 = never, 1 = first step etc...
audio_len = 10
sample_rate = 16_000
trainer = dict(
max_epochs=250,
devices=1,
weights_summary="full",
benchmark=True,
num_sanity_val_steps=0,
precision="16-mixed", # NOTE: we train in mixed precision
reload_dataloaders_every_epoch=True,
default_root_dir="./outputs",
accumulate_grad_batches=1,
check_val_every_n_epoch=10
)
optimizer = dict(
cnn_lr=0.0001,
rnn_lr=0.001,
pt_lr=0.0001,
pt_lr_scale=1.0,
pt_trainable_layers="all",
adamw=False,
weight_decay=1e-4,
betas=(0.9, 0.999),
schedule_mode="cos",
num_warmup_steps=270
)
mel = dict(
n_mels=128,
n_fft=2048,
hop_length=256,
win_length=2048,
sample_rate=sample_rate,
f_min=0,
f_max=8000,
window_fn=torch.hamming_window,
wkwargs={"periodic": False},
power=1,
)
passt_mel = dict(
n_mels=128,
sr=16_000,
win_length=400,
hopsize=160,
n_fft=512,
freqm=0,
timem=0,
htk=False,
fmin=0.0,
fmax=None,
norm=1,
fmin_aug_range=10,
fmax_aug_range=1000,
fast_norm=True,
preamp=True,
trainable=False,
padding="center",
periodic_window=True,
)
fpasst = dict(
arch="passt_deit_bd_p16_384",
n_classes=527,
embed_dim=768,
sample_rate=16_000,
pos_embed_length=250,
frame_patchout=0,
in_channels=16,
pretrained_name="passt_as_strong"
)
encoder = dict(
audio_len=10,
frame_len=2048,
frame_hop=256,
net_pooling=4,
fs=sample_rate
)
atst_frame = dict(
pretrained_name="atst_as_strong"
)
t4_wrapper = dict(
name="Task4CRNNEmbeddingsWrapper",
audioset_classes=527,
no_wrapper=False,
dropout=0.5,
n_layers_RNN=2,
n_in_channel=1,
nclass=27,
attention=True,
n_RNN_cell=256,
activation="cg",
rnn_type="BGRU",
kernel_size=[3, 3, 3, 3, 3, 3, 3],
padding=[1, 1, 1, 1, 1, 1, 1],
stride=[1, 1, 1, 1, 1, 1, 1],
nb_filters=[16, 32, 64, 128, 128, 128, 128],
pooling=[[2, 2], [2, 2], [1, 2], [1, 2], [1, 2], [1, 2], [1, 2]],
dropout_recurrent=0,
use_embeddings=True,
embedding_size=768,
embedding_type="frame",
aggregation_type="pool1d",
model_init_id=None
)
beats = dict(
pretrained_name=None
)
training = dict(sample_rate=sample_rate,
include_external_strong=True,
exclude_overlapping=True,
dir_p=0.5,
dir_desed_strong=True,
dir_weak=True,
dir_unlabeled=True,
dir_maestro=True,
wavmix_p=0.5,
wavmix_target="strong",
use_desed_maestro_alias=True,
use_pseudo_labels=True
)
validation = dict(sample_rate=sample_rate)
test = dict(sample_rate=sample_rate)
# maestro, strong real, strong synth, weak, unlabeled (ssl loss), pseudo strong loss (set to 0 in stage 2)
# these loss weights are the results of a (painful) tuning process; they might be far from optimal
loss_weights = (2, 1, 1, 1, 70, 0)
ssl_scale_max = 1.0
ema_factor = 0.999
val_thresholds = [0.5]
# the following dict holds all the paths necessary to load all the different parts of the dataset
base_path = DATASET_PATH
t4_paths = dict(
synth_folder=os.path.join(base_path, "dcase_synth/audio/train/synthetic21_train/soundscapes_16k/"),
synth_folder_44k=os.path.join(base_path, "dcase_synth/audio/train/synthetic21_train/soundscapes/"),
synth_tsv=os.path.join(base_path, "dcase_synth/metadata/train/synthetic21_train/soundscapes.tsv"),
strong_folder=os.path.join(base_path, "audio/train/strong_label_real_16k/"),
strong_folder_44k=os.path.join(base_path, "audio/train/strong_label_real/"),
strong_tsv=os.path.join(base_path, "metadata/train/audioset_strong.tsv"),
external_strong_folder=os.path.join(base_path, "audio/external_strong_16k/"),
external_strong_train_tsv="resources/external_strong_split/external_audioset_strong_train.tsv",
external_strong_val_tsv="resources/external_strong_split/external_audioset_strong_eval.tsv",
external_strong_dur="resources/external_strong_split/external_audioset_strong_dur.tsv",
weak_folder=os.path.join(base_path, "audio/train/weak_16k/"),
weak_folder_44k=os.path.join(base_path, "audio/train/weak/"),
weak_tsv=os.path.join(base_path, "metadata/train/weak.tsv"),
unlabeled_folder=os.path.join(base_path, "audio/train/unlabel_in_domain_16k/"),
unlabeled_folder_44k=os.path.join(base_path, "audio/train/unlabel_in_domain/"),
synth_val_folder=os.path.join(base_path, "audio/validation/synthetic21_validation/soundscapes_16k/"),
synth_val_folder_44k=os.path.join(base_path,
"dcase_synth/audio/validation/synthetic21_validation/soundscapes/"),
synth_val_tsv=os.path.join(base_path, "dcase_synth/metadata/validation/synthetic21_validation/soundscapes.tsv"),
synth_val_dur=os.path.join(base_path, "dcase_synth/metadata/validation/synthetic21_validation/durations.tsv"),
test_folder=os.path.join(base_path, "audio/validation/validation_16k/"),
test_folder_44k=os.path.join(base_path, "audio/validation/validation/"),
test_tsv=os.path.join(base_path, "metadata/validation/validation.tsv"),
test_dur=os.path.join(base_path, "metadata/validation/validation_durations.tsv"),
synth_maestro_train=os.path.join(base_path, "audio/maestro_synth_train_16k"),
synth_maestro_train_44k=os.path.join(base_path, "audio/maestro_synth_train"),
synth_maestro_tsv=os.path.join(base_path, "metadata/maestro_synth_train.tsv"),
real_maestro_train_folder=os.path.join(base_path, "audio/maestro_real_train_16k"),
real_maestro_train_folder_44k=os.path.join(base_path, "audio/maestro_real_train"),
real_maestro_train_tsv=os.path.join(base_path, "metadata/maestro_real_train.tsv"),
real_maestro_val_folder=os.path.join(base_path, "audio/maestro_real_validation_16k"),
real_maestro_val_folder_44k=os.path.join(base_path, "audio/maestro_real_validation"),
real_maestro_val_tsv=os.path.join(base_path, "metadata/maestro_real_validation.tsv"),
real_maestro_val_dur=os.path.join(base_path, "metadata/maestro_real_durations.tsv"),
pseudo_labels=os.path.join("resources", "pseudo-labels/{}.hdf5"),
strong_tsv_exclude=os.path.join("resources/exclude", "audioset_strong_exclude.tsv"),
weak_tsv_exclude=os.path.join("resources/exclude", "weak_exclude.tsv"),
unlabeled_tsv_exclude=os.path.join("resources/exclude", "unlabeled_exclude.tsv"),
eval_public_folder=os.path.join(base_path, "eval/desed_public_eval/audio/eval/public_16k"),
eval_public_tsv=os.path.join(base_path, "eval/desed_public_eval/metadata/eval/public.tsv"),
eval_public_dur=os.path.join(base_path, "eval/desed_public_eval/metadata/eval/public_durations.tsv"),
eval_private_folder=os.path.join(base_path, "eval/eval24/audio_16k"),
eval_private_dur=os.path.join(base_path, "eval/eval24/eval24_durations.tsv")
)
median_window = [3, 9, 9, 5, 5, 5, 9, 7, 11, 9, 7, 3, 9, 13, 7, 1, 13, 3, 13, 7, 5, 5, 1, 13, 17, 13, 15]
test_n_thresholds = 50
gain_augment = 0
filter_augment = dict(
apply=1,
p=0.8,
n_transform=1,
filter_db_range=(-6, 6),
filter_bands=(3, 6),
filter_minimum_bandwidth=6
)
freq_warp = dict(
apply=1,
p=0.5,
include_maestro=False
)
time_augment = dict(
apply_mask=True,
apply_shift=False,
mask_target="desed_strong", # options: "desed strong", "strong", "all"
shift_range=0.075,
shift_target="desed", # options: "all", "desed"
min_mask_ratio=0.05,
max_mask_ratio=0.3,
)
mix_augment = dict(
apply_mixup=True,
apply_mixstyle=True,
mixup_p=0.5,
mixstyle_p=0.5,
mixstyle_alpha=0.3,
mixup_unlabeled=True,
mixup_desed_strong=True,
mixup_maestro=True,
mixup_weak=True,
mixup_max_coef=True,
mixup_desed_maestro=True,
mixstyle_desed_strong=True,
mixstyle_maestro=True,
mixstyle_unlabeled=True,
mixstyle_weak=True,
mixstyle_desed_maestro=True
)
# only a small subset of the configs we tried, e.g.:
# - focal loss types
# - shift-invariant loss types
# - balancing activate/inactive frames and classes via loss weights
# however, we couldn't make these work
loss = dict(
maestro_type="BCELoss",
pseudo_type="BCELoss",
selfsup_type="MSELoss",
harden_labels_maestro_p=0.0,
harden_pseudo_labels_p=0.0
)
# the scaler as used in the baseline system
scaler = dict(
statistic="instance",
normtype="minmax",
dims=(2, 3)
)
# different settings regarding ssl and pseudo loss;
# interestingly, there is no drastic effect in varying these
ssl_loss_warmup_steps = 270
ssl_no_class_mask = False
include_maestro_ssl = True
exclude_maestro_weak_ssl = False
use_ict_loss = True
atst_checkpoint = "atst_as.ckpt"
beats_checkpoint = "beats_as.pt"
add_configs(ex) # add common configurations
# capture the WandbLogger and prefix it with "wandb", this allows to use sacred to update WandbLogger config from the command line
@ex.command(prefix="wandb")
def get_wandb_logger(config, name=None, project="dcase23_task4", offline=False, tags=[]):
rundir = Path(f"./outputs/{project}/")
rundir.mkdir(parents=True, exist_ok=True)
mode = "offline" if offline else "online"
run = wandb.init(name=name, mode=mode, dir=rundir, project=project, config=config, tags=tags)
run.define_metric("trainer/global_step")
run.define_metric("*", step_metric="trainer/global_step", step_sync=True)
logger = WandbLogger(
name=name, offline=offline, dir=rundir, project=project, config=config, tags=tags
)
return logger
# capture optimizer, this allows to set function parameters via command line
@ex.command(prefix="optimizer")
def get_lr_scheduler(
optimizer,
num_training_steps,
schedule_mode="cos",
gamma: float = 0.999996,
num_warmup_steps=270,
lr_end=1e-7,
):
if schedule_mode in {"exp"}:
return torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma)
if schedule_mode in {"cosine", "cos"}:
return transformers.get_cosine_schedule_with_warmup(
optimizer,
num_warmup_steps=num_warmup_steps,
num_training_steps=num_training_steps,
)
if schedule_mode in {"linear"}:
print("Linear schedule!")
return transformers.get_polynomial_decay_schedule_with_warmup(
optimizer,
num_warmup_steps=num_warmup_steps,
num_training_steps=num_training_steps,
power=1.0,
lr_end=lr_end,
)
raise RuntimeError(f"schedule_mode={schedule_mode} Unknown.")
@ex.command(prefix="scaler")
def get_scaler(statistic="instance", normtype="minmax", dims=(2, 3)):
if statistic == "instance":
scaler = TorchScaler(
"instance",
normtype,
dims,
)
return scaler
else:
raise NotImplementedError
def separate_params(model, arch):
cnn_params = []
rnn_params = []
if arch == "fpasst":
pt_params = [[], [], [], [], [], [], [], [], [], [], [], [], [], []]
elif arch == "atst_frame":
pt_params = [[], [], [], [], [], [], [], [], [], [], [], [], [], []]
elif arch == "beats":
pt_params = [[], [], [], [], [], [], [], [], [], [], [], [], [], []]
else:
raise ValueError("Unknown arch: ", arch)
for k, p in model.named_parameters():
if not 'as_model' in k or "as_model.head_linear_layer" in k:
# it is either rnn or cnn
if 'cnn' in k:
cnn_params.append(p)
else:
rnn_params.append(p)
elif arch == "fpasst":
if 'conv_in' in k or 'pos_embed' in k or 'token' in k or 'patch_embed' in k:
pt_params[0].append(p)
elif 'blocks.0' in k:
pt_params[1].append(p)
elif 'blocks.1' in k:
pt_params[2].append(p)
elif 'blocks.2' in k:
pt_params[3].append(p)
elif 'blocks.3' in k:
pt_params[4].append(p)
elif 'blocks.4' in k:
pt_params[5].append(p)
elif 'blocks.5' in k:
pt_params[6].append(p)
elif 'blocks.6' in k:
pt_params[7].append(p)
elif 'blocks.7' in k:
pt_params[8].append(p)
elif 'blocks.8' in k:
pt_params[9].append(p)
elif 'blocks.9' in k:
pt_params[10].append(p)
elif 'blocks.10' in k:
pt_params[11].append(p)
elif 'blocks.11' in k:
pt_params[12].append(p)
elif 'model.norm' in k or 'head_linear' in k or 'rnn' in k or 'sigmoid' in k:
pt_params[13].append(p)
else:
ValueError("Check layer-wise learning for frame-passt!")
elif arch == "atst_frame":
if "blocks.0." in k:
pt_params[1].append(p)
elif "blocks.1." in k:
pt_params[2].append(p)
elif "blocks.2." in k:
pt_params[3].append(p)
elif "blocks.3." in k:
pt_params[4].append(p)
elif "blocks.4." in k:
pt_params[5].append(p)
elif "blocks.5." in k:
pt_params[6].append(p)
elif "blocks.6." in k:
pt_params[7].append(p)
elif "blocks.7." in k:
pt_params[8].append(p)
elif "blocks.8" in k:
pt_params[9].append(p)
elif "blocks.9." in k:
pt_params[10].append(p)
elif "blocks.10." in k:
pt_params[11].append(p)
elif "blocks.11." in k:
pt_params[12].append(p)
elif ".norm_frame." in k or ".rnn." in k or 'head_linear' in k or 'sigmoid_dense' in k:
pt_params[13].append(p)
else:
pt_params[0].append(p)
elif arch == "beats":
if ".layers.0." in k:
pt_params[1].append(p)
elif ".layers.1." in k:
pt_params[2].append(p)
elif ".layers.2." in k:
pt_params[3].append(p)
elif ".layers.3." in k:
pt_params[4].append(p)
elif ".layers.4." in k:
pt_params[5].append(p)
elif ".layers.5." in k:
pt_params[6].append(p)
elif ".layers.6." in k:
pt_params[7].append(p)
elif ".layers.7." in k:
pt_params[8].append(p)
elif ".layers.8." in k:
pt_params[9].append(p)
elif ".layers.9." in k:
pt_params[10].append(p)
elif ".layers.10." in k:
pt_params[11].append(p)
elif ".layers.11." in k:
pt_params[12].append(p)
elif ".norm_frame." in k or ".rnn." in k or 'head_linear' in k or 'sigmoid_dense' in k:
pt_params[13].append(p)
else:
pt_params[0].append(p)
else:
ValueError("Check layer-wise learning implementation!")
return cnn_params, rnn_params, list(reversed(pt_params))
@ex.command(prefix="optimizer")
def get_optimizer(
model, arch, cnn_lr=0.0001, rnn_lr=0.001, pt_lr=0.0001, pt_lr_scale=1.0, pt_trainable_layers="all",
adamw=False, weight_decay=1e-4, betas=[0.9, 0.999]
):
cnn_params, rnn_params, pt_params = separate_params(model, arch)
cnn_param_groups = [
{"params": cnn_params, "lr": cnn_lr}
]
rnn_param_groups = [
{"params": rnn_params, "lr": rnn_lr}
]
pt_trainable_params = []
if pt_trainable_layers == "all":
trainable_layers = len(pt_params)
else:
trainable_layers = pt_trainable_layers
for i in range(trainable_layers):
pt_trainable_params.append(pt_params[i])
for p in pt_params[i]:
p.requires_grad = True
init_lr = pt_lr
lr_scale = pt_lr_scale
scale_lrs = [init_lr * (lr_scale ** i) for i in range(trainable_layers)]
pt_param_groups = [{"params": pt_trainable_params[i], "lr": scale_lrs[i]} for i in
range(len(pt_trainable_params))]
param_groups = cnn_param_groups + rnn_param_groups + pt_param_groups
if adamw:
print(f"\nUsing adamw weight_decay={weight_decay}!\n")
return torch.optim.AdamW(param_groups, weight_decay=weight_decay, betas=betas)
return torch.optim.Adam(param_groups, betas=betas)
class T4Module(L.LightningModule):
def __init__(
self,
config
):
super(T4Module, self).__init__()
config = DefaultMunch.fromDict(config)
self.config = config
self.construct_modules()
for param in self.teacher.parameters():
param.detach_()
self.sample_rate = self.config.sample_rate
self.loss_weights = self.config.loss_weights
self.mix_config = self.config.mix_augment
self.ta_config = self.config.time_augment
self.fa_config = self.config.filter_augment
self.gain_augment = self.config.gain_augment if "gain_augment" in self.config else 0
self.gain_target = self.config.gain_target if "gain_target" in self.config else "all"
self.median_filter = ClassWiseMedianFilter(self.config.median_window)
self.freq_warp = RandomResizeCrop((1, 1.0), time_scale=(1.0, 1.0))
self.fwarp_config = self.config.freq_warp
# for weak labels we simply compute f1 score
self.get_weak_student_f1_seg_macro = torchmetrics.classification.f_beta.MultilabelF1Score(
len(self.encoder.labels),
average="macro"
)
self.get_weak_teacher_f1_seg_macro = torchmetrics.classification.f_beta.MultilabelF1Score(
len(self.encoder.labels),
average="macro"
)
self.val_buffer_sed_scores_eval_student = {}
self.val_buffer_sed_scores_eval_teacher = {}
self.val_buffer_real_sed_scores_eval_student = {}
self.val_buffer_real_sed_scores_eval_teacher = {}
test_n_thresholds = self.config.test_n_thresholds
test_thresholds = np.arange(
1 / (test_n_thresholds * 2), 1, 1 / test_n_thresholds
)
self.test_buffer_psds_eval_student = {k: pd.DataFrame() for k in test_thresholds}
self.test_buffer_psds_eval_teacher = {k: pd.DataFrame() for k in test_thresholds}
self.test_buffer_sed_scores_eval_student = {}
self.test_buffer_sed_scores_eval_teacher = {}
self.test_buffer_sed_scores_eval_unprocessed_student = {}
self.test_buffer_sed_scores_eval_unprocessed_teacher = {}
self.test_buffer_detections_thres05_student = pd.DataFrame()
self.test_buffer_detections_thres05_teacher = pd.DataFrame()
def construct_modules(self):
arch = self.config["arch"]
self.arch = arch
scall = functools.partial(
config_call, config=self.config
)
if arch == "atst_frame":
self.mel = scall(atst_mel)
transformer = ATSTWrapper(os.path.join(PRETRAINED_MODELS, self.config['atst_checkpoint']))
embed_dim = 768
elif arch == "fpasst":
self.mel = scall(passt_mel)
transformer = scall(passt_net)
embed_dim = transformer.num_features
elif arch == "beats":
transformer = BEATsWrapper(cfg_path=os.path.join(PRETRAINED_MODELS, self.config['beats_checkpoint']))
self.mel = transformer.preprocess
embed_dim = 768
else:
raise ValueError(f"Unknown arch={arch}")
self.crnn_mel = scall(MelSpectrogram)
self.scaler = get_scaler()
transformer.arch = arch
if self.config.t4_wrapper.name == "Task4CRNNEmbeddingsWrapper":
self.student = Task4CRNNEmbeddingsWrapper(transformer, audioset_classes=527,
embedding_size=embed_dim, nclass=27,
pretrained_name=self.config[arch]["pretrained_name"],
model_init_mode="student")
else:
raise ValueError(f"Unknown head={self.config.head}")
# teacher is loaded separately from checkpoint
# IMPORTANT - we need a copy of net, otherwise the same object is used in both student and teacher
# which can have unwanted side effects
transformer = deepcopy(transformer)
if self.config.t4_wrapper.name == "Task4CRNNEmbeddingsWrapper":
self.teacher = Task4CRNNEmbeddingsWrapper(transformer, audioset_classes=527,
embedding_size=embed_dim, nclass=27,
pretrained_name=self.config[arch]["pretrained_name"])
else:
raise ValueError(f"Unknown head={self.config.head}")
self.encoder = scall(many_hot_encoder)
# losses
self.strong_loss = nn.BCELoss()
self.weak_loss = nn.BCELoss()
if self.config.loss.maestro_type == "BCELoss":
self.maestro_loss = nn.BCELoss()
elif self.config.loss.maestro_type == "MSELoss":
self.maestro_loss = nn.MSELoss()
else:
raise ValueError(f"Unknown Maestro loss type: {self.config.loss.maestro_type}")
if self.config.loss.selfsup_type == "both":
bce = nn.BCELoss()
mse = nn.MSELoss()
self.selfsup_loss = lambda y_hat, y: (mse(y_hat, y) * 4 + bce(y_hat, y)) / 2
elif self.config.loss.selfsup_type == "BCELoss":
self.selfsup_loss = nn.BCELoss()
elif self.config.loss.selfsup_type == "MSELoss":
self.selfsup_loss = nn.MSELoss()
else:
raise ValueError(f"Unknown Pseudo loss type: {self.config.loss.pseudo_type}")
if self.config.loss.pseudo_type == "both":
bce = nn.BCELoss()
mse = nn.MSELoss()
self.pseudo_label_loss = lambda y_hat, y: (mse(y_hat, y) * 4 + bce(y_hat, y)) / 2
elif self.config.loss.pseudo_type == "BCELoss":
self.pseudo_label_loss = nn.BCELoss()
elif self.config.loss.pseudo_type == "MSELoss":
self.pseudo_label_loss = nn.MSELoss()
else:
raise ValueError(f"Unknown Pseudo loss type: {self.config.loss.pseudo_type}")
def on_train_start(self) -> None:
# for tracking energy consumption
log_path = os.path.join(self.loggers[0].name, self.loggers[0].experiment.id)
os.makedirs(os.path.join(log_path, "codecarbon"), exist_ok=True)
self.tracker_train = OfflineEmissionsTracker(
"DCASE Task 4 Stage 2",
output_dir=os.path.join(log_path, "codecarbon"),
output_file="emissions_stage1.csv",
log_level="warning",
country_iso_code="AUT",
gpu_ids=[torch.cuda.current_device()],
)
self.tracker_train.start()
def on_test_start(self) -> None:
log_path = os.path.join(self.loggers[0].name, self.loggers[0].experiment.id)
os.makedirs(os.path.join(log_path, "codecarbon"), exist_ok=True)
self.tracker_devtest = OfflineEmissionsTracker(
"DCASE Task 4 Stage 2, Test",
output_dir=os.path.join(log_path, "codecarbon"),
output_file="emissions_stage1_test.csv",
log_level="warning",
country_iso_code="AUT",
gpu_ids=[torch.cuda.current_device()],
)
self.tracker_devtest.start()
def on_train_end(self) -> None:
# dump consumption
self.tracker_train.stop()
training_kwh = self.tracker_train._total_energy.kWh
self.loggers[0].experiment.log({"train/tot_energy_kWh": torch.tensor(float(training_kwh))})
def update_ema(self, alpha, global_step, model, ema_model):
""" Update teacher model parameters
Args:
alpha: float, the factor to be used between each updated step.
global_step: int, the current global step to be used.
model: torch.Module, student model to use
ema_model: torch.Module, teacher model to use
"""
# Use the true average until the exponential average is more correct
alpha = min(1 - 1 / (global_step + 1), alpha)
for ema_params, params in zip(ema_model.parameters(), model.parameters()):
ema_params.data.mul_(alpha).add_(params.data, alpha=1 - alpha)
def take_log(self, mels):
amp_to_db = AmplitudeToDB(stype="amplitude")
amp_to_db.amin = 1e-5 # amin= 1e-5 as in librosa
return amp_to_db(mels).clamp(min=-50, max=80) # clamp to reproduce old code
def forward_pseudo_labels(self, audio, mode="student"):
model = self.student if mode == "student" else self.teacher
with autocast(enabled=False, device_type='cuda'):
audio = audio.float()
sed_feats = self.crnn_mel(audio).unsqueeze(1)
pt_feats = self.mel(audio)
strong = model(
self.scaler(
self.take_log(sed_feats)
),
pt_feats,
return_strong_logits=True
)
return strong
def detect(self, mel_feats, transformer_feats, model, classes_mask=None):
x = model(
self.scaler(
self.take_log(mel_feats)
),
transformer_feats,
classes_mask=classes_mask
)
return x
def training_step(self, batch, batch_idx):
hooks = []
if self.trainer.global_rank == 0:
hooks = register_print_hooks(
self, register_at_step=self.config.debug_shapes
)
audio, labels, padded_indxs, pseudo_strong, valid_class_mask = batch
pseudo_strong = pseudo_strong.transpose(1, 2)
audio = audio.float()
valid_class_mask = valid_class_mask.bool()
indx_maestro, indx_strong, indx_synth, indx_weak, indx_unlabelled = np.cumsum(self.config.training.batch_sizes)
batch_num = audio.shape[0]
# deriving masks for each dataset
all_strong_mask = torch.zeros(batch_num).to(audio).bool()
maestro_mask = torch.zeros(batch_num).to(audio).bool()
desed_strong_mask = torch.zeros(batch_num).to(audio).bool()
desed_synth_mask = torch.zeros(batch_num).to(audio).bool()
desed_real_strong_mask = torch.zeros(batch_num).to(audio).bool()
weak_mask = torch.zeros(batch_num).to(audio).bool()
ssl_mask = torch.zeros(batch_num).to(audio).bool()
unlabeled_mask = torch.zeros(batch_num).to(audio).bool()
desed_mask = torch.zeros(batch_num).to(audio).bool()
all_strong_mask[:indx_synth] = 1
maestro_mask[:indx_maestro] = 1
desed_strong_mask[indx_maestro:indx_synth] = 1
desed_synth_mask[indx_strong:indx_synth] = 1
desed_real_strong_mask[indx_maestro:indx_strong] = 1
weak_mask[indx_synth:indx_weak] = 1
ssl_mask[indx_maestro:] = 1
unlabeled_mask[indx_weak:] = 1
desed_mask[indx_maestro:] = 1
# calculate ssl loss on Maestro as well
if self.config.include_maestro_ssl:
ssl_mask = torch.ones(batch_num).to(audio).bool()
if self.config.only_maestro_ssl:
ssl_mask[indx_maestro:] = 0
# gain augment
if self.gain_augment > 0:
if self.gain_target == "all":
audio = gain_augment(audio, gain=self.gain_augment)
elif self.gain_target == "desed":
audio[desed_mask] = gain_augment(audio[desed_mask], gain=self.gain_augment)
else:
raise ValueError(f"Unknown gain target: {self.gain_target}")
with autocast(enabled=False, device_type='cuda'):
audio = audio.float()
sed_feats = self.crnn_mel(audio).unsqueeze(1)
pt_feats = self.mel(audio)
# deriving weak labels
labels_weak = (torch.sum(labels[weak_mask], -1) > 0).float()
if self.config.loss.harden_labels_maestro_p > random.random():
labels_maestro_hard = torch.where(labels[maestro_mask] > 0.5, torch.tensor(1.0), torch.tensor(0.0))
labels_maestro_hard = labels_maestro_hard.to(labels.dtype)
labels[maestro_mask] = labels_maestro_hard
if self.config.loss.harden_pseudo_labels_p > random.random():
pseudo_strong = torch.where(pseudo_strong > 0.5, torch.tensor(1.0), torch.tensor(0.0))
pseudo_strong = pseudo_strong.to(labels.dtype)
if self.ta_config.apply_shift:
if self.ta_config.shift_target == "all":
features, pt_feats, labels, pseudo_strong = frame_shift(sed_feats, labels, embeddings=pt_feats,
pseudo_labels=pseudo_strong,
net_pooling=self.encoder.net_pooling,
shift_range=self.ta_config.shift_range)
elif self.ta_config.shift_target == "desed":
sed_feats[desed_mask], pt_feats[desed_mask], labels[desed_mask], pseudo_strong[desed_mask] = \
frame_shift(sed_feats[desed_mask], labels[desed_mask], embeddings=pt_feats[desed_mask],
pseudo_labels=pseudo_strong[desed_mask],
net_pooling=self.encoder.net_pooling,
shift_range=self.ta_config.shift_range)
else:
raise ValueError(f"Unknown shift target: {self.ta_config.shift_target}")
if self.ta_config.apply_mask:
if self.ta_config.mask_target == "desed_strong":
sed_feats[desed_strong_mask], pt_feats[desed_strong_mask], labels[desed_strong_mask], pseudo_strong[desed_strong_mask] = \
time_mask(sed_feats[desed_strong_mask], labels[desed_strong_mask],
embeddings=pt_feats[desed_strong_mask], pseudo_labels=pseudo_strong[desed_strong_mask], net_pooling=self.encoder.net_pooling,
min_mask_ratio=self.ta_config.min_mask_ratio,
max_mask_ratio=self.ta_config.max_mask_ratio)
elif self.ta_config.mask_target == "strong":
sed_feats[all_strong_mask], pt_feats[all_strong_mask], labels[all_strong_mask], pseudo_strong[all_strong_mask] = \
time_mask(sed_feats[all_strong_mask], labels[all_strong_mask],
embeddings=pt_feats[all_strong_mask], pseudo_labels=pseudo_strong[all_strong_mask], net_pooling=self.encoder.net_pooling,
min_mask_ratio=self.ta_config.min_mask_ratio,
max_mask_ratio=self.ta_config.max_mask_ratio)
elif self.ta_config.mask_target == "all":
sed_feats, pt_feats, labels, pseudo_strong = \
time_mask(sed_feats,
labels,
embeddings=pt_feats,
pseudo_labels=pseudo_strong,
net_pooling=self.encoder.net_pooling,
min_mask_ratio=self.ta_config.min_mask_ratio,
max_mask_ratio=self.ta_config.max_mask_ratio)
else:
raise ValueError(f"Unknown value for 'mask_target': {self.ta_config.mask_target}")
sed_feats_org = sed_feats.clone()
pt_feats_org = pt_feats.clone()
if self.mix_config.apply_mixup and self.mix_config.mixup_p > random.random():
if self.mix_config.mixup_weak:
sed_feats[weak_mask], pt_feats[weak_mask], labels_weak, pseudo_strong[
weak_mask], perm_weak, c_weak = mixup(
sed_feats[weak_mask], embeddings=pt_feats[weak_mask], targets=labels_weak, mixup_label_type="soft",
pseudo_strong=pseudo_strong[weak_mask],
return_mix_coef=True, max_coef=self.mix_config.mixup_max_coef
)
if self.mix_config.mixup_desed_maestro and self.mix_config.mixup_desed_strong \
and self.mix_config.mixup_maestro:
sed_feats[all_strong_mask], pt_feats[all_strong_mask], labels[
all_strong_mask], valid_class_mask[all_strong_mask], pseudo_strong[
all_strong_mask], perm_strong, c_strong = mixup(
sed_feats[all_strong_mask], embeddings=pt_feats[all_strong_mask],
valid_class_mask=valid_class_mask[all_strong_mask],
targets=labels[all_strong_mask], pseudo_strong=pseudo_strong[all_strong_mask],
mixup_label_type="soft",
return_mix_coef=True, max_coef=self.mix_config.mixup_max_coef
)
perm_maestro = None
else:
if self.mix_config.mixup_desed_strong:
sed_feats[desed_strong_mask], pt_feats[desed_strong_mask], labels[desed_strong_mask], pseudo_strong[
desed_strong_mask], \
perm_strong, c_strong = mixup(
sed_feats[desed_strong_mask], embeddings=pt_feats[desed_strong_mask],
targets=labels[desed_strong_mask], pseudo_strong=pseudo_strong[desed_strong_mask],
mixup_label_type="soft",
return_mix_coef=True, max_coef=self.mix_config.mixup_max_coef
)
if self.mix_config.mixup_maestro:
sed_feats[maestro_mask], pt_feats[maestro_mask], labels[maestro_mask], pseudo_strong[
maestro_mask], perm_maestro, c_maestro = mixup(
sed_feats[maestro_mask], embeddings=pt_feats[maestro_mask],
targets=labels[maestro_mask], pseudo_strong=pseudo_strong[maestro_mask],
mixup_label_type="soft",
return_mix_coef=True, max_coef=self.mix_config.mixup_max_coef
)