viks66 commited on
Commit
a6c21ac
·
verified ·
1 Parent(s): e5f9e94

add model.py

Browse files
Files changed (1) hide show
  1. model.py +250 -0
model.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from huggingface_hub import hf_hub_download
4
+ from moshi.models import loaders as moshi_loaders
5
+
6
+ # Config (from ms_lstm_mimi-25hz-nq8_delay1f training run)
7
+ MODEL_DEFAULTS = {
8
+ "input_size": 512, # Mimi feat_size
9
+ "hidden_size": 512,
10
+ "num_layers": 2,
11
+ "output_size": 5,
12
+ "dropout": 0.1,
13
+ "bidirectional": False,
14
+ "project": 128, # projects 512 → 128 before LSTMs
15
+ "num_project": 1,
16
+ }
17
+
18
+
19
+ AUDIO_DEFAULTS = {
20
+ "sr": 24000, # Mimi native sample rate
21
+ "num_quantizers": 8,
22
+ "frame_rate_hz": 25.0, # after ×2 upsample from Mimi's native 12.5Hz
23
+ }
24
+
25
+
26
+ class MimiLSTM(nn.Module):
27
+ """Two-stream LSTM over Mimi embeddings.
28
+
29
+ Input x: (batch, 2, feat_size, T) — speaker_1 at index 0, speaker_2 at index 1.
30
+ Output: (batch, T, output_size)
31
+ """
32
+ def __init__(self, input_size, hidden_size, num_layers, output_size,
33
+ dropout, bidirectional, project, **_):
34
+ super().__init__()
35
+ self.mel_embed = nn.Sequential(
36
+ nn.Linear(input_size, project),
37
+ nn.ReLU(),
38
+ )
39
+ lstm_kwargs = dict(
40
+ input_size=project,
41
+ hidden_size=hidden_size,
42
+ num_layers=num_layers,
43
+ batch_first=True,
44
+ dropout=dropout,
45
+ bidirectional=bidirectional,
46
+ )
47
+ self.model1 = nn.LSTM(**lstm_kwargs)
48
+ self.model2 = nn.LSTM(**lstm_kwargs)
49
+ self.linear = nn.Linear(hidden_size * 2, output_size)
50
+
51
+ def init_hidden(self, batch_size, device):
52
+ h = torch.zeros(self.model1.num_layers, batch_size, self.model1.hidden_size).to(device)
53
+ c = torch.zeros(self.model1.num_layers, batch_size, self.model1.hidden_size).to(device)
54
+ return h, c
55
+
56
+ def infer(self, x):
57
+ """Full-sequence inference. x: (1, 2, feat, T)."""
58
+ x = x.permute(0, 1, 3, 2) # (1, 2, T, feat)
59
+ x = self.mel_embed(x) # (1, 2, T, project)
60
+ h, c = self.init_hidden(x.size(0), x.device)
61
+ x1, _ = self.model1(x[:, 0], (h, c))
62
+ x2, _ = self.model2(x[:, 1], (h, c))
63
+ return self.linear(torch.cat([x1, x2], dim=-1)) # (1, T, output_size)
64
+
65
+ def infer_ar_step(self, feat1, feat2, h1, c1, h2, c2):
66
+ """Single-frame AR step.
67
+
68
+ feat1, feat2: (1, feat_size) — one frame per speaker.
69
+ Returns: logits (1, output_size), updated (h1, c1, h2, c2).
70
+ """
71
+ f1 = self.mel_embed(feat1).unsqueeze(1) # (1, 1, project)
72
+ f2 = self.mel_embed(feat2).unsqueeze(1)
73
+ out1, (h1, c1) = self.model1(f1, (h1, c1)) # (1, 1, hidden)
74
+ out2, (h2, c2) = self.model2(f2, (h2, c2))
75
+ logits = self.linear(torch.cat([out1, out2], dim=-1)).squeeze(1) # (1, output_size)
76
+ return logits, h1, c1, h2, c2
77
+
78
+ def infer_ar(self, x):
79
+ """Frame-by-frame AR inference. x: (1, 2, feat, T).
80
+ Equivalent to infer() for a unidirectional LSTM but simulates real-time decoding.
81
+ """
82
+ x = x.permute(0, 1, 3, 2) # (1, 2, T, feat)
83
+ x = self.mel_embed(x) # (1, 2, T, project)
84
+ T = x.size(2)
85
+ h1, c1 = self.init_hidden(x.size(0), x.device)
86
+ h2, c2 = self.init_hidden(x.size(0), x.device)
87
+ outputs = []
88
+ for t in range(T):
89
+ f1 = x[:, 0, t:t+1, :] # (1, 1, project)
90
+ f2 = x[:, 1, t:t+1, :]
91
+ out1, (h1, c1) = self.model1(f1, (h1, c1))
92
+ out2, (h2, c2) = self.model2(f2, (h2, c2))
93
+ outputs.append(self.linear(torch.cat([out1, out2], dim=-1)))
94
+ return torch.cat(outputs, dim=1) # (1, T, output_size)
95
+
96
+
97
+ class AudioFeatureExtractor:
98
+ """Extracts Mimi embeddings from raw waveform using the moshi library."""
99
+
100
+ def __init__(self, sr, num_quantizers, device="cuda", **_):
101
+ mimi_weight = hf_hub_download(moshi_loaders.DEFAULT_REPO, moshi_loaders.MIMI_NAME)
102
+ self.mimi = moshi_loaders.get_mimi(mimi_weight, device=device, num_codebooks=num_quantizers)
103
+ self.mimi.eval()
104
+ self.sr = sr
105
+ self.device = device
106
+
107
+ def _to_tensor(self, wav):
108
+ """1D numpy array → (1, 1, T) tensor on device."""
109
+ return torch.from_numpy(wav).float().to(self.device).unsqueeze(0).unsqueeze(0)
110
+
111
+ @torch.no_grad()
112
+ def __call__(self, wav):
113
+ """Full-sequence. wav: 1D numpy array. Returns (1, feat_size, T) at 25Hz."""
114
+ x = self._to_tensor(wav)
115
+ emb = self.mimi.encode_to_latent(x, quantize=True) # (1, feat, T) at 12.5Hz
116
+ return self.mimi.upsample(emb) # (1, feat, T) at 25Hz
117
+
118
+ @torch.no_grad()
119
+ def stream(self, wav1, wav2):
120
+ """Streaming both speakers batched together, one Mimi frame (1920 samples) at a time.
121
+ Yields (1, feat_size, frames) for speaker1 and speaker2 per chunk.
122
+ Single streaming context so KV cache is shared and there's no double-enter conflict.
123
+ """
124
+ chunk_samples = self.mimi.frame_size # 1920
125
+
126
+ def pad(wav):
127
+ t = torch.from_numpy(wav).float().to(self.device)
128
+ r = len(t) % chunk_samples
129
+ return torch.nn.functional.pad(t, (0, chunk_samples - r if r else 0))
130
+
131
+ w1, w2 = pad(wav1), pad(wav2)
132
+ n_chunks = len(w1) // chunk_samples
133
+
134
+ with self.mimi.streaming(batch_size=2):
135
+ for i in range(n_chunks):
136
+ s = i * chunk_samples
137
+ chunk = torch.stack([w1[s:s+chunk_samples], w2[s:s+chunk_samples]]).unsqueeze(1) # (2, 1, 1920)
138
+ emb = self.mimi.encode_to_latent(chunk, quantize=True) # (2, feat, 1)
139
+ emb = self.mimi.upsample(emb) # (2, feat, 2)
140
+ yield emb[0:1], emb[1:2] # (1, feat, 2) each
141
+
142
+
143
+ def load_model(checkpoint_path, device="cpu"):
144
+ model = MimiLSTM(**MODEL_DEFAULTS)
145
+ ckpt = torch.load(checkpoint_path, map_location=device)
146
+ model.load_state_dict(ckpt["model_state_dict"])
147
+ model.eval()
148
+ return model.to(device)
149
+
150
+
151
+ CLASS_NAMES = ["bos", "system_end", "user_end", "system", "user"]
152
+
153
+
154
+ if __name__ == "__main__":
155
+ import argparse
156
+ import numpy as np
157
+ import soundfile as sf
158
+ import matplotlib.pyplot as plt
159
+
160
+ parser = argparse.ArgumentParser()
161
+ parser.add_argument("--checkpoint", default=None)
162
+ parser.add_argument("--sample_dir", required=True)
163
+ parser.add_argument("--ar", action="store_true", help="Streaming Mimi (chunk-by-chunk) + AR LSTM step-by-step.")
164
+ parser.add_argument("--out", default="eval_output.png")
165
+ args = parser.parse_args()
166
+
167
+ import torchaudio
168
+ import numpy as np
169
+ import soundfile as sf
170
+ import matplotlib.pyplot as plt
171
+ from pathlib import Path
172
+
173
+ device = "cuda" if torch.cuda.is_available() else "cpu"
174
+ if args.checkpoint:
175
+ model = load_model(args.checkpoint, device=device)
176
+ print(f"Loaded: {args.checkpoint}")
177
+ else:
178
+ model = MimiLSTM(**MODEL_DEFAULTS).to(device).eval()
179
+ print("No checkpoint — using random weights.")
180
+
181
+ extractor = AudioFeatureExtractor(**AUDIO_DEFAULTS, device=device)
182
+ target_sr = AUDIO_DEFAULTS["sr"]
183
+ d = Path(args.sample_dir)
184
+
185
+ wav1, sr1 = sf.read(d / "speaker_1_audio.wav", dtype="float32")
186
+ wav2, sr2 = sf.read(d / "speaker_2_audio.wav", dtype="float32")
187
+ if sr1 != target_sr:
188
+ wav1 = torchaudio.functional.resample(torch.from_numpy(wav1), sr1, target_sr).numpy()
189
+ if sr2 != target_sr:
190
+ wav2 = torchaudio.functional.resample(torch.from_numpy(wav2), sr2, target_sr).numpy()
191
+
192
+ if args.ar:
193
+ # streaming Mimi chunk-by-chunk + AR LSTM step-by-step
194
+ print("Running streaming Mimi + AR LSTM...")
195
+ from tqdm import tqdm
196
+ h1, c1 = model.init_hidden(1, device)
197
+ h2, c2 = model.init_hidden(1, device)
198
+ all_logits = []
199
+ n_chunks = (len(wav1) + 1919) // 1920
200
+ with torch.no_grad():
201
+ for feat1_chunk, feat2_chunk in tqdm(
202
+ extractor.stream(wav1, wav2),
203
+ total=n_chunks, unit="chunk", desc="Streaming"
204
+ ):
205
+ feat1_chunk, feat2_chunk = feat1_chunk.to(device), feat2_chunk.to(device)
206
+ for t in range(feat1_chunk.shape[-1]):
207
+ logits, h1, c1, h2, c2 = model.infer_ar_step(
208
+ feat1_chunk[:, :, t], feat2_chunk[:, :, t], h1, c1, h2, c2
209
+ )
210
+ all_logits.append(logits)
211
+ out = torch.stack(all_logits, dim=1) # (1, T, output_size)
212
+ else:
213
+ feat1 = extractor(wav1) # (1, feat, T)
214
+ feat2 = extractor(wav2)
215
+ T = min(feat1.shape[-1], feat2.shape[-1])
216
+ x = torch.cat([feat1[:, :, :T], feat2[:, :, :T]], dim=0).unsqueeze(0) # (1, 2, feat, T)
217
+ with torch.no_grad():
218
+ out = model.infer(x.to(device))
219
+
220
+ T = out.shape[1]
221
+ print(f"Audio: {len(wav1)/target_sr:.1f}s, {T} frames @ {AUDIO_DEFAULTS['frame_rate_hz']} Hz")
222
+ probs = torch.softmax(out[0], dim=-1).cpu().numpy() # (T, 5)
223
+
224
+ frame_times = np.arange(T) / AUDIO_DEFAULTS["frame_rate_hz"]
225
+ wav_times = np.arange(len(wav1)) / target_sr
226
+
227
+ duration = len(wav1) / target_sr
228
+ fig_width = max(28, int(duration * 0.2)) # ~0.2 inches per second
229
+ fig, (ax_wav, ax_pred) = plt.subplots(
230
+ 2, 1, figsize=(fig_width, 6),
231
+ gridspec_kw={"hspace": 0.08, "height_ratios": [1, 1]},
232
+ )
233
+
234
+ ax_wav.plot(wav_times, wav1, linewidth=0.3, color="steelblue", alpha=0.7, label="Speaker 1")
235
+ ax_wav.plot(wav_times, wav2, linewidth=0.3, color="darkorange", alpha=0.7, label="Speaker 2")
236
+ ax_wav.set_ylabel("Amplitude")
237
+ ax_wav.set_xlim(wav_times[0], wav_times[-1])
238
+ ax_wav.legend(loc="upper right", fontsize=8)
239
+ ax_wav.set_xticklabels([])
240
+
241
+ for i, name in enumerate(CLASS_NAMES):
242
+ ax_pred.plot(frame_times, probs[:, i], label=name, linewidth=1.0)
243
+ ax_pred.set_ylabel("Softmax probability")
244
+ ax_pred.set_xlabel("Time (s)")
245
+ ax_pred.set_xlim(frame_times[0], frame_times[-1])
246
+ ax_pred.set_ylim(0, 1)
247
+ ax_pred.legend(loc="upper right", fontsize=8)
248
+
249
+ plt.savefig(args.out, dpi=150, bbox_inches="tight")
250
+ print(f"Saved: {args.out}")