Download test_streaming.py from mahmud71/muaalem-streaming: direct link, hf CLI and curl.
- Browser
- Download file 3.83 kB
-
https://huggingface.co/mahmud71/muaalem-streaming/resolve/main/test_streaming.py
- Command line
-
hf download hf://mahmud71/muaalem-streaming/test_streaming.py
-
curl -L -o test_streaming.py https://huggingface.co/mahmud71/muaalem-streaming/resolve/main/test_streaming.py
3.83 kB
| """Checks that the streaming model computes what it should, before any | |
| training: | |
| 1. The torch features equal the SeamlessM4T extractor's raw log-mel frames. | |
| 2. With one chunk covering the whole clip and nothing remembered, the | |
| streaming model equals the original model (same weights, same answer). | |
| 3. One chunk at a time with the carried state equals all chunks at once. | |
| If this fails, training would teach something the app can't reproduce. | |
| python test_streaming.py CLIP.pcm | |
| CLIP.pcm: 16 kHz mono s16le recitation, at least 8 s. | |
| """ | |
| import argparse | |
| import sys | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| from transformers import SeamlessM4TFeatureExtractor | |
| sys.path.insert(0, str(Path(__file__).parent)) | |
| from features import Fbank, NormStats, running_normalize, stack_pairs # noqa: E402 | |
| from streaming_model import StreamingMuaalem, download, load_muaalem # noqa: E402 | |
| def check(name: str, a: torch.Tensor, b: torch.Tensor, tolerance: float) -> bool: | |
| diff = (a - b).abs().max().item() | |
| ok = diff <= tolerance | |
| print(f"{'PASS' if ok else 'FAIL'} {name}: max difference {diff:.2e} (allowed {tolerance:.0e})") | |
| return ok | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("clip", type=Path) | |
| args = parser.parse_args() | |
| torch.manual_seed(0) | |
| pcm = np.fromfile(args.clip, dtype=np.int16) | |
| if len(pcm) < 8 * 16000: | |
| raise SystemExit("need at least 8 s of audio") | |
| audio = torch.from_numpy(pcm[: 8 * 16000].astype(np.float32) / 32768)[None] | |
| snapshot = download() | |
| base = load_muaalem(snapshot) | |
| extractor = SeamlessM4TFeatureExtractor.from_pretrained(snapshot) | |
| results = [] | |
| # 1. Features. | |
| fbank = Fbank() | |
| ours = fbank(audio)[0] | |
| theirs = torch.from_numpy(extractor._extract_fbank_features(audio[0].numpy())).float() | |
| results.append(check("features vs extractor", ours, theirs, 1e-2)) | |
| with torch.no_grad(): | |
| # 2. Full context = the original model (5 s, as the model was trained). | |
| clip = audio[:, : 5 * 16000] | |
| features = torch.from_numpy( | |
| extractor(clip[0].numpy(), sampling_rate=16000, return_tensors="np")["input_features"] | |
| ) | |
| T = features.shape[1] | |
| original = base(features) | |
| stream = StreamingMuaalem(base).eval() | |
| full, _ = stream(features, torch.tensor([T]), chunk=T + T % 2, left=0) | |
| results.append(check("full context vs original model", full, original, 1e-3)) | |
| # 3. Step by step vs all at once (8 s, chunk 32, 192 remembered). | |
| stats = NormStats(ours.mean(0), ours.var(0)) | |
| raw = fbank(audio) | |
| chunk = stream.chunk | |
| n = raw.shape[1] // (2 * chunk) * (2 * chunk) | |
| raw = raw[:, :n] | |
| normed = stack_pairs(running_normalize(raw, torch.tensor([n]), 2 * chunk, stats)) | |
| at_once, _ = stream(normed, torch.tensor([normed.shape[1]])) | |
| state = stream.initial_state() | |
| steps = [] | |
| for start in range(0, normed.shape[1], chunk): | |
| logits, state = stream.step(normed[:, start : start + chunk], state) | |
| steps.append(logits) | |
| results.append(check("step by step vs all at once", torch.cat(steps, 1), at_once, 1e-3)) | |
| # And running normalization chunk by chunk equals the batch version. | |
| pieces = [] | |
| for end in range(2 * chunk, n + 1, 2 * chunk): | |
| part = running_normalize(raw[:, :end], torch.tensor([end]), 2 * chunk, stats) | |
| pieces.append(part[:, end - 2 * chunk : end]) | |
| results.append( | |
| check("normalization chunk by chunk", torch.cat(pieces, 1), running_normalize(raw, torch.tensor([n]), 2 * chunk, stats), 1e-4) | |
| ) | |
| if not all(results): | |
| raise SystemExit(1) | |
| print("all checks passed") | |
| if __name__ == "__main__": | |
| main() | |