tiny-voca-da / recipe /scripts /compute_budget.py
inlanger's picture
tiny-voca-da v0.1: frontend v4 + sm9 vocoder (ONNX fp32/int8, PyTorch, frontend, recipe, samples)
adabee1 verified
Raw History Blame Contribute Delete
3.17 kB
"""How much compute and memory one second of speech needs (for small-device targets such as ESP32).
Runs the same single-utterance graph that tiny_voca.export puts into ONNX (Exportable) on the
probe set under torch's FlopCounterMode, and reports multiply-accumulates (MACs = FLOPs / 2) per
second of audio, split by part: voice model (encoder, durations, prosody, acoustic stacks),
DSP synthesiser, neural vocoder. Counts matmul / conv / conv-transpose only; element-wise work is
small next to them. Also reports parameter counts and the weight size at fp32 / fp16 / int8.
python scripts/compute_budget.py --checkpoint models/X.pt --vocoder models/Y.pt --set probes_da.jsonl
"""
import argparse
import json
from collections import defaultdict
from pathlib import Path
import torch
from torch.utils.flop_counter import FlopCounterMode
from tiny_voca.export import Exportable, load_model, load_vocoder, match_frontend
from tiny_voca.languages import profile_for
from tiny_voca.text import phonemize
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--checkpoint', type=Path, required=True)
p.add_argument('--vocoder', type=Path, required=True)
p.add_argument('--set', type=Path, required=True)
p.add_argument('--output', type=Path)
args = p.parse_args()
torch.set_num_threads(4)
match_frontend(args.checkpoint)
model = load_model(args.checkpoint, 'cpu').eval()
vocoder = load_vocoder(args.vocoder).eval()
wrapper = Exportable(model, False, vocoder).eval()
profile = profile_for('da')
rate = model.config.sample_rate
parts = {'voice model': sum(x.numel() for x in model.parameters()),
'neural vocoder': sum(x.numel() for x in vocoder.parameters())}
seconds, totals = 0.0, defaultdict(float)
rows = [json.loads(x) for x in args.set.read_text(encoding='utf-8').splitlines() if x.strip()]
for row in rows:
phones = phonemize(row['text'], profile)
inputs = (torch.tensor([phones.ids]), torch.tensor([phones.stress]), torch.tensor([0]),
torch.tensor([1.0]), torch.tensor([0.0]), torch.tensor([1.0]))
counter = FlopCounterMode(display=False, depth=4)
with torch.no_grad(), counter:
audio, _ = wrapper(*inputs)
seconds += audio.shape[-1] / rate
for name, ops in counter.get_flop_counts().items():
totals[name] += sum(ops.values())
for op, n in ops.items():
totals[f'{name} :: {op}'] += n
macs = {k: v / 2 / seconds for k, v in sorted(totals.items(), key=lambda kv: -kv[1])}
report = {'audio_seconds': seconds, 'clips': len(rows), 'params': parts,
'params_total': sum(parts.values()),
'weights_mb': {k: sum(parts.values()) * b / 1e6 for k, b in (('fp32', 4), ('fp16', 2), ('int8', 1))},
'mmacs_per_audio_second': {k: round(v / 1e6, 1) for k, v in macs.items()}}
print(json.dumps(report, indent=1))
if args.output:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, indent=1) + '\n')
if __name__ == '__main__':
main()