-
Notifications
You must be signed in to change notification settings - Fork 11
/
model.py
executable file
·1842 lines (1760 loc) · 67.3 KB
/
model.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
# Copyright 2020-2023 Xupeng Chen, Ran Wang
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""audio to audio and ecog to audio pipeline with loss functions"""
from networks import *
import numpy as np
from torch.nn import functional as F
from metrics.torch_stoi import NegSTOILoss
cumsum = torch.cumsum
def compdiff(comp):
'''smoothness loss'''
return ((comp[:, :, 1:] - comp[:, :, :-1]).abs()).mean()
def compdiffd2(comp):
diff = comp[:, :, 1:] - comp[:, :, :-1]
return ((diff[:, :, 1:] - diff[:, :, :-1]).abs()).mean()
def diff_dim(data, axis=1):
if axis == 1:
data = F.pad(data, (0, 0, 1, 0))
return data[:, 1:] - data[:, :-1]
elif axis == 2:
data = F.pad(data, (1, 0, 0, 0))
return data[:, :, 1:] - data[:, :, :-1]
def safe_divide(numerator, denominator, eps=1e-7):
"""Avoid dividing by zero by adding a small epsilon."""
safe_denominator = torch.where(
denominator == 0.0, eps, denominator.double()
).float()
return numerator / safe_denominator
def safe_log(x, eps=1e-5):
"""Avoid taking the log of a non-positive number."""
# print ('type',type(x),x)
safe_x = torch.where(x <= eps, eps, x.double())
return torch.log(safe_x).float()
def safe_log_(x, eps=1e-5):
"""Avoid taking the log of a non-positive number."""
print("type", type(x))
safe_x = torch.where(x <= eps, eps, x)
return torch.log(safe_x)
def logb(x, base=2.0, safe=True):
"""Logarithm with base as an argument."""
if safe:
return safe_divide(safe_log(x), safe_log(torch.tensor([base])))
else:
return torch.log(x) / torch.log(base)
def hz_to_midi(frequencies):
"""Torch-compatible hz_to_midi function."""
notes = 12.0 * (logb(frequencies, 2.0) - logb(torch.tensor([440.0]), 2.0)) + 69.0
# Map 0 Hz to MIDI 0 (Replace -inf MIDI with 0.)
notes = torch.where(torch.less_equal(frequencies, 0.0), 0.0, notes.double())
return notes.float()
def piecewise_linear(epoch, start_decay=20, end_decay=40):
if epoch < start_decay:
return 1
elif start_decay <= epoch < end_decay:
return 1 / (start_decay - end_decay) * epoch + 2
else:
return 0
def minmaxscale(data, quantile=0.9):
# for frequency scaling
if quantile is not None:
datamax = torch.quantile(data, quantile)
data = torch.clip(data, -10e10, datamax)
minv = data.min()
maxv = data.max()
if minv == maxv:
return data
else:
return (data - minv) / (maxv - minv)
def minmaxscale_ref(data, data_select, quantile=0.9):
# for noise scale
# data_select: a reference data, eg only true noise part
if quantile is not None:
datamax = torch.quantile(data_select, quantile)
data_select = torch.clip(data_select, -10e10, datamax)
minv = data_select.min()
maxv = data_select.max()
data = torch.clip(data, -10e10, datamax)
# print (minv,maxv,maxv - minv)
if minv == maxv:
return data
else:
return (data - minv) / (maxv - minv)
def df_norm_torch(amp):
amp_db = torchaudio.transforms.AmplitudeToDB()(amp)
amp_db_norm = (amp_db.clamp(min=-70) + 70) / 50
return amp_db, amp_db_norm
class GHMR(nn.Module):
def __init__(self, mu=0.02, bins=30, momentum=0, loss_weight=1.0):
super(GHMR, self).__init__()
"""
explained in Gradient Harmonized Single-stage Detector: https://arxiv.org/pdf/1811.05181.pdf
balance the training process in object detection and other tasks
especially for datasets with imbalanced distributions of object classes and difficulties.
"""
self.mu = mu
self.bins = bins
self.edges = [float(x) / bins for x in range(bins + 1)]
self.edges[-1] = 1e3
self.momentum = momentum
if momentum > 0:
self.acc_sum = [0.0 for _ in range(bins)]
self.loss_weight = loss_weight
def forward(self, pred, target, label_weight, avg_factor=None, reweight=1):
"""Args:
pred [batch_num, 4 (* class_num)]:
The prediction of box regression layer. Channel number can be 4 or
(4 * class_num) depending on whether it is class-agnostic.
target [batch_num, 4 (* class_num)]:
The target regression values with the same size of pred.
label_weight [batch_num, 4 (* class_num)]:
The weight of each sample, 0 if ignored.
"""
mu = self.mu
edges = self.edges
mmt = self.momentum
# ASL1 loss
diff = pred - target
loss = torch.sqrt(diff * diff + mu * mu) - mu
# gradient length
g = torch.abs(diff / torch.sqrt(mu * mu + diff * diff)).detach()
weights = torch.zeros_like(g)
valid = label_weight > 0
tot = max(label_weight.float().sum().item(), 1.0)
n = 0 # n: valid bins
for i in range(self.bins):
inds = (g >= edges[i]) & (g < edges[i + 1]) & valid
num_in_bin = inds.sum().item()
if num_in_bin > 0:
n += 1
if mmt > 0:
self.acc_sum[i] = mmt * self.acc_sum[i] + (1 - mmt) * num_in_bin
weights[inds] = tot / self.acc_sum[i]
else:
weights[inds] = tot / num_in_bin
if n > 0:
weights /= n
loss = loss * weights
loss = (loss * reweight).sum() / tot
return loss * self.loss_weight
class STOI_Loss(nn.Module):
def __init__(self, extended=False, plus=True, FFT_size=256):
super(STOI_Loss, self).__init__()
"""
Differentiable Short-Time Objective Intelligibility (STOI) Loss
https://ieeexplore.ieee.org/document/5495701
Detailed in metrics.torch_stoi
"""
self.loss_func = NegSTOILoss(
sample_rate=16000, extended=extended, plus=plus, FFT_size=FFT_size
)
def forward(self, rec_amp, spec_amp, on_stage, suffix="stoi", tracker=None):
stoi_loss = self.loss_func(rec_amp, spec_amp, on_stage).mean()
tracker.update(dict({"Lae_" + suffix: stoi_loss}))
return stoi_loss
def MTF_pytorch(S):
"""
Compute the Modulation Transfer Function (MTF) of a spectrogram.
Then we could use it to compute the MTF loss between original and reconstructed spectrogram.
"""
# S is linear spectrogram
F = torch.fft.fftshift(
torch.log(torch.abs(torch.fft.fft2(torch.log(torch.abs(S)))))
)
# 128, 256
F_tmp = F[
:,
:,
F.shape[2] // 2 - 15 : F.shape[2] // 2 + 15,
5 : F.shape[3] // 2,
]
F_horizontal = F_tmp[:, :, :, -10:] * 2
F_vertical = F_tmp[:, :, F_tmp.shape[2] // 2 - 5 : F_tmp.shape[2] // 2 + 5] * 2
return F_tmp, F_horizontal, F_vertical
class Model(nn.Module):
def __init__(
self,
generator="",
encoder="",
ecog_decoder_name="",
spec_chans=128,
n_formants=2,
n_formants_noise=2,
n_formants_ecog=2,
n_fft=256,
noise_db=-50,
max_db=22.5,
wavebased=False,
with_ecog=False,
with_encoder2=False,
ghm_loss=True,
power_synth=True,
apply_flooding=False,
normed_mask=False,
dummy_formant=False,
Visualize=False,
key=None,
index=None,
A2A=False,
do_mel_guide=True,
noise_from_data=False,
specsup=True,
causal=False,
anticausal=False,
pre_articulate=False,
alpha_sup=False,
ld_loss_weight=True,
alpha_loss_weight=True,
consonant_loss_weight=True,
component_regression=False,
amp_formant_loss_weight=True,
freq_single_formant_loss_weight=True,
amp_minmax=False,
distill=False,
amp_energy=False,
network_db=False,
f0_midi=False,
alpha_db=False,
delta_time=False,
delta_freq=False,
cumsum=False,
learned_mask=False,
n_filter_samples=40,
dynamic_filter_shape=False,
learnedbandwidth=False,
patient="HB02",
rdropout=0, #https://arxiv.org/abs/2106.14448
return_filtershape=False,
spec_fr=125,
gender_patient="Female",
reverse_order=True,
larger_capacity=False,
unified=False,
use_stoi=False
):
super(Model, self).__init__()
self.component_regression = component_regression
self.use_stoi = use_stoi
self.amp_minmax = amp_minmax
self.amp_energy = amp_energy
self.f0_midi = f0_midi
self.alpha_db = alpha_db
self.ld_loss_weight = ld_loss_weight
self.freq_single_formant_loss_weight = freq_single_formant_loss_weight
self.amp_formant_loss_weight = amp_formant_loss_weight
self.alpha_loss_weight = alpha_loss_weight
self.consonant_loss_weight = consonant_loss_weight
self.spec_chans = spec_chans
self.with_ecog = with_ecog
self.with_encoder2 = with_encoder2
self.ecog_decoder_name = ecog_decoder_name
self.n_formants_ecog = n_formants_ecog
self.n_formants = n_formants
self.wavebased = wavebased
self.n_fft = n_fft
self.n_mels = spec_chans
self.do_mel_guide = do_mel_guide
self.noise_db = noise_db
self.spec_sup = specsup
self.max_db = max_db
self.n_formants_noise = n_formants_noise
self.power_synth = power_synth
self.apply_flooding = apply_flooding
self.Visualize = Visualize
self.key = key
self.index = index
self.A2A = A2A
self.return_value = True
self.alpha_sup = alpha_sup
self.return_guide = False
self.delta_time = delta_time
self.delta_freq = delta_freq
self.cumsum = cumsum
self.distill = distill
self.patient = patient
self.rdropout = rdropout
self.return_cc = False
self.cc_method = "None"
self.noise_from_data = noise_from_data
self.weighted_vis = True
self.return_filtershape = return_filtershape
self.formant_freq_limits_abs = torch.tensor(
[950.0, 3400.0, 3800.0, 5000.0, 6000.0, 7000.0]
).reshape(
[1, 6, 1]
) # freq difference
self.formant_freq_limits_abs_low = torch.tensor(
[300.0, 700.0, 1800.0, 3400, 5000.0, 6000.0]
).reshape(
[1, 6, 1]
) # freq difference
print("patient in model", patient)
self.decoder = GENERATORS[generator](
n_mels=spec_chans,
k=40,
wavebased=wavebased,
n_fft=n_fft,
noise_db=noise_db,
max_db=max_db,
noise_from_data=noise_from_data,
return_wave=False,
power_synth=power_synth,
n_formants=n_formants,
normed_mask=normed_mask,
dummy_formant=dummy_formant,
learned_mask=learned_mask,
n_filter_samples=n_filter_samples,
dynamic_filter_shape=dynamic_filter_shape,
learnedbandwidth=learnedbandwidth,
return_filtershape=return_filtershape,
spec_fr=spec_fr,
reverse_order=reverse_order
)
if do_mel_guide:
self.decoder_mel = GENERATORS[generator](
n_mels=spec_chans,
k=40,
wavebased=False,
n_fft=n_fft,
noise_db=noise_db,
max_db=max_db,
add_bgnoise=False,
)
self.encoder = ENCODERS[encoder](
n_mels=spec_chans,
n_formants=n_formants,
n_formants_noise=n_formants_noise,
wavebased=wavebased,
hop_length=128,
n_fft=n_fft,
noise_db=noise_db,
max_db=max_db,
power_synth=power_synth,
patient=patient,
gender_patient=gender_patient,
larger_capacity=larger_capacity,
unified=unified,
)
if with_ecog:
self.ecog_decoder = ECOG_DECODER[ecog_decoder_name](
n_mels=spec_chans,
n_formants=n_formants_ecog,
network_db=network_db,
causal=causal,
anticausal=anticausal,
pre_articulate=pre_articulate,
)
self.ghm_loss = ghm_loss
self.stoi_loss_female = STOI_Loss(extended=False, plus=True, FFT_size=256)
self.stoi_loss_male = STOI_Loss(extended=False, plus=True, FFT_size=512)
def noise_dist_init(self, dist):
with torch.no_grad():
self.decoder.noise_dist = dist.reshape([1, 1, 1, dist.shape[0]])
def generate_fromecog(
self,
ecog=None,
return_components=False,
onstage=None,
):
'''
Use the ECoG decoder to generate speech parameters
and then generate spectrogram using speech synthesizer
'''
components = self.ecog_decoder(ecog)
rec = self.decoder.forward(components, onstage)
if return_components:
return rec, components
else:
return rec
def encode(
self,
spec,
x_denoise=None,
duomask=False,
noise_level=None,
x_amp=None,
gender="Female",
):
'''encode the spectrogram to components using the speech encoder'''
components = self.encoder(
spec,
x_denoise=x_denoise,
duomask=duomask,
noise_level=noise_level if self.noise_from_data else None,
x_amp=x_amp,
gender=gender,
)
return components
def spectrogram_loss(
self,
spec,
rec,
db=True,
amp=True,
tracker=None,
GHM=False,
suffix="",
MTF=False,
reweight = 1
):
"""
given rec, spec as reconstructed and original spectrogram, compute the difference loss including:
1. L2 GHMR loss in dB scale
2. L2 GHMR loss in amp scale
3. delta loss in time domain to smooth neighboring frames
4. delta loss in freq domain to smooth neighboring freqs
5. cumsum loss to ensure more attention to low freqs
6. L2 GHMR loss between MTF of original and reconstructed spectrogram
"""
if amp:
spec_amp = amplitude(spec, noise_db=self.noise_db, max_db=self.max_db)
rec_amp = amplitude(rec, noise_db=self.noise_db, max_db=self.max_db)
spec_amp_ = spec_amp
rec_amp_ = rec_amp
if GHM:
Lae_a = self.ghm_loss(
rec_amp_, spec_amp_, torch.ones(spec_amp_), reweight=reweight
)
Lae_a_l2 = torch.tensor([0.0])
else:
Lae_a = (spec_amp_ - rec_amp_).abs().mean()
Lae_a_l2 = torch.sqrt((spec_amp_ - rec_amp_) ** 2 + 1e-6).mean()
else:
Lae_a = torch.tensor(0.0)
Lae_a_l2 = torch.tensor(0.0)
if tracker is not None:
tracker.update(
dict({"Lae_a" + suffix: Lae_a, "Lae_a_l2" + suffix: Lae_a_l2})
)
if db:
if GHM:
Lae_db = self.ghm_loss(rec, spec, torch.ones(spec), reweight=reweight)
Lae_db_l2 = torch.tensor([0.0])
else:
Lae_db = (spec - rec).abs().mean()
Lae_db_l2 = torch.sqrt((spec - rec) ** 2 + 1e-6).mean()
else:
Lae_db = torch.tensor(0.0)
Lae_db_l2 = torch.tensor(0.0)
if MTF:
spec_amp = amplitude(spec, noise_db=self.noise_db, max_db=self.max_db)
rec_amp = amplitude(rec, noise_db=self.noise_db, max_db=self.max_db)
F_tmp, F_horizontal, F_vertical = MTF_pytorch(spec_amp)
F_tmp_rec, F_horizontal_rec, F_vertical_rec = MTF_pytorch(rec_amp)
Lae_mtf = (
(F_tmp - F_tmp_rec).abs().mean()
+ (F_horizontal - F_horizontal_rec).abs().mean()
+ (F_vertical - F_vertical_rec).abs().mean()
)
else:
Lae_mtf = torch.tensor(0.0)
if self.delta_time:
loss_delta_time = (
(diff_dim(rec_amp, axis=2) - diff_dim(spec_amp, axis=2)).abs().mean()
)
if tracker is not None:
tracker.update(dict({"Lae_delta_time" + suffix: Lae_delta_time}))
else:
loss_delta_time = torch.tensor(0.0)
if self.delta_freq:
loss_delta_freq = (
(diff_dim(rec_amp, axis=1) - diff_dim(spec_amp, axis=1)).abs().mean()
)
if tracker is not None:
tracker.update(dict({"Lae_delta_time" + suffix: loss_delta_freq}))
else:
loss_delta_freq = torch.tensor(0.0)
if self.cumsum:
loss_cumsum = (
(cumsum(rec_amp, axis=1) - cumsum(spec_amp, axis=1)).abs().mean()
)
if tracker is not None:
tracker.update(dict({"Lae_delta_time" + suffix: loss_cumsum}))
else:
loss_cumsum = torch.tensor(0.0)
if tracker is not None:
tracker.update(
dict({"Lae_db" + suffix: Lae_db, "Lae_db_l2" + suffix: Lae_db_l2})
)
return (
Lae_a
+ Lae_db / 2.0
+ Lae_mtf
+ loss_delta_time
+ loss_delta_freq
+ loss_cumsum
)
def flooding(self, loss, beta):
'''flooding loss function https://proceedings.mlr.press/v119/ishida20a/ishida20a.pdf'''
if self.apply_flooding:
return (loss - beta).abs() + beta
else:
return loss
def run_components_loss(
self,
rec,
spec,
tracker,
components_ecog,
components_guide,
alpha,
betas,
on_stage_wider,
on_stage,
):
"""
the core loss function for ECoG to Speech decoding (step2)
calculate component loss with spectrogram encoded components and ECoG decoded components
"""
if self.spec_sup:
'''
original and reconstructed linear spectrogram loss using function `lae`
'''
Lrec = 80 * self.spectrogram_loss(
rec, spec, tracker=tracker, amp=False, suffix="1", MTF=False
)
else:
Lrec = torch.tensor([0.0])
#original and reconstructed mel spectrogram loss using function `lae`
spec_amp = amplitude(spec, self.noise_db, self.max_db).transpose(-2, -1)
rec_amp = amplitude(rec, self.noise_db, self.max_db).transpose(-2, -1)
spec_mel = to_db(
torchaudio.transforms.MelScale(f_max=8000, n_stft=self.n_fft)(
spec_amp
).transpose(-2, -1),
self.noise_db,
self.max_db,
)
rec_mel = to_db(
torchaudio.transforms.MelScale(f_max=8000, n_stft=self.n_fft)(
rec_amp
).transpose(-2, -1),
self.noise_db,
self.max_db,
)
Lrec += 80 * self.spectrogram_loss(rec_mel, spec_mel, tracker=tracker, amp=False, suffix="2")
#stoi loss
if self.use_stoi:
if spec_amp.shape[-2] == 256:
stoi_loss = (
self.stoi_loss_female(
rec_amp, spec_amp, on_stage, suffix="stoi", tracker=tracker
)
* 10
)
else:
stoi_loss = (
self.stoi_loss_male(
rec_amp, spec_amp, on_stage, suffix="stoi", tracker=tracker
)
* 10
)
Lrec += stoi_loss
tracker.update(dict(Lrec=Lrec))
'''
loss function for ECoG to speech paramater decoding
computed between speech to speech encoded guidance speecch parameters
and ECoG decoded speech parameters
'''
Lcomp = 0
# define a bunch of weights for different speech parameters
consonant_weight = 1
if self.power_synth:
loudness_db = torchaudio.transforms.AmplitudeToDB()(
components_guide["loudness"]
)
loudness_db_norm = (loudness_db.clamp(min=-70) + 70) / 50
if self.amp_minmax:
hamon_amp_minmax_weight = (
torch.tensor([2, 5, 4, 0.5, 0.5, 0.5])
.view(1, -1, 1)
.expand_as(components_guide["amplitude_formants_hamon"])
)
amplitude_formants_hamon_db_norm = torch.zeros_like(
components_guide["amplitude_formants_hamon"]
)
for freqs in range(amplitude_formants_hamon_db_norm.shape[1]):
amplitude_formants_hamon_db_norm[:, freqs] = minmaxscale(
components_guide["amplitude_formants_hamon"][:, freqs]
)
amplitude_formants_hamon_db_norm = (
amplitude_formants_hamon_db_norm * hamon_amp_minmax_weight
)
noise_amp_minmax_weight = (
torch.tensor([2, 0.5, 0.5, 0.5, 0.5, 0.5, 10])
.view(1, -1, 1)
.expand_as(components_guide["amplitude_formants_noise"])
)
amplitude_formants_noise_db_norm = torch.zeros_like(
components_guide["amplitude_formants_noise"]
)
for freqs in range(amplitude_formants_noise_db_norm.shape[1]):
amplitude_formants_noise_db_norm[:, freqs] = minmaxscale_ref(
components_guide["amplitude_formants_noise"][:, freqs],
data_select=components_guide["amplitude_formants_noise"][
:, freqs
][
torch.where(
components_guide["amplitudes"][:, 0:1].squeeze(1)
< 0.5
)
],
)
amplitude_formants_noise_db_norm = (
amplitude_formants_noise_db_norm * noise_amp_minmax_weight
)
else:
amplitude_formants_hamon_db = torchaudio.transforms.AmplitudeToDB()(
components_guide["amplitude_formants_hamon"]
)
amplitude_formants_hamon_db_norm = (
amplitude_formants_hamon_db.clamp(min=-70) + 70
) / 50
amplitude_formants_noise_db = torchaudio.transforms.AmplitudeToDB()(
components_guide["amplitude_formants_noise"]
)
amplitude_formants_noise_db_norm = (
amplitude_formants_noise_db.clamp(min=-70) + 70
) / 50
else:
loudness_db = torchaudio.transforms.AmplitudeToDB()(
components_guide["loudness"]
)
loudness_db_norm = (loudness_db.clamp(min=-70) + 70) / 50
if self.amp_minmax:
hamon_amp_minmax_weight = (
torch.tensor([2, 5, 4, 0.5, 0.5, 0.5])
.view(1, -1, 1)
.expand_as(components_guide["amplitude_formants_hamon"])
)
amplitude_formants_hamon_db_norm = torch.zeros_like(
components_guide["amplitude_formants_hamon"]
)
for freqs in range(amplitude_formants_hamon_db_norm.shape[1]):
amplitude_formants_hamon_db_norm[:, freqs] = minmaxscale(
components_guide["amplitude_formants_hamon"][:, freqs]
)
amplitude_formants_hamon_db_norm = (
amplitude_formants_hamon_db_norm * hamon_amp_minmax_weight
)
noise_amp_minmax_weight = (
torch.tensor([2, 0.5, 0.5, 0.5, 0.5, 0.5, 10])
.view(1, -1, 1)
.expand_as(components_guide["amplitude_formants_noise"])
)
amplitude_formants_noise_db_norm = torch.zeros_like(
components_guide["amplitude_formants_noise"]
)
for freqs in range(amplitude_formants_noise_db_norm.shape[1]):
amplitude_formants_noise_db_norm[:, freqs] = minmaxscale_ref(
components_guide["amplitude_formants_noise"][:, freqs],
data_select=components_guide["amplitude_formants_noise"][
:, freqs
][
torch.where(
components_guide["amplitudes"][:, 0:1].squeeze(1)
< 0.5
)
],
)
amplitude_formants_noise_db_norm = (
amplitude_formants_noise_db_norm * noise_amp_minmax_weight
)
else:
amplitude_formants_hamon_db = torchaudio.transforms.AmplitudeToDB()(
components_guide["amplitude_formants_hamon"]
)
amplitude_formants_hamon_db_norm = (
amplitude_formants_hamon_db.clamp(min=-70) + 70
) / 50
amplitude_formants_noise_db = torchaudio.transforms.AmplitudeToDB()(
components_guide["amplitude_formants_noise"]
)
amplitude_formants_noise_db_norm = (
amplitude_formants_noise_db.clamp(min=-70) + 70
) / 50
loudness_db_norm_weight = loudness_db_norm if self.ld_loss_weight else 1
if self.alpha_loss_weight:
alpha_formant_weight = components_guide["amplitudes"][:, 0:1]
alpha_noise_weight = components_guide["amplitudes"][:, 1:2]
else:
alpha_formant_weight = 1
alpha_noise_weight = 1
if self.amp_formant_loss_weight:
amplitude_formants_hamon_db_norm_weight = (
amplitude_formants_hamon_db_norm
)
amplitude_formants_noise_db_norm_weight = (
amplitude_formants_noise_db_norm
)
else:
amplitude_formants_hamon_db_norm_weight = 1
amplitude_formants_noise_db_norm_weight = 1
if self.freq_single_formant_loss_weight:
freq_single_formant_weight = (
torch.tensor([6, 3, 2, 1, 1, 1])
.view(1, -1, 1)
.expand_as(
components_guide["amplitude_formants_hamon"][
:, : self.n_formants_ecog
]
)
)
else:
freq_single_formant_weight = 1
if self.consonant_loss_weight:
consonant_weight = 100 * (
torch.sign(components_guide["amplitudes"][:, 1:] - 0.5) * 0.5 + 0.5
)
else:
consonant_weight = 1
#we calculate the loss for each speech parameter separately
for key in [
"loudness",
"f0_hz",
"amplitudes",
"amplitude_formants_hamon",
"freq_formants_hamon",
"amplitude_formants_noise",
"freq_formants_noise",
"bandwidth_formants_noise_hz",
]:
if key == "loudness":
if self.power_synth:
loudness_db_norm_ecog = (
torchaudio.transforms.AmplitudeToDB()(components_ecog[key])
+ 70
) / 50
else:
loudness_db_norm_ecog = (
torchaudio.transforms.AmplitudeToDB()(components_ecog[key])
+ 70
) / 50
diff = (
alpha["loudness"]
* 150
* torch.mean(
(loudness_db_norm - loudness_db_norm_ecog) ** 2
)
)
tracker.update(
{
"loudness_metric": torch.mean(
(loudness_db_norm - loudness_db_norm_ecog) ** 2
* on_stage_wider
)
}
)
if key == "f0_hz":
if self.f0_midi:
difftmp = (
hz_to_midi(components_guide[key]) / 4
- hz_to_midi(components_ecog[key]) / 4
)
else:
difftmp = (
components_guide[key] / 40
- components_ecog[key] / 40
)
diff = (
alpha["f0_hz"]
* 0.3
* torch.mean(difftmp**2 * on_stage_wider * loudness_db_norm)
)
diff = self.flooding(diff, alpha["f0_hz"] * betas["f0_hz"])
tracker.update(
{
"f0_metric": torch.mean(
(
components_guide["f0_hz"] / 40
- components_ecog["f0_hz"] / 40
)
** 2
* on_stage_wider
* loudness_db_norm
) } )
if key in ["amplitudes"]:
weight = on_stage_wider * loudness_db_norm_weight
tmp_target = components_guide[key]
tmp_ecog = components_ecog[key]
if self.alpha_db:
tmp_target = df_norm_torch(tmp_target)[1]
tmp_ecog = df_norm_torch(tmp_ecog)[1]
if self.ghm_loss:
diff = (
alpha["amplitudes"]
* 540 * self.spectrogram_loss(tmp_target, tmp_ecog, reweight=weight)
)
else:
diff = (
alpha["amplitudes"]
* 180 * torch.mean((tmp_target - tmp_ecog) ** 2 * weight)
)
diff = self.flooding(
diff, alpha["amplitudes"] * betas["amplitudes"]
)
tracker.update(
{
"amplitudes_metric": torch.mean(
(
components_guide["amplitudes"]
- components_ecog["amplitudes"]
) ** 2 * weight
) } )
if key in ["amplitude_formants_hamon"]:
weight = (
alpha_formant_weight
* on_stage_wider
* consonant_weight
* loudness_db_norm_weight
)
if self.amp_energy == 1:
tmp_diff = (
df_norm_torch(
(
components_guide["loudness"].expand_as(
components_guide[key][
:, : self.n_formants_ecog
]
)
* components_guide[key][
:, : self.n_formants_ecog
]
)
)[1]
- df_norm_torch(
(
components_guide["loudness"].expand_as(
components_ecog[key][
:, : self.n_formants_ecog
]
)
* components_ecog[key][
:, : self.n_formants_ecog
]
)
)[1]
) ** 2 * freq_single_formant_weight
elif self.amp_energy == 2:
tmp_diff = (
df_norm_torch(
components_guide[key][:, : self.n_formants_ecog]
)[1]
- df_norm_torch(
components_ecog[key][:, : self.n_formants_ecog]
)[1]
) ** 2 * freq_single_formant_weight
elif self.amp_energy == 3:
tmp_diff = (
df_norm_torch(
components_guide[key][:, : self.n_formants_ecog]
)[1]
- df_norm_torch(
components_ecog[key][:, : self.n_formants_ecog]
)[1]
) ** 2 * freq_single_formant_weight + (
(
components_guide[key][:, : self.n_formants_ecog]
- components_ecog[key][:, : self.n_formants_ecog]
)
** 2
* freq_single_formant_weight
)
else:
tmp_diff = (
components_guide[key][:, : self.n_formants_ecog]
- components_ecog[key][:, : self.n_formants_ecog]
) ** 2 * freq_single_formant_weight
diff = (
alpha["amplitude_formants_hamon"]
* 400
* torch.mean(tmp_diff * weight)
)
diff = self.flooding(
diff,
alpha["amplitude_formants_hamon"]
* betas["amplitude_formants_hamon"],
)
tracker.update(
{
"amplitude_formants_hamon_metric": torch.mean(
(
components_guide["amplitude_formants_hamon"][
:, : self.n_formants_ecog
]
- components_ecog["amplitude_formants_hamon"]
)
** 2
* weight
)
}
)
if key in ["freq_formants_hamon"]:
weight = (
alpha_formant_weight
* on_stage_wider
* consonant_weight
* loudness_db_norm_weight
)
tmp_diff = (
components_guide[key][:, : self.n_formants_ecog]
- components_ecog[key][:, : self.n_formants_ecog]
) ** 2 * freq_single_formant_weight
diff = (
alpha["freq_formants_hamon"]
* 300
* torch.mean(
tmp_diff
* amplitude_formants_hamon_db_norm_weight
* weight
)
)
diff = self.flooding(
diff,
alpha["freq_formants_hamon"] * betas["freq_formants_hamon"],
)
tracker.update(
{
"freq_formants_hamon_hz_metric_2": torch.mean(
(
components_guide["freq_formants_hamon_hz"][:, :2]
/ 400
- components_ecog["freq_formants_hamon_hz"][:, :2]
/ 400
)
** 2
* weight
)
}
)
tracker.update(
{
"freq_formants_hamon_hz_metric_"
+ str(self.n_formants_ecog): torch.mean(
(
components_guide["freq_formants_hamon_hz"][
:, : self.n_formants_ecog
]
/ 400
- components_ecog["freq_formants_hamon_hz"][