muaalem-streaming / prepare_data.py
mahmud71's picture
Muaalem streaming: INT8 ONNX, source and model card
21f5301 verified
Raw History Blame Contribute Delete
11 kB
"""Prepares training data for streaming Muaalem from Tadabur
(huggingface.co/datasets/FaisaI/tadabur, CC BY-NC 4.0).
For each chosen Tadabur file (one ayah recording per row):
1. decode the WAV to mono 16 kHz;
2. cut long ayahs into 2-10 s pieces between words (the dataset's word
times), so no word is split;
3. label each piece with today's Muaalem mini at full context: the
phonetic letters the app hears now are what the streaming model learns;
4. store the piece as FLAC with its labels, reciter, surah and ayah.
About 3% of reciters (reciter_id % 31 == 0) go to heldout/ and are never
trained on. Global log-mel statistics (the fixed averages the streaming
rescaling starts from) are summed over the training pieces.
Resumable: finished files are listed in OUT/done.txt and skipped.
python prepare_data.py --out DIR [--files 50] [--hours 11]
python prepare_data.py --out DIR --local preview.parquet # a local file
Writes OUT/train/*.parquet, OUT/heldout/*.parquet, OUT/norm_stats.json.
"""
from __future__ import annotations
import argparse
import io
import json
import math
import sys
import time
from multiprocessing import Pool
from pathlib import Path
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import soundfile as sf
import torch
from scipy.signal import resample_poly
sys.path.insert(0, str(Path(__file__).parent))
from features import RATE, Fbank, NormStats, stack_pairs, whole_clip_normalize # noqa: E402
from streaming_model import StreamingMuaalem, download, load_muaalem # noqa: E402
DATASET = "FaisaI/tadabur"
MIN_S, MAX_S = 2.0, 10.0
HELDOUT_MOD = 31
SCHEMA = pa.schema(
[
("flac", pa.binary()),
("labels", pa.binary()), # uint8 symbol ids, blanks and repeats removed
("reciter", pa.int32()),
("surah", pa.int16()),
("ayah", pa.int16()),
("seconds", pa.float32()),
]
)
def to_16k(wav: bytes) -> np.ndarray:
data, rate = sf.read(io.BytesIO(wav), dtype="float32", always_2d=True)
mono = data.mean(axis=1)
if rate != RATE:
g = math.gcd(RATE, rate)
mono = resample_poly(mono, RATE // g, rate // g)
return np.clip(mono * 32768, -32768, 32767).astype(np.int16)
def cut_points(duration: float, word_starts: list[float]) -> list[float]:
"""Cuts at word starts so each piece is at most MAX_S (and, where the
words allow, at least MIN_S)."""
cuts = [0.0]
while duration - cuts[-1] > MAX_S:
ok = [c for c in word_starts if cuts[-1] + MIN_S <= c <= cuts[-1] + MAX_S]
cuts.append(max(ok) if ok else cuts[-1] + MAX_S)
cuts.append(duration)
return cuts
def pieces_of(row: dict) -> list[tuple[np.ndarray, bytes]]:
"""One ayah recording -> [(int16 samples, flac bytes)]."""
try:
samples = to_16k(row["audio"]["bytes"])
except Exception:
return []
duration = len(samples) / RATE
try:
words = json.loads(row["metadata"]).get("word_alignments") or []
starts = [float(w["start"]) for w in words[1:]]
except Exception:
starts = []
cuts = cut_points(duration, starts)
out = []
for a, b in zip(cuts, cuts[1:]):
if b - a < MIN_S:
continue
piece = samples[int(a * RATE) : int(b * RATE)]
buffer = io.BytesIO()
sf.write(buffer, piece, RATE, format="FLAC", subtype="PCM_16")
out.append((piece, buffer.getvalue()))
return out
class Teacher:
"""Today's model at full context, batched on the GPU."""
def __init__(self, device: str):
self.device = device
self.model = StreamingMuaalem(load_muaalem(download())).to(device).eval()
self.fbank = Fbank().to(device)
@torch.no_grad()
def label(self, clips: list[np.ndarray]) -> tuple[list[bytes], list[torch.Tensor]]:
"""Returns each clip's labels and its raw log-mel frames (for the
global statistics)."""
labels: list[bytes] = [b""] * len(clips)
raws: list[torch.Tensor] = [None] * len(clips)
order = sorted(range(len(clips)), key=lambda i: len(clips[i]))
batch: list[int] = []
budget = 24 * 10 * RATE # samples per batch
for i in order + [None]:
if i is not None and (len(batch) + 1) * len(clips[i]) <= budget:
batch.append(i)
continue
if batch:
self._run([clips[j] for j in batch], batch, labels, raws)
batch = [i] if i is not None else []
return labels, raws
def _run(self, clips, index, labels, raws):
lengths = torch.tensor([Fbank.frames(len(c)) for c in clips], device=self.device)
audio = torch.zeros(len(clips), max(len(c) for c in clips), device=self.device)
for k, c in enumerate(clips):
audio[k, : len(c)] = torch.from_numpy(c.astype(np.float32) / 32768).to(self.device)
raw = self.fbank(audio)
lengths = lengths - lengths % 2
features = stack_pairs(whole_clip_normalize(raw, lengths))
frames = lengths // 2
T = features.shape[1]
with torch.autocast(self.device, dtype=torch.float16, enabled=self.device == "cuda"):
logits, out_lengths = self.model(features, frames, chunk=T + T % 2, left=0)
ids = logits.argmax(-1).cpu().numpy()
for k, j in enumerate(index):
seq, prev = [], None
for s in ids[k, : int(out_lengths[k])]:
if s != prev and s != 0:
seq.append(int(s))
prev = s
labels[j] = bytes(seq)
raws[j] = raw[k, : int(lengths[k])].cpu()
def shards(files: int) -> list[str]:
from huggingface_hub import HfApi
names = sorted(
f for f in HfApi().list_repo_files(DATASET, repo_type="dataset")
if f.startswith("data/train-") and f.endswith(".parquet")
)
picks = np.linspace(0, len(names) - 1, files).round().astype(int)
return [names[i] for i in sorted(set(picks))]
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--out", type=Path, required=True)
parser.add_argument("--files", type=int, default=50)
parser.add_argument("--hours", type=float, default=11.0, help="stop starting new files after this")
parser.add_argument("--local", type=Path, help="process this parquet file instead")
parser.add_argument("--limit", type=int, help="rows per file (for a quick try)")
parser.add_argument("--workers", type=int, default=4)
args = parser.parse_args()
began = time.time()
device = "cuda" if torch.cuda.is_available() else "cpu"
for sub in ("train", "heldout"):
(args.out / sub).mkdir(parents=True, exist_ok=True)
done_file = args.out / "done.txt"
done = set(done_file.read_text().split()) if done_file.exists() else set()
sums_file = args.out / "stats_sums.npz"
if sums_file.exists():
z = np.load(sums_file)
s, ss, count = z["s"], z["ss"], int(z["count"])
else:
s, ss, count = np.zeros(80), np.zeros(80), 0
teacher = Teacher(device)
targets = [str(args.local)] if args.local else shards(args.files)
print(f"{len(targets)} files, {len(done)} already done, device {device}", flush=True)
with Pool(args.workers) as pool:
for name in targets:
stem = Path(name).stem
if stem in done:
continue
if time.time() - began > args.hours * 3600:
print("time limit reached; run again to continue", flush=True)
break
started = time.time()
if args.local:
path = Path(name)
else:
from huggingface_hub import hf_hub_download
path = Path(hf_hub_download(DATASET, name, repo_type="dataset", local_dir=args.out / "download"))
writers = {
sub: pq.ParquetWriter(args.out / sub / f"{stem}.parquet.part", SCHEMA)
for sub in ("train", "heldout")
}
seconds = {"train": 0.0, "heldout": 0.0}
rows_seen = 0
source = pq.ParquetFile(path)
for batch in source.iter_batches(batch_size=64, columns=["audio", "reciter_id", "surah_id", "ayah_id", "metadata"]):
rows = batch.to_pylist()
if args.limit is not None:
rows = rows[: max(0, args.limit - rows_seen)]
if not rows:
break
rows_seen += len(rows)
cut = pool.map(pieces_of, rows)
flat = [(r, p, f) for r, ps in zip(rows, cut) for p, f in ps]
if not flat:
continue
labels, raws = teacher.label([p for _, p, _ in flat])
table = {sub: {k: [] for k in SCHEMA.names} for sub in writers}
for (row, piece, flac), lab, raw in zip(flat, labels, raws):
sub = "heldout" if row["reciter_id"] % HELDOUT_MOD == 0 else "train"
if not lab:
continue
t = table[sub]
t["flac"].append(flac)
t["labels"].append(lab)
t["reciter"].append(row["reciter_id"])
t["surah"].append(row["surah_id"])
t["ayah"].append(row["ayah_id"])
t["seconds"].append(len(piece) / RATE)
seconds[sub] += len(piece) / RATE
if sub == "train":
r = raw.double().numpy()
s += r.sum(0)
ss += (r * r).sum(0)
count += r.shape[0]
for sub, t in table.items():
if t["flac"]:
writers[sub].write_table(pa.table(t, schema=SCHEMA))
for sub, w in writers.items():
w.close()
part = args.out / sub / f"{stem}.parquet.part"
part.rename(part.with_suffix(""))
if not args.local:
path.unlink(missing_ok=True)
np.savez(sums_file, s=s, ss=ss, count=count)
mean = s / count
NormStats(torch.tensor(mean), torch.tensor(ss / count - mean**2)).save(args.out / "norm_stats.json", count)
done.add(stem)
done_file.write_text("\n".join(sorted(done)) + "\n")
print(
f"{stem}: {rows_seen} ayahs, train {seconds['train'] / 3600:.2f} h, "
f"heldout {seconds['heldout'] / 3600:.2f} h, {time.time() - started:.0f} s",
flush=True,
)
total = {sub: sum(pq.ParquetFile(p).metadata.num_rows for p in (args.out / sub).glob("*.parquet")) for sub in ("train", "heldout")}
print(f"done: {len(done)} files; pieces {total}; {(time.time() - began) / 60:.0f} min", flush=True)
if __name__ == "__main__":
main()