File size: 9,682 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
"""Unit tests for ONNX export parity, chunked vocoder streaming, and OT-CFM distillation."""
from __future__ import annotations

import copy
from pathlib import Path
import tempfile
import unittest

import numpy as np
import torch

from lua_nova_v1.config import CFMConfig, Config
from lua_nova_v1.export import (
    ExportableCFMAcoustic,
    example_cfm_inputs,
    export_bigvgan_onnx,
    export_cfm_onnx,
    verify_bigvgan_onnx,
    verify_cfm_onnx,
)
from lua_nova_v1.inference import OnnxSynthesizer
from lua_nova_v1.inference.streaming import stream_vocoder_chunks
from lua_nova_v1.models import BigVGANVocoderWrapper, LuaNovaCFM
from lua_nova_v1.models.bigvgan import _ensure_bigvgan_importable
from lua_nova_v1.training.distill import distill_loss_step, make_channel_weights


def _tiny_v5_cfg() -> CFMConfig:
    base = Config(
        channels=32,
        heads=2,
        feedforward=64,
        encoder_layers=1,
        prosody_layers=1,
        acoustic_layers=1,
        predictor_channels=16,
        vocos_n_mels=100,
    )
    return CFMConfig(
        base=base,
        flow_channels=32,
        flow_layers=2,
        flow_heads=2,
        flow_feedforward=64,
        flow_kernel=3,
        use_acoustic_prior=True,
        use_f0_harmonics=True,
        acoustic_from_frames=True,
        use_energy_gate=True,
        use_ling_context=True,
        use_duration_flow=True,
        use_prosody_flow=True,
        prosody_context_layers=1,
        dur_flow_channels=16,
        dur_flow_layers=1,
        dur_flow_heads=2,
        dur_flow_feedforward=32,
        prosody_flow_channels=16,
        prosody_flow_layers=1,
        prosody_flow_heads=2,
        prosody_flow_feedforward=32,
        mel_space="bigvgan_24k_100",
    )


class OnnxAndStreamingTests(unittest.TestCase):
    def test_cfm_onnx_export_and_parity_euler2_and_sway8(self) -> None:
        model = LuaNovaCFM(_tiny_v5_cfg()).eval()
        # Deterministic math check between predict_physical_mel and ExportableCFMAcoustic.
        inp = example_cfm_inputs("Dia vinte e dois de março, vamos testar!")
        wrapper_det = ExportableCFMAcoustic(
            model, n_steps=4, solver="midpoint", sway_coef=-0.5, temperature=0.0, dur_temp=0.0, prosody_temp=0.0
        ).eval()
        with torch.no_grad():
            mel_ref, flen_ref, _ = model.predict_physical_mel(
                inp[0],
                inp[1],
                torch.tensor([inp[0].shape[1]]),
                inp[2],
                speed=float(inp[3].item()),
                pitch_shift=float(inp[4].item()),
                pitch_range=float(inp[5].item()),
                n_steps=4,
                cfg_scale=1.0,
                temperature=0.0,
                solver="midpoint",
                sway_coef=-0.5,
                dur_temp=0.0,
                prosody_temp=0.0,
            )
            mel_wrap, flen_wrap = wrapper_det(*inp)
        self.assertEqual(int(flen_ref.item()), int(flen_wrap.item()))
        self.assertLess((mel_ref - mel_wrap).abs().max().item(), 1e-4)

        with tempfile.TemporaryDirectory() as tmp:
            onnx_euler2 = Path(tmp) / "cfm_euler2.onnx"
            export_cfm_onnx(model, onnx_euler2, n_steps=2, solver="euler", sway_coef=0.0, temperature=0.35, seed=0)
            self.assertTrue(onnx_euler2.with_suffix(".meta.json").is_file())
            for probe_text in ("Oi!", "Olá, tudo bem com você hoje?", "Dia vinte e dois de março vamos ao mercado."):
                parity2 = verify_cfm_onnx(
                    model,
                    onnx_euler2,
                    n_steps=2,
                    solver="euler",
                    sway_coef=0.0,
                    temperature=0.35,
                    seed=0,
                    text=probe_text,
                )
                self.assertEqual(parity2["frames_match"], 1.0)
                self.assertLess(parity2["max_abs_diff"], 1e-4)

            onnx_sway8 = Path(tmp) / "cfm_sway8.onnx"
            export_cfm_onnx(model, onnx_sway8, n_steps=8, solver="midpoint", sway_coef=-0.5, temperature=0.35, seed=0)
            parity8 = verify_cfm_onnx(
                model, onnx_sway8, n_steps=8, solver="midpoint", sway_coef=-0.5, temperature=0.35, seed=0
            )
            self.assertEqual(parity8["frames_match"], 1.0)
            self.assertLess(parity8["max_abs_diff"], 1e-4)

    def test_stream_vocoder_chunks_exact_length_and_smooth_boundary(self) -> None:
        hop = 256
        total_frames = 90
        mel = np.zeros((total_frames, 100), dtype=np.float32)
        mel[:, 0] = np.arange(total_frames, dtype=np.float32)

        def _smooth_dummy_vocoder(mel_slice: np.ndarray) -> np.ndarray:
            n_frames = int(mel_slice.shape[0])
            f0 = float(mel_slice[0, 0])
            t = np.arange(n_frames * hop, dtype=np.float32) / float(hop) + f0
            return 0.5 * np.sin(2.0 * np.pi * 0.25 * t)

        chunks = list(
            stream_vocoder_chunks(
                _smooth_dummy_vocoder,
                mel,
                hop=hop,
                chunk_frames=32,
                context_frames=8,
                fade_frames=4,
            )
        )
        self.assertGreater(len(chunks), 1)
        stitched = np.concatenate(chunks, axis=0)
        self.assertEqual(stitched.shape, (total_frames * hop,))
        self.assertTrue(np.isfinite(stitched).all())

        full = _smooth_dummy_vocoder(mel)
        self.assertLess(float(np.abs(stitched - full).max()), 1e-5)

    def test_distill_loss_step_updates_only_student_flow(self) -> None:
        teacher = LuaNovaCFM(_tiny_v5_cfg()).eval()
        for p in teacher.parameters():
            p.requires_grad_(False)
        student = copy.deepcopy(teacher)
        for p in student.parameters():
            p.requires_grad_(False)
        for p in student.flow.parameters():
            p.requires_grad_(True)
        student.eval()
        student.flow.train()

        batch = {
            "tokens": torch.tensor([[1, 5, 6, 7, 2], [1, 8, 9, 2, 0]], dtype=torch.long),
            "stress": torch.tensor([[0, 1, 0, 0, 0], [0, 0, 1, 0, 0]], dtype=torch.long),
            "token_lengths": torch.tensor([5, 4], dtype=torch.long),
            "durations": torch.tensor([[2, 4, 5, 3, 2], [2, 5, 4, 2, 0]], dtype=torch.long),
            "frame_lengths": torch.tensor([16, 13], dtype=torch.long),
            "speakers": torch.tensor([0, 0], dtype=torch.long),
            "prosody": torch.randn(2, 16, 3),
        }
        ch_w = make_channel_weights(100, 1.4, "cpu")
        loss, metrics = distill_loss_step(
            teacher,
            student,
            batch,
            ch_w,
            teacher_steps=4,
            teacher_sway=-0.5,
            teacher_temp=0.35,
            student_steps=2,
            training=True,
        )
        self.assertTrue(torch.isfinite(loss))
        self.assertIn("end_l1", metrics)
        loss.backward()
        self.assertTrue(any(p.grad is not None for p in student.flow.parameters()))
        self.assertTrue(all(p.grad is None for p in student.encoder.parameters()))

    def test_bigvgan_onnx_export_and_onnx_synthesizer_stream(self) -> None:
        _ensure_bigvgan_importable()
        import bigvgan
        from env import AttrDict

        h = {
            "num_mels": 100,
            "hop_size": 256,
            "sampling_rate": 24000,
            "upsample_initial_channel": 64,
            "upsample_rates": [8, 8, 2, 2],
            "upsample_kernel_sizes": [16, 16, 4, 4],
            "resblock": "1",
            "resblock_kernel_sizes": [3],
            "resblock_dilation_sizes": [[1, 3]],
            "activation": "snakebeta",
            "snake_logscale": True,
            "use_bias_at_final": True,
            "use_tanh_at_final": True,
        }
        cfm = LuaNovaCFM(_tiny_v5_cfg()).eval()
        net = bigvgan.BigVGAN(AttrDict(h), use_cuda_kernel=False).eval()
        with tempfile.TemporaryDirectory() as tmp:
            voc_ckpt = Path(tmp) / "tiny_bigvgan.pt"
            torch.save({"h": h, "state_dict": net.state_dict(), "weight_norm_removed": False}, voc_ckpt)
            voc_wrapper = BigVGANVocoderWrapper(ckpt_path=voc_ckpt, device="cpu")

            voc_onnx = Path(tmp) / "tiny_bigvgan.onnx"
            export_bigvgan_onnx(voc_wrapper, voc_onnx, dummy_frames=8)
            parity = verify_bigvgan_onnx(voc_wrapper, voc_onnx, test_frames=13)
            self.assertEqual(int(parity["samples"]), 13 * 256)
            self.assertLess(parity["max_abs_diff"], 1e-4)

            cfm_onnx = Path(tmp) / "tiny_cfm2.onnx"
            export_cfm_onnx(cfm, cfm_onnx, n_steps=2, solver="euler", sway_coef=0.0, temperature=0.35, seed=0)

            ox = OnnxSynthesizer(cfm_onnx, voc_onnx, threads=2)
            full_wav = ox.speak("Olá, tudo bem?", normalize=True, postprocess=True)
            self.assertEqual(full_wav.dtype, np.float32)
            self.assertTrue(np.isfinite(full_wav).all())
            self.assertGreater(full_wav.size, 256)

            chunks = list(ox.speak_stream("Olá! Vamos testar o streaming agora.", chunk_frames=12, context_frames=4, fade_frames=2))
            self.assertGreater(len(chunks), 1)
            streamed = np.concatenate(chunks, axis=0)
            self.assertTrue(np.isfinite(streamed).all())
            self.assertGreater(streamed.size, 256)


if __name__ == "__main__":
    unittest.main()