File size: 44,133 Bytes
d4101a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""LuaNovaCFM: PT-BR phonetic front end, ProsodyFlow, and OT-CFM Slaney-100 mel decoder."""
from __future__ import annotations

import math

import torch
from torch import nn
from torch.nn import functional as F

from ..config import CFMConfig, Config
from ..text.phonemizer import PHONE_IDS, PUNCTUATION, SYMBOL_TO_ID, VOICELESS, VOWELS
from .frontend import (
    Predictor,
    Stack,
    UtteranceTooLong,
    VocosHead,
    length_mask,
    rotary_table,
    rotate,
)

_SP_ID = SYMBOL_TO_ID["<sp>"]
_COMMA_ID = SYMBOL_TO_ID[","]
_PERIOD_ID = SYMBOL_TO_ID["."]
_QUESTION_ID = SYMBOL_TO_ID["?"]
_EXCLAM_ID = SYMBOL_TO_ID["!"]
_SEMICOLON_ID = SYMBOL_TO_ID[";"]
_COLON_ID = SYMBOL_TO_ID[":"]
_DASH_ID = SYMBOL_TO_ID["—"]
_ELLIPSIS_ID = SYMBOL_TO_ID["…"]
_CLAUSE_PUNCT_IDS = tuple(SYMBOL_TO_ID[p] for p in (",", ";", ":", "—", "…", ".", "?", "!"))


class MelStatsHead(nn.Module):
    """Lightweight mel normalization statistics container for external vocoders such as BigVGAN."""

    def __init__(self, c: Config) -> None:
        super().__init__()
        self.config = c
        self.vocos = None
        self.frozen = True
        self.register_buffer("mel_mean", torch.zeros(c.vocos_n_mels, dtype=torch.float32))
        self.register_buffer("mel_scale", torch.ones(c.vocos_n_mels, dtype=torch.float32))

    def freeze_vocoder(self, frozen: bool = True) -> None:
        self.frozen = frozen

    def set_mel_stats(self, mean, scale) -> None:
        mean_t = torch.as_tensor(mean, dtype=torch.float32, device=self.mel_mean.device)
        scale_t = torch.as_tensor(scale, dtype=torch.float32, device=self.mel_scale.device).clamp_min(1e-6)
        if mean_t.shape != (self.config.vocos_n_mels,) or scale_t.shape != (self.config.vocos_n_mels,):
            raise ValueError("vocoder mel stats shape mismatch")
        self.mel_mean.copy_(mean_t)
        self.mel_scale.copy_(scale_t)

    def decode_mel(self, mel_norm: torch.Tensor, lengths: torch.Tensor) -> torch.Tensor:
        raise RuntimeError("External BigVGAN vocoder wrapper is required to decode waveforms in BigVGAN mel space")


def make_prosody_noise_kernel(length: int = 25, sigma_wide: float = 5.0, sigma_narrow: float = 1.5) -> torch.Tensor:
    """Kernel 1D multiescala normalizado para variancia unitaria do ruido prosodico [2, 1, K]."""
    half = length // 2
    idx = torch.arange(length, dtype=torch.float32) - float(half)
    g_wide = torch.exp(-0.5 * (idx / sigma_wide) ** 2)
    g_wide = g_wide / g_wide.sum()
    g_narrow = torch.exp(-0.5 * (idx / sigma_narrow) ** 2)
    g_narrow = g_narrow / g_narrow.sum()
    w = 0.65 * g_wide + 0.35 * g_narrow
    w = w / torch.sqrt((w ** 2).sum()).clamp_min(1e-8)
    return w[None, None, :].expand(2, 1, length).contiguous()


def smooth_prosody_noise(eps: torch.Tensor, frame_mask: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:
    """Convolucao multiescala ONNX-safe em ruido gaussiano [B, T, 2] para eliminar micro-jitter de F0."""
    pad = kernel.shape[-1] // 2
    sm = F.conv1d(eps.float().transpose(1, 2), kernel.to(eps.device, dtype=torch.float32), padding=pad, groups=2)
    return sm.transpose(1, 2) * frame_mask[..., None].float()


def linguistic_context_features(

    tokens: torch.Tensor,

    stress: torch.Tensor,

    token_mask: torch.Tensor,

    phone_tokens: torch.Tensor,

    vowel_tokens: torch.Tensor,

    voiceless_tokens: torch.Tensor,

    clause_punct_tokens: torch.Tensor,

) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
    """Extrai 26 canais de contexto palavra/tonica/clausula/frase + matriz same_word (100% ONNX opset 17)."""
    mask_f = token_mask.float()
    is_phone = (phone_tokens[tokens] & token_mask).float()
    is_vowel = (vowel_tokens[tokens] & token_mask).float()
    is_voiceless = (voiceless_tokens[tokens] & token_mask).float()
    is_voiced_cons = is_phone * (1.0 - is_vowel) * (1.0 - is_voiceless)
    is_sp = ((tokens == _SP_ID) & token_mask).float()
    is_cb = (clause_punct_tokens[tokens] & token_mask).float()

    l_dim = tokens.shape[1]
    idx_f = torch.arange(l_dim, device=tokens.device, dtype=torch.float32)[None, :]
    tri_le = (idx_f[:, :, None] >= idx_f[:, None, :]).float()

    # 1..6: Utterance-level structure and punctuation indicators
    utt_len = mask_f.sum(dim=1, keepdim=True).clamp_min(1.0)
    utt_pos = ((idx_f + 0.5) / utt_len) * mask_f
    utt_rem = ((utt_len - 1.0 - idx_f).clamp_min(0.0) / utt_len) * mask_f
    utt_log_len = (torch.log1p(utt_len) / 6.0) * mask_f
    utt_has_q = ((tokens == _QUESTION_ID) & token_mask).float().sum(dim=1, keepdim=True).clamp(0.0, 1.0) * mask_f
    utt_has_ex = ((tokens == _EXCLAM_ID) & token_mask).float().sum(dim=1, keepdim=True).clamp(0.0, 1.0) * mask_f
    utt_has_comma = ((tokens == _COMMA_ID) & token_mask).float().sum(dim=1, keepdim=True).clamp(0.0, 1.0) * mask_f

    # 7..13: Word-level & lexical stress geometry
    is_delim = (1.0 - is_phone) * mask_f
    word_id = is_delim.long().cumsum(dim=1)
    same_word = (word_id[:, :, None] == word_id[:, None, :]).float() * (is_phone[:, :, None] * is_phone[:, None, :])
    word_phones = same_word.sum(dim=-1)
    word_log_phones = (torch.log1p(word_phones) / 4.0) * is_phone
    word_vowels = (same_word * is_vowel[:, None, :]).sum(dim=-1)
    word_log_vowels = (torch.log1p(word_vowels) / 3.0) * is_phone
    is_prim_stress = ((stress == 1) & token_mask).float() * is_phone
    stress_weights = same_word * is_prim_stress[:, None, :]
    stress_sum = stress_weights.sum(dim=-1)
    word_has_stress = stress_sum.clamp(0.0, 1.0) * is_phone
    pos_in_word = (((same_word * tri_le).sum(dim=-1) - 0.5).clamp_min(0.0) / word_phones.clamp_min(1.0)) * is_phone
    stress_idx = (stress_weights * idx_f[None, ...]).sum(dim=-1) / stress_sum.clamp_min(1.0)
    dist_to_stress = ((idx_f - stress_idx) / 6.0).clamp(-2.0, 2.0) * word_has_stress

    prev_phone = torch.cat((torch.zeros_like(is_phone[:, :1]), is_phone[:, :-1]), dim=1)
    word_start = is_phone * (1.0 - prev_phone)
    total_words = word_start.sum(dim=1, keepdim=True).clamp_min(1.0)
    cum_words = word_start.cumsum(dim=1)
    word_pos_utt = ((cum_words - 0.5).clamp_min(0.0) / total_words) * is_phone
    log_total_words = (torch.log1p(total_words) / 4.0) * mask_f

    # 14..21: Clause-level structure (segmented at , ; : — … . ? !)
    cb_prev = torch.cat((torch.zeros_like(is_cb[:, :1]), is_cb[:, :-1]), dim=1)
    clause_id = cb_prev.long().cumsum(dim=1)
    same_clause = (clause_id[:, :, None] == clause_id[:, None, :]).float() * (mask_f[:, :, None] * mask_f[:, None, :])
    clause_len = same_clause.sum(dim=-1).clamp_min(1.0)
    clause_log_len = (torch.log1p(clause_len) / 5.0) * mask_f
    pos_in_clause_raw = (same_clause * tri_le).sum(dim=-1)
    pos_in_clause = ((pos_in_clause_raw - 0.5).clamp_min(0.0) / clause_len) * mask_f
    clause_rem = ((clause_len - pos_in_clause_raw).clamp_min(0.0) / clause_len) * mask_f

    q_tok = ((tokens == _QUESTION_ID) & token_mask).float()
    ex_tok = ((tokens == _EXCLAM_ID) & token_mask).float()
    comma_tok = ((tokens == _COMMA_ID) & token_mask).float()
    period_tok = ((tokens == _PERIOD_ID) & token_mask).float()
    other_cb_tok = (
        ((tokens == _SEMICOLON_ID) | (tokens == _COLON_ID) | (tokens == _DASH_ID) | (tokens == _ELLIPSIS_ID))
        & token_mask
    ).float()
    clause_ends_q = (same_clause * q_tok[:, None, :]).sum(dim=-1).clamp(0.0, 1.0) * mask_f
    clause_ends_ex = (same_clause * ex_tok[:, None, :]).sum(dim=-1).clamp(0.0, 1.0) * mask_f
    clause_ends_comma = (same_clause * comma_tok[:, None, :]).sum(dim=-1).clamp(0.0, 1.0) * mask_f
    clause_ends_period = (same_clause * period_tok[:, None, :]).sum(dim=-1).clamp(0.0, 1.0) * mask_f
    clause_ends_other = (same_clause * other_cb_tok[:, None, :]).sum(dim=-1).clamp(0.0, 1.0) * mask_f

    ling_feats = torch.stack(
        (
            utt_pos, utt_rem, utt_log_len, utt_has_q, utt_has_ex, utt_has_comma,
            word_log_phones, word_log_vowels, word_has_stress, pos_in_word, dist_to_stress, word_pos_utt, log_total_words,
            clause_log_len, pos_in_clause, clause_rem,
            clause_ends_q, clause_ends_ex, clause_ends_comma, clause_ends_period, clause_ends_other,
            is_vowel, is_voiced_cons, is_voiceless, is_sp, is_cb,
        ),
        dim=-1,
    ) * mask_f[..., None]
    clause_ctx_tok = torch.stack((pos_in_clause, clause_rem, clause_ends_q, clause_ends_comma), dim=-1) * mask_f[..., None]
    return ling_feats, same_word, clause_ctx_tok


def energy_noise_gate(

    condition: torch.Tensor,

    frame_mask: torch.Tensor,

    center: float = -1.6,

    slope: float = 2.5,

    floor: float = 0.05,

) -> torch.Tensor:
    """Porta suave por energia e vozeamento para zerar ruido inicial em pausas (ONNX opset 17)."""
    eng = condition[..., 2].float()
    voiced = condition[..., 1].float()
    g = torch.sigmoid(slope * (eng - center))
    g = torch.maximum(g, 0.85 * voiced)
    g = floor + (1.0 - floor) * g
    return g[..., None] * frame_mask[..., None].float()


def smooth_f0_channel(condition: torch.Tensor, prob: float) -> torch.Tensor:
    """Aplica filtro caixa 3-frames no canal F0 em uma fracao ``prob`` do batch."""
    if prob <= 0.0 or condition.shape[1] < 2:
        return condition
    mask = (torch.rand(condition.shape[0], device=condition.device) < prob)[:, None]
    if not bool(mask.any()):
        return condition
    f0 = condition[..., 0].float()
    sm = F.avg_pool1d(F.pad(f0.unsqueeze(1), (1, 1), mode="replicate"), 3, stride=1).squeeze(1)
    f0_out = torch.where(mask, sm.to(condition.dtype), condition[..., 0])
    return torch.cat((f0_out[..., None], condition[..., 1:]), dim=-1)


def f0_features(condition: torch.Tensor, frame_mask: torch.Tensor) -> torch.Tensor:
    """Extrai 12 canais prosodicos/harmonicos explicitos de ``condition`` [B, T, 3] (100% ONNX opset 17)."""
    c = condition.float()
    log_f0 = c[..., 0]
    voiced = c[..., 1]
    energy = c[..., 2]
    delta_f0 = F.pad(log_f0[:, 1:] - log_f0[:, :-1], (1, 0))
    f0_norm = torch.exp(log_f0.clamp(-2.0, 1.5))
    feats = [log_f0, delta_f0, voiced, energy]
    for k in (1.0, 2.0, 3.0, 4.0):
        ang = (2.0 * math.pi * k) * f0_norm
        feats.append(voiced * torch.sin(ang))
        feats.append(voiced * torch.cos(ang))
    return torch.stack(feats, dim=-1) * frame_mask[..., None].float()


class SinusoidalTimeEmbedding(nn.Module):
    def __init__(self, dim: int):
        super().__init__()
        self.dim = dim
        self.mlp = nn.Sequential(
            nn.Linear(dim, dim * 2),
            nn.SiLU(),
            nn.Linear(dim * 2, dim),
        )

    def forward(self, t: torch.Tensor) -> torch.Tensor:
        half = self.dim // 2
        freqs = torch.exp(
            -math.log(10000.0) * torch.arange(half, device=t.device, dtype=torch.float32) / max(half - 1, 1)
        )
        args = t.float()[:, None] * freqs[None, :] * 1000.0
        emb = torch.cat((args.sin(), args.cos()), dim=-1)
        return self.mlp(emb)


class FlowAttention(nn.Module):
    def __init__(self, channels: int, heads: int, dropout: float):
        super().__init__()
        self.heads = heads
        self.dropout = dropout
        self.qkv = nn.Linear(channels, 3 * channels)
        self.out = nn.Linear(channels, channels)

    def forward(self, x: torch.Tensor, mask: torch.Tensor, table: tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
        b, t, c = x.shape
        q, k, v = self.qkv(x).view(b, t, 3, self.heads, c // self.heads).permute(2, 0, 3, 1, 4)
        y = F.scaled_dot_product_attention(
            rotate(q, table),
            rotate(k, table),
            v,
            attn_mask=mask[:, None, None, :],
            dropout_p=self.dropout if self.training else 0.0,
        )
        return self.out(y.transpose(1, 2).reshape(b, t, c))


class FlowBlock(nn.Module):
    """Bloco Transformer RoPE + Conv depthwise com modulação AdaLN-Zero pelo tempo t."""

    def __init__(self, channels: int, heads: int, feedforward: int, kernel: int, dropout: float):
        super().__init__()
        self.norm1 = nn.LayerNorm(channels, elementwise_affine=False)
        self.attention = FlowAttention(channels, heads, dropout)
        self.norm2 = nn.LayerNorm(channels, elementwise_affine=False)
        self.depthwise = nn.Conv1d(channels, channels, kernel, padding=kernel // 2, groups=channels)
        self.expand = nn.Linear(channels, feedforward)
        self.project = nn.Linear(feedforward, channels)
        self.dropout = nn.Dropout(dropout)
        # 6 modulations: shift1, scale1, gate1, shift2, scale2, gate2
        self.ada = nn.Sequential(nn.SiLU(), nn.Linear(channels, 6 * channels))
        nn.init.zeros_(self.ada[1].weight)
        nn.init.zeros_(self.ada[1].bias)

    def forward(self, x: torch.Tensor, t_emb: torch.Tensor, mask: torch.Tensor, table) -> torch.Tensor:
        keep = mask[..., None]
        s1, sc1, g1, s2, sc2, g2 = self.ada(t_emb)[:, None, :].chunk(6, dim=-1)
        h = self.norm1(x) * (1.0 + sc1) + s1
        x = (x + g1 * self.dropout(self.attention(h, mask, table))) * keep
        h2 = (self.norm2(x) * (1.0 + sc2) + s2) * keep
        y = self.depthwise(h2.transpose(1, 2)).transpose(1, 2)
        y = self.project(self.dropout(F.gelu(self.expand(y))))
        return (x + g2 * self.dropout(y)) * keep


class FlowDecoder(nn.Module):
    """Preditor de velocidade v_theta(x_t, t | cond, prior_mel, f0_feats) no espaço mel-100 do Vocos."""

    def __init__(self, cfg: CFMConfig):
        super().__init__()
        c = cfg.base
        d = cfg.flow_channels
        self.n_mels = c.vocos_n_mels
        self.use_f0_harmonics = bool(cfg.use_f0_harmonics)
        in_dim = self.n_mels * 2 + c.channels + (12 if self.use_f0_harmonics else 0)
        self.time_emb = SinusoidalTimeEmbedding(d)
        self.in_proj = nn.Linear(in_dim, d)
        self.blocks = nn.ModuleList(
            FlowBlock(d, cfg.flow_heads, cfg.flow_feedforward, cfg.flow_kernel, cfg.flow_dropout)
            for _ in range(cfg.flow_layers)
        )
        self.final_norm = nn.LayerNorm(d, elementwise_affine=False)
        self.final_ada = nn.Sequential(nn.SiLU(), nn.Linear(d, 2 * d))
        self.out_proj = nn.Linear(d, self.n_mels)
        nn.init.zeros_(self.final_ada[1].weight)
        nn.init.zeros_(self.final_ada[1].bias)
        nn.init.zeros_(self.out_proj.weight)
        nn.init.zeros_(self.out_proj.bias)
        self.head_width = d // cfg.flow_heads

    def forward(

        self,

        x_t: torch.Tensor,

        t: torch.Tensor,

        cond: torch.Tensor,

        prior_mel: torch.Tensor,

        frame_mask: torch.Tensor,

        f0_feats: torch.Tensor | None = None,

    ) -> torch.Tensor:
        keep = frame_mask[..., None]
        t_emb = self.time_emb(t)
        parts = (x_t, prior_mel, cond, f0_feats) if (self.use_f0_harmonics and f0_feats is not None) else (x_t, prior_mel, cond)
        h = self.in_proj(torch.cat(parts, dim=-1)) * keep
        table = rotary_table(x_t.shape[1], self.head_width, x_t.device)
        for block in self.blocks:
            h = block(h, t_emb, frame_mask, table)
        shift, scale = self.final_ada(t_emb)[:, None, :].chunk(2, dim=-1)
        h = self.final_norm(h) * (1.0 + scale) + shift
        return self.out_proj(h) * keep


class LinguisticContextAdapter(nn.Module):
    """Adaptador residual zero-inicializado para contexto de palavra, tonica e clausula."""

    def __init__(self, c: Config, layers: int = 2, ling_dim: int = 26):
        super().__init__()
        self.ling_proj = nn.Linear(ling_dim, c.channels)
        self.word_proj = nn.Linear(c.channels, c.channels)
        self.stack = Stack(c, layers)
        self.out_proj = nn.Linear(c.channels, c.channels)
        nn.init.zeros_(self.out_proj.weight)
        nn.init.zeros_(self.out_proj.bias)

    def forward(

        self,

        hidden: torch.Tensor,

        ling_feats: torch.Tensor,

        same_word: torch.Tensor,

        token_mask: torch.Tensor,

    ) -> torch.Tensor:
        w = same_word.to(hidden.dtype)
        w = w / w.sum(dim=-1, keepdim=True).clamp_min(1.0)
        word_mean = torch.bmm(w, hidden)
        x = (hidden + self.ling_proj(ling_feats.to(hidden.dtype)) + self.word_proj(word_mean)) * token_mask[..., None]
        return (hidden + self.out_proj(self.stack(x, token_mask))) * token_mask[..., None]


class DurationFlow(nn.Module):
    """Preditor generativo OT-CFM para log1p(duracao) de fonemas e pausas."""

    def __init__(self, cfg: CFMConfig):
        super().__init__()
        d = cfg.dur_flow_channels
        in_dim = 2 + cfg.base.channels
        self.time_emb = SinusoidalTimeEmbedding(d)
        self.in_proj = nn.Linear(in_dim, d)
        self.blocks = nn.ModuleList(
            FlowBlock(d, cfg.dur_flow_heads, cfg.dur_flow_feedforward, cfg.dur_flow_kernel, 0.05)
            for _ in range(cfg.dur_flow_layers)
        )
        self.final_norm = nn.LayerNorm(d, elementwise_affine=False)
        self.final_ada = nn.Sequential(nn.SiLU(), nn.Linear(d, 2 * d))
        self.out_proj = nn.Linear(d, 1)
        nn.init.zeros_(self.final_ada[1].weight)
        nn.init.zeros_(self.final_ada[1].bias)
        nn.init.zeros_(self.out_proj.weight)
        nn.init.zeros_(self.out_proj.bias)
        self.head_width = d // cfg.dur_flow_heads

    def forward(

        self,

        z_t: torch.Tensor,

        t: torch.Tensor,

        prior_log_dur: torch.Tensor,

        token_ctx: torch.Tensor,

        token_mask: torch.Tensor,

    ) -> torch.Tensor:
        keep = token_mask[..., None]
        t_emb = self.time_emb(t)
        h = self.in_proj(torch.cat((z_t.float(), prior_log_dur.float(), token_ctx.float()), dim=-1)) * keep
        table = rotary_table(z_t.shape[1], self.head_width, z_t.device)
        for block in self.blocks:
            h = block(h, t_emb, token_mask, table)
        shift, scale = self.final_ada(t_emb)[:, None, :].chunk(2, dim=-1)
        h = self.final_norm(h) * (1.0 + scale) + shift
        return self.out_proj(h) * keep


class ProsodyFlow(nn.Module):
    """Preditor generativo OT-CFM para contorno [log_F0, energia] em nivel de frame."""

    def __init__(self, cfg: CFMConfig):
        super().__init__()
        d = cfg.prosody_flow_channels
        in_dim = 5 + cfg.base.channels
        self.time_emb = SinusoidalTimeEmbedding(d)
        self.in_proj = nn.Linear(in_dim, d)
        self.blocks = nn.ModuleList(
            FlowBlock(d, cfg.prosody_flow_heads, cfg.prosody_flow_feedforward, cfg.prosody_flow_kernel, 0.05)
            for _ in range(cfg.prosody_flow_layers)
        )
        self.final_norm = nn.LayerNorm(d, elementwise_affine=False)
        self.final_ada = nn.Sequential(nn.SiLU(), nn.Linear(d, 2 * d))
        self.out_proj = nn.Linear(d, 2)
        nn.init.zeros_(self.final_ada[1].weight)
        nn.init.zeros_(self.final_ada[1].bias)
        nn.init.zeros_(self.out_proj.weight)
        nn.init.zeros_(self.out_proj.bias)
        self.head_width = d // cfg.prosody_flow_heads

    def forward(

        self,

        y_t: torch.Tensor,

        t: torch.Tensor,

        prior_fe: torch.Tensor,

        voicing_prob: torch.Tensor,

        prosody_hidden: torch.Tensor,

        frame_mask: torch.Tensor,

    ) -> torch.Tensor:
        keep = frame_mask[..., None]
        t_emb = self.time_emb(t)
        h = self.in_proj(
            torch.cat((y_t.float(), prior_fe.float(), voicing_prob.float(), prosody_hidden.float()), dim=-1)
        ) * keep
        table = rotary_table(y_t.shape[1], self.head_width, y_t.device)
        for block in self.blocks:
            h = block(h, t_emb, frame_mask, table)
        shift, scale = self.final_ada(t_emb)[:, None, :].chunk(2, dim=-1)
        h = self.final_norm(h) * (1.0 + scale) + shift
        return self.out_proj(h) * keep


class LuaNovaCFM(nn.Module):
    """Front-end fonético CTC do LuaNovaBase + Prior Mel + FlowDecoder OT-CFM + Vocos 24 kHz."""

    FRONTEND_MODULES = (
        "tokens", "stress", "voices", "encoder", "duration",
        "frame_voices", "frame_position", "prosody_stack", "prosody_head",
    )
    ITEM3_MODULES = ("context_adapter", "frame_ctx_proj", "dur_flow", "prosody_flow")

    def __init__(self, cfg: CFMConfig, vocos_model=None, load_vocos: bool | None = None):
        super().__init__()
        self.cfm_config = cfg
        self.config = c = cfg.base
        # Front-end idêntico ao LuaNovaBase (carrega pesos direto do checkpoint Stage 1!)
        self.tokens = nn.Embedding(c.vocab_size, c.channels, padding_idx=0)
        self.stress = nn.Embedding(3, c.channels)
        self.voices = nn.Embedding(len(c.speakers), c.channels)
        self.encoder = Stack(c, c.encoder_layers)
        self.duration = Predictor(c, 2)
        self.frame_voices = nn.Embedding(len(c.speakers), c.channels)
        self.frame_position = nn.Linear(3, c.channels)
        self.prosody_stack = Stack(c, c.prosody_layers)
        self.prosody_head = nn.Linear(c.channels, 3)
        self.prosody_projection = nn.Linear(3, c.channels)
        # Item 3 (opcionais para manter retrocompatibilidade v1/v2/v3)
        self.context_adapter = LinguisticContextAdapter(c, layers=cfg.prosody_context_layers) if cfg.use_ling_context else None
        if cfg.use_ling_context:
            self.frame_ctx_proj = nn.Linear(6, c.channels)
            nn.init.zeros_(self.frame_ctx_proj.weight)
            nn.init.zeros_(self.frame_ctx_proj.bias)
        else:
            self.frame_ctx_proj = None
        self.dur_flow = DurationFlow(cfg) if cfg.use_duration_flow else None
        self.prosody_flow = ProsodyFlow(cfg) if cfg.use_prosody_flow else None
        # Prior mel determinístico (5 camadas RoPE quando use_acoustic_prior=True) + Flow Matching decoder
        self.acoustic_stack = Stack(c, c.acoustic_layers) if cfg.use_acoustic_prior else None
        self.prior_head = nn.Linear(c.channels, c.vocos_n_mels)
        self.flow = FlowDecoder(cfg)
        use_vocos = (cfg.mel_space == "vocos") if load_vocos is None else bool(load_vocos)
        self.vocoder = VocosHead(c, vocos_model=vocos_model) if (use_vocos or vocos_model is not None) else MelStatsHead(c)
        self.vocoder.freeze_vocoder(True)

        phones = torch.zeros(c.vocab_size, dtype=torch.bool)
        phones[sorted(PHONE_IDS)] = True
        self.register_buffer("phone_tokens", phones, persistent=False)
        vowels = torch.zeros(c.vocab_size, dtype=torch.bool)
        vowels[[SYMBOL_TO_ID[v] for v in VOWELS]] = True
        self.register_buffer("vowel_tokens", vowels, persistent=False)
        voiceless = torch.zeros(c.vocab_size, dtype=torch.bool)
        voiceless[[SYMBOL_TO_ID[v] for v in VOICELESS]] = True
        self.register_buffer("voiceless_tokens", voiceless, persistent=False)
        puncts = torch.zeros(c.vocab_size, dtype=torch.bool)
        puncts[[SYMBOL_TO_ID[p] for p in PUNCTUATION]] = True
        self.register_buffer("punct_tokens", puncts, persistent=False)
        clause_puncts = torch.zeros(c.vocab_size, dtype=torch.bool)
        clause_puncts[list(_CLAUSE_PUNCT_IDS)] = True
        self.register_buffer("clause_punct_tokens", clause_puncts, persistent=False)
        self.register_buffer("prosody_noise_kernel", make_prosody_noise_kernel(), persistent=False)
        self._frontend_frozen = False

    def freeze_frontend(self, frozen: bool = True) -> None:
        self._frontend_frozen = frozen
        for name in self.FRONTEND_MODULES + self.ITEM3_MODULES:
            mod = getattr(self, name)
            if mod is None:
                continue
            for p in mod.parameters():
                p.requires_grad_(not frozen)
            if frozen:
                mod.eval()

    def train(self, mode: bool = True):
        super().train(mode)
        if self.vocoder.frozen and getattr(self.vocoder, "vocos", None) is not None:
            self.vocoder.vocos.eval()
        if self._frontend_frozen:
            for name in self.FRONTEND_MODULES + self.ITEM3_MODULES:
                mod = getattr(self, name)
                if mod is not None:
                    mod.eval()
        return self

    def load_frontend(

        self, state_dict: dict, prosody_state_dict: dict | None = None

    ) -> list[str]:
        """Carrega pesos do front-end (+ acoustic_stack/prior_head/Vocos se use_acoustic_prior) e prosodia refinada."""
        loaded = []
        own = self.state_dict()
        prefix = "model." if any(k.startswith("model.encoder.") for k in state_dict) else ""
        keep_prefixes = tuple(f"{m}." for m in self.FRONTEND_MODULES) + (
            "prosody_projection.",
            "vocoder.mel_mean",
            "vocoder.mel_scale",
        )
        if self.acoustic_stack is not None:
            keep_prefixes = keep_prefixes + ("acoustic_stack.",)
        for k, v in state_dict.items():
            if prefix and not k.startswith(prefix):
                continue
            key = k[len(prefix):] if prefix else k
            if self.acoustic_stack is not None and key == "vocoder.proj.weight" and "prior_head.weight" in own:
                if own["prior_head.weight"].shape == v.shape:
                    own["prior_head.weight"] = v
                    loaded.append("prior_head.weight")
                    continue
            if self.acoustic_stack is not None and key == "vocoder.proj.bias" and "prior_head.bias" in own:
                if own["prior_head.bias"].shape == v.shape:
                    own["prior_head.bias"] = v
                    loaded.append("prior_head.bias")
                    continue
            if any(key == p or key.startswith(p) for p in keep_prefixes) and key in own and own[key].shape == v.shape:
                own[key] = v
                loaded.append(key)

        if prosody_state_dict is not None:
            ppref = "model." if any(k.startswith("model.prosody_stack.") for k in prosody_state_dict) else ""
            for k, v in prosody_state_dict.items():
                if ppref and not k.startswith(ppref):
                    continue
                key = k[len(ppref):] if ppref else k
                if key.startswith(("prosody_stack.", "prosody_head.")) and key in own and own[key].shape == v.shape:
                    own[key] = v
                    if key not in loaded:
                        loaded.append(key)

        self.load_state_dict(own, strict=True)
        return loaded

    def encode(self, tokens, stress, lengths, speakers):
        mask = length_mask(lengths, tokens.shape[1])
        x = (self.tokens(tokens) + self.stress(stress) + self.voices(speakers)[:, None]) * mask[..., None]
        return self.encoder(x, mask), mask

    def encode_prosody_context(

        self,

        hidden: torch.Tensor,

        tokens: torch.Tensor,

        stress: torch.Tensor,

        token_mask: torch.Tensor,

    ) -> tuple[torch.Tensor, torch.Tensor | None]:
        if self.context_adapter is None:
            return hidden, None
        ling_feats, same_word, clause_ctx_tok = linguistic_context_features(
            tokens,
            stress,
            token_mask,
            self.phone_tokens,
            self.vowel_tokens,
            self.voiceless_tokens,
            self.clause_punct_tokens,
        )
        prosody_token_ctx = self.context_adapter(hidden, ling_feats, same_word, token_mask)
        return prosody_token_ctx, clause_ctx_tok

    def _expand_indices(self, durations: torch.Tensor):
        lengths = durations.sum(1)
        if bool((lengths < 1).any()):
            raise ValueError("utterance has no frames")
        if bool((lengths > self.config.max_frames).any()):
            raise UtteranceTooLong("utterance exceeds max_frames; split the input")
        size = int(lengths.max())
        ends = durations.cumsum(1)
        frame = torch.arange(size, device=durations.device)[None].expand(durations.shape[0], size).contiguous()
        index = torch.searchsorted(ends, frame, right=True).clamp(max=durations.shape[1] - 1)
        owned = durations.gather(1, index).clamp_min(1)
        offset = frame - (ends.gather(1, index) - durations.gather(1, index))
        relative = (offset.float() + 0.5) / owned.float()
        features = torch.stack((relative, 1.0 - relative, torch.log1p(owned.float()) / 4.0), dim=-1)
        mask = frame < lengths[:, None]
        return frame, index, features, mask, lengths

    def expand(self, hidden, durations, token_mask, speakers):
        _frame, index, features, mask, lengths = self._expand_indices(durations)
        expanded = hidden.gather(1, index[..., None].expand(-1, -1, hidden.shape[-1]))
        expanded = expanded + self.frame_position(features.to(hidden.dtype)) + self.frame_voices(speakers)[:, None]
        return expanded * mask[..., None], mask, lengths

    def expand_with_context(

        self,

        hidden: torch.Tensor,

        prosody_token_ctx: torch.Tensor,

        clause_ctx_tok: torch.Tensor | None,

        durations: torch.Tensor,

        token_mask: torch.Tensor,

        speakers: torch.Tensor,

    ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
        frame, index, features, mask, lengths = self._expand_indices(durations)
        pos_voice = self.frame_position(features.to(hidden.dtype)) + self.frame_voices(speakers)[:, None]
        acoustic_frames = (hidden.gather(1, index[..., None].expand(-1, -1, hidden.shape[-1])) + pos_voice) * mask[..., None]
        if self.context_adapter is None and self.frame_ctx_proj is None:
            return acoustic_frames, acoustic_frames, mask, lengths
        prosody_frames = prosody_token_ctx.gather(1, index[..., None].expand(-1, -1, prosody_token_ctx.shape[-1])) + pos_voice
        if self.frame_ctx_proj is not None:
            if clause_ctx_tok is None:
                raise ValueError("clause_ctx_tok required when frame_ctx_proj is enabled")
            f_pos = (frame.float() + 0.5) / lengths.clamp_min(1).float()[:, None]
            f_rem = 1.0 - f_pos
            c_f = clause_ctx_tok.gather(1, index[..., None].expand(-1, -1, 4))
            ctx_6 = torch.cat((f_pos[..., None], f_rem[..., None], c_f.float()), dim=-1) * mask[..., None].float()
            prosody_frames = prosody_frames + self.frame_ctx_proj(ctx_6.to(prosody_frames.dtype))
        return acoustic_frames, prosody_frames * mask[..., None], mask, lengths

    def predict_prosody(self, frames, frame_mask):
        hidden = self.prosody_stack(frames, frame_mask)
        return hidden, self.prosody_head(hidden) * frame_mask[..., None]

    @staticmethod
    def hard_prosody(prediction):
        return torch.stack(
            (prediction[..., 0].clamp(-2.0, 1.5), (prediction[..., 1] > 0).to(prediction.dtype), prediction[..., 2].clamp(-4.5, 3.0)),
            dim=-1,
        )

    def predict_durations(self, hidden, mask, tokens, speed=1.0):
        output = self.duration(hidden, mask).float()
        frames = torch.round((torch.exp(output[..., 0].clamp(0.0, math.log1p(400.0))) - 1.0) / speed).long().clamp_min(1)
        present = self.phone_tokens[tokens] | (output[..., 1] > 0)
        return torch.where(present, frames, torch.zeros_like(frames)) * mask

    def sample_durations(

        self,

        prosody_token_ctx: torch.Tensor,

        token_mask: torch.Tensor,

        tokens: torch.Tensor,

        speed: float = 1.0,

        seed: int = 0,

        temperature: float | None = None,

        steps: int | None = None,

        noise: torch.Tensor | None = None,

    ) -> tuple[torch.Tensor, torch.Tensor]:
        raw = self.duration(prosody_token_ctx, token_mask).float()
        prior_z = raw[..., 0].clamp(0.0, math.log1p(400.0))
        if self.dur_flow is not None:
            n_steps = int(self.cfm_config.dur_flow_steps if steps is None else steps)
            temp = float(self.cfm_config.dur_flow_temp if temperature is None else temperature)
            b, l_len, _ = prosody_token_ctx.shape
            if noise is None:
                gen = torch.Generator(device=prosody_token_ctx.device).manual_seed(int(seed) + 101)
                eps = torch.randn((b, l_len, 1), generator=gen, device=prosody_token_ctx.device, dtype=torch.float32)
            else:
                eps = noise.float()
            sigma = self.cfm_config.dur_flow_sigma * temp
            z = (prior_z[..., None] + sigma * eps) * token_mask[..., None].float()
            dt = 1.0 / max(n_steps, 1)
            for i in range(n_steps):
                t_vec = torch.full((b,), i * dt, device=z.device, dtype=torch.float32)
                v = self.dur_flow(z, t_vec, prior_z[..., None], prosody_token_ctx, token_mask)
                z = (z + dt * v) * token_mask[..., None].float()
            z1 = z.squeeze(-1)
        else:
            z1 = prior_z
        frames = torch.round((torch.exp(z1.clamp(0.0, math.log1p(400.0))) - 1.0) / speed).long().clamp_min(1)
        present = self.phone_tokens[tokens] | (raw[..., 1] > 0)
        durations = torch.where(present, frames, torch.zeros_like(frames)) * token_mask
        return durations, raw

    def sample_prosody(

        self,

        prosody_frames: torch.Tensor,

        frame_mask: torch.Tensor,

        seed: int = 0,

        temperature: float | None = None,

        steps: int | None = None,

        noise: torch.Tensor | None = None,

    ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
        prosody_hidden, prior_raw = self.predict_prosody(prosody_frames, frame_mask)
        if self.prosody_flow is None:
            return prosody_hidden, prior_raw, prior_raw
        n_steps = int(self.cfm_config.prosody_flow_steps if steps is None else steps)
        temp = float(self.cfm_config.prosody_flow_temp if temperature is None else temperature)
        b, t_len, _ = prosody_frames.shape
        if noise is None:
            gen = torch.Generator(device=prosody_frames.device).manual_seed(int(seed) + 202)
            eps = torch.randn((b, t_len, 2), generator=gen, device=prosody_frames.device, dtype=torch.float32)
        else:
            eps = noise.float()
        eps_sm = smooth_prosody_noise(eps, frame_mask, self.prosody_noise_kernel)
        prior_fe = torch.stack((prior_raw[..., 0].float(), prior_raw[..., 2].float()), dim=-1)
        voicing_prob = torch.sigmoid(prior_raw[..., 1:2].float())
        sigma = self.cfm_config.prosody_flow_sigma * temp
        y = (prior_fe + sigma * eps_sm) * frame_mask[..., None].float()
        dt = 1.0 / max(n_steps, 1)
        for i in range(n_steps):
            t_vec = torch.full((b,), i * dt, device=y.device, dtype=torch.float32)
            v = self.prosody_flow(y, t_vec, prior_fe, voicing_prob, prosody_hidden, frame_mask)
            y = (y + dt * v) * frame_mask[..., None].float()
        prosody = torch.cat((y[..., :1], prior_raw[..., 1:2].float(), y[..., 1:2]), dim=-1) * frame_mask[..., None].float()
        return prosody_hidden, prosody, prior_raw

    def condition_and_prior(self, prosody_hidden, condition, frame_mask):
        ph = prosody_hidden
        if (
            not self.cfm_config.acoustic_from_frames
            and self.acoustic_stack is not None
            and self.training
            and self.cfm_config.prosody_hidden_dropout > 0
        ):
            ph = F.dropout1d(ph.transpose(1, 2), p=self.cfm_config.prosody_hidden_dropout, training=True).transpose(1, 2)
        proj = (ph + self.prosody_projection(condition.to(ph.dtype))) * frame_mask[..., None]
        cond = self.acoustic_stack(proj, frame_mask) if self.acoustic_stack is not None else proj
        prior_mel = self.prior_head(cond.float()) * frame_mask[..., None]
        return cond, prior_mel

    @staticmethod
    def widen_pitch(prosody, frame_mask, pitch_range):
        if pitch_range == 1.0:
            return prosody
        voiced = ((prosody[..., 1] > 0) & frame_mask).to(prosody.dtype)
        mean = (prosody[..., 0] * voiced).sum(1, keepdim=True) / voiced.sum(1, keepdim=True).clamp_min(1)
        pitch = mean + (prosody[..., 0] - mean) * pitch_range
        return torch.cat((pitch[..., None], prosody[..., 1:]), dim=-1) * frame_mask[..., None]

    @staticmethod
    def sway_time_grid(n_steps: int, sway_coef: float = 0.0) -> list[float]:
        """Return monotone ODE time schedule in [0, 1]; uniform when ``sway_coef == 0.0``."""
        if sway_coef == 0.0:
            return [i / n_steps for i in range(n_steps + 1)]
        s = max(-1.0, min(1.0, float(sway_coef)))
        return [u + s * (math.cos(0.5 * math.pi * u) - 1.0 + u) for u in (i / n_steps for i in range(n_steps + 1))]

    def sample_mel(

        self,

        cond: torch.Tensor,

        prior_mel: torch.Tensor,

        frame_mask: torch.Tensor,

        n_steps: int = 8,

        cfg_scale: float = 1.2,

        temperature: float = 0.85,

        solver: str = "midpoint",

        seed: int = 0,

        f0_feats: torch.Tensor | None = None,

        noise_gate: torch.Tensor | None = None,

        sway_coef: float = 0.0,

    ) -> torch.Tensor:
        """Integra o campo de velocidade OT-CFM em ``n_steps`` passos (Euler ou Midpoint)."""
        b, t_len, m = prior_mel.shape
        gen = torch.Generator(device=prior_mel.device).manual_seed(int(seed))
        sigma = self.cfm_config.prior_sigma * temperature
        eps = torch.randn((b, t_len, m), generator=gen, device=prior_mel.device, dtype=torch.float32)
        noise = sigma * eps if noise_gate is None else sigma * noise_gate * eps
        x = (prior_mel + noise) * frame_mask[..., None]
        zero_cond = torch.zeros_like(cond)
        zero_prior = torch.zeros_like(prior_mel)
        zero_f0 = torch.zeros_like(f0_feats) if f0_feats is not None else None

        def velocity(x_cur: torch.Tensor, t_val: float) -> torch.Tensor:
            t_vec = torch.full((b,), t_val, device=x_cur.device, dtype=torch.float32)
            v_c = self.flow(x_cur, t_vec, cond, prior_mel, frame_mask, f0_feats=f0_feats)
            if cfg_scale == 1.0:
                return v_c
            v_u = self.flow(x_cur, t_vec, zero_cond, zero_prior, frame_mask, f0_feats=zero_f0)
            return v_u + cfg_scale * (v_c - v_u)

        if sway_coef == 0.0:
            dt = 1.0 / n_steps
            steps = [(i * dt, dt) for i in range(n_steps)]
        else:
            t_grid = self.sway_time_grid(n_steps, sway_coef)
            steps = [(t_grid[i], t_grid[i + 1] - t_grid[i]) for i in range(n_steps)]
        for t0, dt_i in steps:
            if solver == "midpoint":
                v0 = velocity(x, t0)
                x_mid = (x + 0.5 * dt_i * v0) * frame_mask[..., None]
                v_mid = velocity(x_mid, t0 + 0.5 * dt_i)
                x = (x + dt_i * v_mid) * frame_mask[..., None]
            else:
                v0 = velocity(x, t0)
                x = (x + dt_i * v0) * frame_mask[..., None]
        return x

    @torch.inference_mode()
    def predict_physical_mel(

        self,

        tokens,

        stress,

        lengths,

        speakers,

        speed: float = 1.0,

        pitch_shift: float = 0.0,

        seed: int = 0,

        pitch_range: float | None = None,

        n_steps: int = 8,

        cfg_scale: float = 1.0,

        temperature: float = 0.35,

        solver: str = "midpoint",

        sway_coef: float = 0.0,

        voiced_vowels: bool = True,

        dur_steps: int | None = None,

        dur_temp: float | None = None,

        prosody_steps: int | None = None,

        prosody_temp: float | None = None,

    ) -> tuple[torch.Tensor, torch.Tensor, dict]:
        """Predict unnormalized physical log-mel ``[B, T, 100]``, ``frame_lengths``, and details."""
        pr = self.cfm_config.default_pitch_range if pitch_range is None else float(pitch_range)
        hidden, mask = self.encode(tokens, stress, lengths, speakers)
        prosody_token_ctx, clause_ctx_tok = self.encode_prosody_context(hidden, tokens, stress, mask)
        durations, _ = self.sample_durations(
            prosody_token_ctx, mask, tokens, speed=speed, seed=seed, temperature=dur_temp, steps=dur_steps
        )
        acoustic_frames, prosody_frames, frame_mask, frame_lengths = self.expand_with_context(
            hidden, prosody_token_ctx, clause_ctx_tok, durations, mask, speakers
        )
        prosody_hidden, prosody, _ = self.sample_prosody(
            prosody_frames, frame_mask, seed=seed, temperature=prosody_temp, steps=prosody_steps
        )
        if voiced_vowels:
            ends = durations.cumsum(1)
            frame = torch.arange(prosody_frames.shape[1], device=tokens.device)[None].expand(len(lengths), -1).contiguous()
            index = torch.searchsorted(ends, frame, right=True).clamp(max=tokens.shape[1] - 1)
            is_vowel = self.vowel_tokens[tokens.gather(1, index)] & frame_mask
            prosody = torch.cat((prosody[..., :1], torch.where(is_vowel, prosody[..., 1].clamp_min(1.0), prosody[..., 1])[..., None], prosody[..., 2:]), dim=-1)
        prosody = self.widen_pitch(prosody, frame_mask, pr)
        if pitch_shift != 0.0:
            prosody = torch.cat((prosody[..., :1] + pitch_shift, prosody[..., 1:]), dim=-1) * frame_mask[..., None]
        hard_p = self.hard_prosody(prosody)
        base_h = acoustic_frames if self.cfm_config.acoustic_from_frames else prosody_hidden
        cond, prior_mel = self.condition_and_prior(base_h, hard_p, frame_mask)
        f0_feats = f0_features(hard_p, frame_mask) if self.cfm_config.use_f0_harmonics else None
        noise_gate = energy_noise_gate(hard_p, frame_mask) if self.cfm_config.use_energy_gate else None
        mel_norm = self.sample_mel(
            cond, prior_mel, frame_mask, n_steps=n_steps, cfg_scale=cfg_scale,
            temperature=temperature, solver=solver, seed=seed, f0_feats=f0_feats,
            noise_gate=noise_gate, sway_coef=sway_coef,
        )
        phys_mel = (mel_norm * self.vocoder.mel_scale + self.vocoder.mel_mean).clamp(min=-11.512925)
        return phys_mel, frame_lengths, {"durations": durations, "prosody": prosody, "mel_norm": mel_norm}

    @torch.inference_mode()
    def synthesize(

        self,

        tokens,

        stress,

        lengths,

        speakers,

        speed: float = 1.0,

        pitch_shift: float = 0.0,

        seed: int = 0,

        pitch_range: float | None = None,

        n_steps: int = 8,

        cfg_scale: float = 1.2,

        temperature: float = 0.85,

        solver: str = "midpoint",

        sway_coef: float = 0.0,

        voiced_vowels: bool = True,

        dur_steps: int | None = None,

        dur_temp: float | None = None,

        prosody_steps: int | None = None,

        prosody_temp: float | None = None,

    ):
        _, frame_lengths, details = self.predict_physical_mel(
            tokens, stress, lengths, speakers,
            speed=speed, pitch_shift=pitch_shift, seed=seed, pitch_range=pitch_range,
            n_steps=n_steps, cfg_scale=cfg_scale, temperature=temperature, solver=solver,
            sway_coef=sway_coef, voiced_vowels=voiced_vowels,
            dur_steps=dur_steps, dur_temp=dur_temp, prosody_steps=prosody_steps, prosody_temp=prosody_temp,
        )
        audio = self.vocoder.decode_mel(details["mel_norm"], frame_lengths)
        return audio, frame_lengths * self.config.hop, details