-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_flow_matching.py
More file actions
226 lines (182 loc) · 6.7 KB
/
Copy pathtest_flow_matching.py
File metadata and controls
226 lines (182 loc) · 6.7 KB
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
"""
Test Flow Matching implementation
Verify all components work correctly
"""
import torch
import sys
def test_flow_matching_core():
"""Test core Flow Matching module"""
print("=" * 60)
print("Testing Flow Matching Core Module")
print("=" * 60)
from flow_matching import FlowMatchingTTS
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(f"Device: {device}")
# Create model
model = FlowMatchingTTS(
n_mel_channels=80,
n_text_vocab=200,
d_model=256, # Smaller for testing
nhead=4,
num_layers=3,
dim_feedforward=1024,
dropout=0.1,
use_duration_predictor=True
).to(device)
print(f"✅ Model created successfully")
# Dummy data
B, T_text, T_mel = 2, 20, 100
text = torch.randint(0, 200, (B, T_text)).to(device)
text_lengths = torch.tensor([15, 20]).to(device)
mel = torch.randn(B, 80, T_mel).to(device)
mel_lengths = torch.tensor([80, 100]).to(device)
# Test training
print("\nTesting training forward pass...")
losses = model(text, text_lengths, mel, mel_lengths)
print(f"✅ Training losses:")
for key, value in losses.items():
print(f" {key}: {value.item():.4f}")
# Test inference
print("\nTesting inference (10 steps)...")
mel_gen, mel_lengths_gen = model.infer(text, text_lengths, n_timesteps=10)
print(f"✅ Generated mel shape: {mel_gen.shape}")
print(f" Mel lengths: {mel_lengths_gen.tolist()}")
# Test with Sway sampling
print("\nTesting inference with Sway sampling...")
mel_gen_sway, _ = model.infer(text, text_lengths, n_timesteps=10, sway_coef=-1.0)
print(f"✅ Generated mel (sway) shape: {mel_gen_sway.shape}")
# Test midpoint method
print("\nTesting inference with midpoint ODE solver...")
mel_gen_mid, _ = model.infer(text, text_lengths, n_timesteps=10,
method='midpoint', sway_coef=0.0)
print(f"✅ Generated mel (midpoint) shape: {mel_gen_mid.shape}")
print("\n" + "=" * 60)
print("✅ All Flow Matching core tests passed!")
print("=" * 60)
def test_flow_matching_synthesizer():
"""Test FlowMatchingSynthesizer (integrated with MB-iSTFT)"""
print("\n" + "=" * 60)
print("Testing FlowMatchingSynthesizer (Full Model)")
print("=" * 60)
from models import FlowMatchingSynthesizer
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(f"Device: {device}")
# Create model
model = FlowMatchingSynthesizer(
n_text_vocab=200,
n_mel_channels=80,
inter_channels=192,
d_model=256, # Smaller for testing
nhead=4,
num_layers=3,
dim_feedforward=1024,
dropout=0.1,
resblock='1',
resblock_kernel_sizes=[3, 7, 11],
resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5], [1, 3, 5]],
upsample_rates=[4, 4],
upsample_initial_channel=512,
upsample_kernel_sizes=[16, 16],
gen_istft_n_fft=16,
gen_istft_hop_size=4,
subbands=4,
use_duration_predictor=True,
gin_channels=0,
).to(device)
print(f"✅ FlowMatchingSynthesizer created successfully")
# Count parameters
n_params = sum(p.numel() for p in model.parameters())
print(f" Total parameters: {n_params:,}")
# Dummy data
B, T_text, T_mel = 2, 20, 100
text = torch.randint(0, 200, (B, T_text)).to(device)
text_lengths = torch.tensor([15, 20]).to(device)
mel = torch.randn(B, 80, T_mel).to(device)
mel_lengths = torch.tensor([80, 100]).to(device)
# Test training
print("\nTesting training forward pass...")
losses = model(text, text_lengths, mel, mel_lengths)
print(f"✅ Training losses:")
for key, value in losses.items():
print(f" {key}: {value.item():.4f}")
# Test inference
print("\nTesting inference (full pipeline: text → mel → audio)...")
audio, audio_mb, mel_gen, mel_lengths_gen = model.infer(
text, text_lengths,
n_timesteps=5, # Fast for testing
sway_coef=-1.0
)
print(f"✅ Generated audio shape: {audio.shape}")
print(f" Audio multiband: {len(audio_mb)} bands")
print(f" Mel shape: {mel_gen.shape}")
print(f" Mel lengths: {mel_lengths_gen.tolist()}")
# Test direct mel-to-audio
print("\nTesting direct mel-to-audio conversion...")
audio_from_mel, audio_mb_from_mel = model.infer_with_mel(mel)
print(f"✅ Audio from mel shape: {audio_from_mel.shape}")
print("\n" + "=" * 60)
print("✅ All FlowMatchingSynthesizer tests passed!")
print("=" * 60)
def test_speed_comparison():
"""Compare inference speed: AR vs Flow Matching"""
print("\n" + "=" * 60)
print("Speed Comparison: AR vs Flow Matching")
print("=" * 60)
import time
device = 'cuda' if torch.cuda.is_available() else 'cpu'
if device == 'cpu':
print("⚠️ CPU detected, skipping speed test (use GPU for accurate comparison)")
return
from flow_matching import FlowMatchingTTS
# Create model
model = FlowMatchingTTS(
n_mel_channels=80,
n_text_vocab=200,
d_model=512,
nhead=8,
num_layers=6,
dim_feedforward=2048,
dropout=0.1,
).to(device)
# Dummy data
B, T_text = 1, 50
text = torch.randint(0, 200, (B, T_text)).to(device)
text_lengths = torch.tensor([50]).to(device)
# Warmup
_ = model.infer(text, text_lengths, n_timesteps=5)
# Test different step counts
for n_steps in [5, 10, 20]:
start = time.time()
for _ in range(10): # Average over 10 runs
mel, _ = model.infer(text, text_lengths, n_timesteps=n_steps)
torch.cuda.synchronize()
elapsed = (time.time() - start) / 10
mel_len = mel.size(2)
audio_len = mel_len * 256 / 22050 # hop_length=256, sr=22050
rtf = elapsed / audio_len
print(f"Steps={n_steps:2d}: {elapsed:.3f}s, RTF={rtf:.3f}, "
f"mel_len={mel_len}, audio={audio_len:.2f}s")
print("\n✅ Speed test completed!")
print(" Note: RTF < 1.0 means faster than real-time")
print("=" * 60)
def main():
"""Run all tests"""
try:
# Test 1: Core Flow Matching
test_flow_matching_core()
# Test 2: Full Synthesizer
test_flow_matching_synthesizer()
# Test 3: Speed comparison
test_speed_comparison()
print("\n" + "🎉" * 30)
print("ALL TESTS PASSED! Flow Matching is ready to use.")
print("🎉" * 30)
except Exception as e:
print("\n" + "❌" * 30)
print(f"TEST FAILED: {e}")
print("❌" * 30)
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
main()