NERDDISCO's picture
kale-tts-1
f21d6eb
Raw History Blame Contribute Delete
25.2 kB
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Kale
# The image clones kikiri-tts (Apache-2.0; vendors StyleTTS2, MIT, Copyright (c) 2023 Aaron (Yinghao) Li) for the JDC pitch extractor
# and the ASRCNN aligner, and installs kokoro (Apache-2.0, Copyright hexgrad). Their code is imported, not copied.
"""kale-tts-1 training app (Modal). Functions, in the order the release build uses them:
prep features of the kept original Maya takes -> /data/feat-<voice>/shard_NNN.pt (24 kHz audio, pitch, loudness, mel)
durations_fn teacher-aligner durations for every take -> /data/feat/dur_<voice>.pt
merge_lists per-voice id lists / durations / pace-window keep lists -> one set for the run (ids_10v.json, dur_10v.pt, dur_keep_10v.json)
remap_rows re-order a checkpoint's per-voice rows by voice name (new voices start from the mean row)
train_kdur mode kpros (pitch/loudness branch + per-voice offsets), kdur (duration head), r2distill (nano student, ../distil/)
train_k size k (tiny decoder) or r2 (nano sound side) on original Maya audio
export_k_fn / export_r2_fn / bundle_fn ONNX exports for ../export/
Every training process runs as a subprocess under a watchdog (deadline + no-progress) that kills its process group; every function
has a timeout; everything scales to zero. Deploy once (`modal deploy app.py`), then drive it with prep.py, build.py, ../distil/distil.py.
App and volume names come from ../config/modal.json (or $KALE_TTS_MODAL_CONFIG); local paths from config/paths.json.
Volumes: /data = runs volume (features, durations, runs, exports; read-write), /v = data volume (renders + kept lists from ../render and
../filter; read-only), /t = teacher volume (teacher export + voice packs from ../teacher; read-only), HF cache.
"""
import json
import os
import signal
import subprocess
import threading
import time
from datetime import datetime, timezone
from pathlib import Path
import modal
HERE = Path(__file__).resolve().parent
_DEFAULT_NAMES = {"train_app": "kale-tts-train", "data_volume": "kale-tts-data", "teacher_volume": "kale-tts-teacher",
"runs_volume": "kale-tts-runs", "hf_cache_volume": "kale-tts-hf-cache"}
def _modal_config_path():
for p in (os.environ.get("KALE_TTS_MODAL_CONFIG"), HERE.parent / "config" / "modal.json", Path("/root/recipe/modal.json")):
if p and Path(p).is_file():
return Path(p)
return None
def _paths_config():
for p in (HERE / "config" / "paths.json", Path("/root/recipe/paths.json")):
if p.is_file():
return json.loads(p.read_text())
return {}
_MC = _modal_config_path()
NAMES = {**_DEFAULT_NAMES, **(json.loads(_MC.read_text()) if _MC else {})}
PATHS = _paths_config()
app = modal.App(NAMES["train_app"])
data = modal.Volume.from_name(NAMES["runs_volume"], create_if_missing=True)
hf = modal.Volume.from_name(NAMES["hf_cache_volume"], create_if_missing=True)
renders = modal.Volume.from_name(NAMES["data_volume"], create_if_missing=True).read_only() # original Maya renders + kept lists
teacher = modal.Volume.from_name(NAMES["teacher_volume"], create_if_missing=True).read_only() # teacher export + voice packs
KIKIRI = "a12d0410e89841e6f3c09958ae5c072f90ae1d49" # kikiri-tts pin (JDC pitch extractor + ASRCNN; StyleTTS2 submodule, MIT)
VOICES_DEFAULT = "s057b,f06,d03,w165,w602,m3,t071,d13,x328,h013f"
vol = data
VOL = {"/data": data, "/root/.cache/huggingface": hf, "/t": teacher, "/v": renders}
cet = lambda: datetime.now(timezone.utc).strftime("%d %b %H:%M UTC") # noqa: E731
_PARADEE = (HERE / PATHS["paradee_dir"]).resolve() if PATHS.get("paradee_dir") else None # vendored paradee (Apache-2.0), third_party/paradee
img = (
modal.Image.debian_slim(python_version="3.12")
.apt_install("libsndfile1", "build-essential", "git")
.run_commands(f"git clone https://github.com/semidark/kikiri-tts.git /opt/kikiri && cd /opt/kikiri && git checkout {KIKIRI}"
" && git submodule update --init --recursive && ls -la /opt/kikiri/StyleTTS2/Utils/JDC/bst.t7")
.pip_install("torch==2.8.0", "torchaudio==2.8.0", "transformers<5", "kokoro==0.9.4", "soundfile", "numpy<2.3", "scipy",
"pyworld>=0.3.5", "setuptools<81", "numba", "onnx", "onnxruntime==1.22.1", "onnxscript", "pyyaml")
.env({"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True", "HF_HUB_DISABLE_TELEMETRY": "1", "PYTHONUNBUFFERED": "1",
"PARADEE_DIR": "/opt/paradee"})
)
if _PARADEE is not None and _PARADEE.is_dir():
img = img.add_local_dir(str(_PARADEE), "/opt/paradee", copy=True, ignore=["__pycache__"])
for _n in ("model.py", "train.py", "kline.py", "onnx_export.py"):
img = img.add_local_file(str(HERE / _n), f"/opt/recipe/{_n}", copy=True)
if _MC is not None:
img = img.add_local_file(str(_MC), "/root/recipe/modal.json", copy=True)
if (HERE / "config" / "paths.json").is_file():
img = img.add_local_file(str(HERE / "config" / "paths.json"), "/root/recipe/paths.json", copy=True)
def _log(msg, path="/data/status.log"):
line = f"{cet()} {msg}"
print(line, flush=True)
try:
with open(path, "a") as f:
f.write(line + "\n")
except Exception: # noqa: BLE001
pass
def _feat(args):
import numpy as np
import pyworld as pw
import soundfile as sf
import torch
import torchaudio
clip, path = args
y, sr = sf.read(path, dtype="float32")
assert sr == 24000 and y.ndim == 1, (path, sr, y.shape)
raw_peak = float(np.abs(y).max())
Fr = len(y) // 600
y = y[: 600 * Fr]
x = y.astype(np.float64)
f0, t = pw.harvest(x, 24000, f0_floor=60.0, f0_ceil=600.0, frame_period=12.5)
f0 = pw.stonemask(x, f0, t, 24000)
f0 = np.pad(f0, (0, max(0, 2 * Fr - len(f0))))[: 2 * Fr].astype(np.float32)
w = torch.from_numpy(y)
mel = torchaudio.transforms.MelSpectrogram(24000, n_fft=2048, win_length=1200, hop_length=300, n_mels=80)(w)
mel = torch.log(mel.clamp_min(1e-5))[:, : 2 * Fr]
fr = torch.nn.functional.pad(w[None, None], (300, 300), mode="reflect")[0, 0].unfold(0, 600, 300)[: 2 * Fr]
N = torch.log(fr.pow(2).mean(-1).clamp_min(1e-8)) / 2
return dict(clip=clip, F=Fr, audio=torch.from_numpy((np.clip(y, -1, 1) * 32767).astype(np.int16)), f0=torch.from_numpy(f0),
N=N.float(), mel=mel.half(), peak=raw_peak)
@app.function(image=img, cpu=32, memory=65536, timeout=3600, max_containers=3, scaledown_window=60, volumes=VOL)
def prep(rows: list, srcdir: str = "/v", tag: str = "", shard0: int = 0): # rows carry src (a wav on the data volume, mounted at /v)
"""rows [{clip, split, ids, text, src}] -> /data/feat/shard_NN.pt (+ stats.pt). tag != '' (the release build: tag = voice) writes
/data/feat-<tag>/shard_NNN.pt."""
from multiprocessing import Pool
import numpy as np
import torch
out = Path("/data/feat" + (f"-{tag}" if tag else ""))
out.mkdir(parents=True, exist_ok=True)
byclip = {r["clip"]: r for r in rows}
with Pool(32) as p:
feats = p.map(_feat, [(r["clip"], r.get("src") or f"{srcdir}/{r['clip']}.wav") for r in rows], chunksize=8)
keep, drop = [], []
for f in feats:
r = byclip[f["clip"]]
f.update(split=r["split"], ids=r["ids"], text=r.get("text", ""))
if f["F"] < len(r["ids"]) + 2 + 4: # monotonic alignment needs >= 1 frame per token
drop.append(f["clip"])
continue
keep.append(f)
for i in range(0, len(keep), 500):
torch.save(keep[i:i + 500], out / f"shard_{shard0 + i // 500:03d}.pt" if tag else out / f"shard_{i // 500:02d}.pt")
if not tag:
mels = torch.cat([f["mel"].float() for f in keep if f["split"] == "train"], 1)
torch.save(dict(mel_mu=mels.mean(1), mel_sd=mels.std(1).clamp_min(1e-3)), out / "stats.pt")
voiced = np.concatenate([f["f0"].numpy() for f in keep])
info = dict(kept=len(keep), dropped=drop, hours=round(sum(f["F"] * 600 for f in keep) / 24000 / 3600, 3),
train=sum(f["split"] == "train" for f in keep), val=sum(f["split"] == "val" for f in keep),
voiced_share=float((voiced > 0).mean()), f0_median=float(np.median(voiced[voiced > 0])),
peak_max=max(f["peak"] for f in keep), time=cet())
(out / (f"prep-{shard0:03d}.json" if shard0 else "prep.json")).write_text(json.dumps(info, indent=1))
data.commit()
return info
def _committer(stop):
while not stop.wait(300):
try:
data.commit()
except Exception as e: # noqa: BLE001
print("commit failed", e)
def _run_many(jobs, deadline, stall_s=30 * 60):
"""jobs: {name: (cmd, logfile)}. Each runs in its own process group; a job is killed at `deadline` (epoch s) or when its
log has not changed for `stall_s`. Returns {name: (returncode, why)}."""
procs = {}
for n, (cmd, logf) in jobs.items():
Path(logf).parent.mkdir(parents=True, exist_ok=True)
lf = open(logf, "a")
procs[n] = (subprocess.Popen(cmd, cwd="/opt/recipe", stdout=lf, stderr=subprocess.STDOUT, start_new_session=True), logf, lf)
res = {}
while len(res) < len(procs):
time.sleep(20)
for n, (p, logf, lf) in procs.items():
if n in res:
continue
if p.poll() is not None:
res[n] = (p.returncode, None)
_log(f"{n} ended rc={p.returncode}")
continue
why = None
if time.time() > deadline:
why = "deadline"
elif time.time() - Path(logf).stat().st_mtime > stall_s:
why = f"no progress for {stall_s // 60} min"
if why:
_log(f"watchdog: killing {n} ({why})")
os.killpg(p.pid, signal.SIGKILL)
p.wait()
res[n] = (p.returncode, why)
return res
@app.function(image=img, gpu="H100", cpu=16, memory=131072, timeout=int(4.5 * 3600), max_containers=2, scaledown_window=60,
volumes=VOL)
def train_k(size: str, run: str, hours: float = 2.5, steps: int = 50000, spec_steps: int = 25000, gan10_steps: int = 6000, bs: int = 16,
slm: float = 1.0, extra: str = "/data/feat-*/shard_*.pt", dur: str = "", kexport: str = "", ids: str = "",
init_acoustic: str = "", no_main: bool = False, voices: str = VOICES_DEFAULT, packs: str = "", balance: bool = False):
"""the k-line sound side (kline.py) on original Maya audio, one style row per voice. size k: tiny decoder on the teacher's frozen text
encoder; size r2: nano sound side with its own small text encoder."""
deadline = time.time() + hours * 3600
os.environ["KLINE_VOICES"] = voices
if balance:
os.environ["KLINE_BALANCE"] = "1"
if packs:
os.environ["KLINE_PACKS"] = packs
if kexport:
os.environ["KLINE_EXPORT"] = kexport
if ids:
os.environ["KLINE_IDS"] = ids
R = f"/data/run/{run}"
Path(R).mkdir(parents=True, exist_ok=True)
cfg = dict(size=size, run=run, hours=hours, steps=steps, spec_steps=spec_steps, gan10_steps=gan10_steps, bs=bs, slm=slm, extra=extra, dur=dur,
kexport=kexport or "/t/export/teacher", ids=ids or "/data/feat/ids.json", init_acoustic=init_acoustic,
no_main=no_main, voices=voices, packs=packs, started=cet())
Path(f"{R}/config.json").write_text(json.dumps(cfg, indent=1))
stop = threading.Event()
threading.Thread(target=_committer, args=(stop,), daemon=True).start()
try:
cmd = ["python", "train.py", "kdec", "--size", size, "--run", run, "--deadline", str(deadline), "--steps", str(steps),
"--spec-steps", str(spec_steps), "--gan10-steps", str(gan10_steps), "--bs", str(bs), "--slm", str(slm)] + (["--extra", extra] if extra else []) \
+ (["--dur", dur] if dur else []) + (["--init-acoustic", init_acoustic] if init_acoustic else []) + (["--no-main"] if no_main else [])
res = _run_many({"kdec": (cmd, f"{R}/kdec.stdout.log")}, deadline + 600)
finally:
stop.set()
data.commit()
return res, Path(f"{R}/kdec/log.txt").read_text()[-2000:] if Path(f"{R}/kdec/log.txt").exists() else Path(f"{R}/kdec.stdout.log").read_text()[-3000:]
def _load_k(run, size, dev, dur_ckpt="", pros_ckpt=""):
import importlib
import sys
import torch
sys.path.insert(0, "/opt/recipe")
cfgp = Path(f"/data/run/{run}/config.json")
if cfgp.exists(): # the run's own teacher export / voices / packs
c = json.loads(cfgp.read_text())
if c.get("kexport"):
os.environ["KLINE_EXPORT"] = c["kexport"]
if c.get("voices"):
os.environ["KLINE_VOICES"] = c["voices"]
if c.get("packs"):
os.environ["KLINE_PACKS"] = c["packs"]
import kline as K
K = importlib.reload(K)
km, pack = K.load_kmodel(dev, dur_ckpt, pros_ckpt)
kd = K.KDec(size).to(dev).eval()
ck = torch.load(f"/data/run/{run}/kdec/last.pt", map_location=dev, weights_only=False)
kd.load_state_dict(ck["model"])
return K, km, pack, kd, ck.get("step")
@app.function(image=img, cpu=4.0, memory=16384, timeout=3600, max_containers=1, scaledown_window=60, volumes=VOL)
def export_k_fn(run: str, size: str, volcano_sents: list, dur_ckpt: str = "", out: str = "", pros_ckpt: str = ""):
import sys
sys.path.insert(0, "/opt/recipe")
import onnx_export
data.reload()
K, km, pack, kd, astep = _load_k(run, size, "cpu", dur_ckpt, pros_ckpt)
od = f"/data/export/{out or run}"
res = onnx_export.export_k(km, pack, kd, od, volcano_sents)
res["dur_ckpt"] = dur_ckpt
res["pros_ckpt"] = pros_ckpt
res.update(run=run, size=size, decoder_step=astep, time=cet())
res = json.loads(json.dumps(res, default=float))
Path(f"{od}/bench.json").write_text(json.dumps(res, indent=1))
data.commit()
return res, {n: Path(f"{od}/{n}").read_bytes() for n in ("e5.int8dec.onnx", "voicepack.npy")}
@app.function(image=img, cpu=4.0, memory=16384, timeout=3600, max_containers=1, scaledown_window=60, volumes=VOL)
def export_r2_fn(run: str, size: str, r2text: str, volcano_sents: list, out: str):
"""nano -> one multi-voice ONNX (sid input), sizes, 4-thread CPU speed in this container, a volcano take per voice"""
import importlib
import sys
import torch
sys.path.insert(0, "/opt/recipe")
data.reload()
c = json.loads(Path(f"/data/run/{run}/config.json").read_text())
os.environ["KLINE_VOICES"] = c["voices"]
import kline as K
K = importlib.reload(K)
import onnx_export
tck = torch.load(r2text, map_location="cpu", weights_only=False)
rt = K.R2Text(tck["width"]).eval(); rt.load_state_dict(tck["model"])
ack = torch.load(f"/data/run/{run}/kdec/last.pt", map_location="cpu", weights_only=False)
ra = K.R2Ac(size).eval(); ra.load_state_dict(ack["model"])
od = f"/data/export/{out}"
res = onnx_export.export_r2(rt, ra, od, volcano_sents, K.VOICES)
res.update(run=run, r2text=r2text, time=cet())
res = json.loads(json.dumps(res, default=float))
Path(f"{od}/bench.json").write_text(json.dumps(res, indent=1))
data.commit()
return res, {n: Path(f"{od}/{n}").read_bytes() for n in ("r2.int8dec.onnx", "r2.int8.onnx")}
@app.function(image=img, gpu="L40S", cpu=16, memory=98304, timeout=3600, max_containers=2, volumes=VOL)
def durations_fn(ids_file: str = "/data/feat/ids.json", ckpt: str = "/t/run/epoch_2nd_00000.pth",
cfg_path: str = "/t/aligner/config.yml", out: str = "dur", shards: str = "/data/feat-*/shard_*.pt"):
"""teacher-aligner durations (kline.aligner_durations) for every take in `shards` that has ids -> /data/feat/<out>.pt (+ .json)"""
import glob
import sys
import numpy as np
import torch
sys.path.insert(0, "/opt/recipe")
import kline as K
data.reload()
kokoro_ids = json.loads(Path(ids_file).read_text())["rows"]
dur, bad = {}, []
for sh in sorted(glob.glob(shards)):
rows = [r for r in torch.load(sh, weights_only=False) if r["clip"] in kokoro_ids]
d, b = K.aligner_durations(rows, kokoro_ids, ckpt=ckpt, cfg_path=cfg_path)
dur.update(d); bad += b
torch.save(dur, f"/data/feat/{out}.pt")
allv = np.concatenate([v.numpy() for v in dur.values()])
first = float(np.mean([v[0].item() for v in dur.values()])); last = float(np.mean([v[-1].item() for v in dur.values()]))
info = dict(clips=len(dur), bad=len(bad), mean_frames=float(allv.mean()), share_1=float((allv == 1).mean()), lead=first, tail=last,
time=cet())
Path(f"/data/feat/{out}.json").write_text(json.dumps(info, indent=1))
data.commit()
return info
@app.function(image=img, gpu="H100", cpu=16, memory=131072, timeout=2 * 3600, max_containers=3, volumes=VOL)
def train_kdur(run: str, steps: int = 6000, lr: float = 2e-4, hours: float = 1.0, kexport: str = "", ids: str = "", dur: str = "dur_10v.pt",
mode: str = "kdur", extra: str = "/data/feat-*/shard_*.pt", no_main: bool = False, dur_ckpt: str = "",
voices: str = VOICES_DEFAULT, pv_init: str = "", pros_ckpt: str = "", bs: int = 0, size: str = "r2",
packs: str = "", pv_freeze: bool = False, balance: bool = False, dur_keep: str = "", r2_init: str = "", pros_init: str = "",
bucketed: bool = False):
"""teacher-head fine-tunes and the nano student (train.py): mode kpros (pitch/loudness branch + per-voice offsets pv), kdur (duration
head on the pace-window takes, pv frozen), r2distill (student text side copies the teacher; see ../distil/). bucketed: r2distill on
length-bucketed batches with 50 % short lines (nano B's student flt)."""
deadline = time.time() + hours * 3600
os.environ["KLINE_VOICES"] = voices
if pv_init:
os.environ["KLINE_PV_INIT"] = pv_init
if pros_ckpt:
os.environ["KLINE_PROS_CKPT"] = pros_ckpt
if pv_freeze:
os.environ["KLINE_PV_FREEZE"] = "1"
if dur_keep:
os.environ["KLINE_DUR_KEEP"] = dur_keep
if r2_init:
os.environ["KLINE_R2_INIT"] = r2_init
if pros_init:
os.environ["KLINE_PROS_INIT"] = pros_init
if balance:
os.environ["KLINE_BALANCE"] = "1"
if packs:
os.environ["KLINE_PACKS"] = packs
if kexport:
os.environ["KLINE_EXPORT"] = kexport
if ids:
os.environ["KLINE_IDS"] = ids
if dur_ckpt:
os.environ["KLINE_DUR_CKPT"] = dur_ckpt
Path(f"/data/run/{run}").mkdir(parents=True, exist_ok=True)
Path(f"/data/run/{run}/kdur_config.json").write_text(json.dumps(dict(kexport=kexport or "/t/export/teacher", ids=ids or "/data/feat/ids.json",
dur=dur, steps=steps, lr=lr, mode=mode, started=cet()), indent=1))
stop = threading.Event()
threading.Thread(target=_committer, args=(stop,), daemon=True).start()
try:
cmd = ["python", "train.py", mode, "--run", run, "--steps", str(steps), "--bs", str(bs) if bs else ("32" if mode == "kdur" else "16"), "--lr", str(lr), "--deadline", str(deadline), "--size", size,
"--extra", extra, "--dur", dur] + (["--no-main"] if no_main else []) + (["--bucketed"] if bucketed else [])
res = _run_many({mode: (cmd, f"/data/run/{run}/{mode}.stdout.log")}, deadline + 300, stall_s=15 * 60)
finally:
stop.set()
data.commit()
return res, Path(f"/data/run/{run}/{mode}/log.txt").read_text()[-2500:] if Path(f"/data/run/{run}/{mode}/log.txt").exists() else ""
@app.function(image=img, cpu=8, memory=32768, timeout=3600, max_containers=1, volumes=VOL)
def merge_lists(parts: list, out_ids: str, out_dur: str, out_keep: str = "", keep_parts: list = ()):
"""merge id lists / duration files / pace-window keep lists of several voices: parts [[ids json, dur .pt], ...]"""
import torch
kokoro_ids, dur, keep = {}, {}, []
for k, d in parts:
kokoro_ids.update(json.loads(Path(k).read_text())["rows"])
dur.update(torch.load(d, weights_only=False))
Path(out_ids).write_text(json.dumps(dict(rows=kokoro_ids)))
torch.save(dur, out_dur)
for p in keep_parts:
keep += json.loads(Path(p).read_text())
if out_keep:
Path(out_keep).write_text(json.dumps(sorted(set(keep))))
data.commit()
return dict(ids=len(kokoro_ids), dur=len(dur), missing_dur=len(set(kokoro_ids) - set(dur)), keep=len(set(keep)))
@app.function(image=img, cpu=2, memory=8192, timeout=900, max_containers=1, volumes=VOL)
def remap_rows(src: str, dst: str, old_voices: list, new_voices: list, keys: list = ("style", "pstyle", "pv")):
"""re-order a checkpoint's per-voice rows by NAME (old_voices -> new_voices). Voices new to the list start
from the mean of the kept rows. Works on {"model": state_dict, ...} checkpoints (KDec / R2Ac 'style', R2Text 'pstyle')."""
import torch
ck = torch.load(src, map_location="cpu", weights_only=False)
sd = ck["model"] if "model" in ck else ck
done = {}
for k in list(sd):
if k.split(".")[-1] in keys and sd[k].dim() == 2 and sd[k].shape[0] == len(old_voices):
old = sd[k]; mean = old.mean(0)
sd[k] = torch.stack([old[old_voices.index(v)] if v in old_voices else mean for v in new_voices]).clone()
done[k] = [list(old.shape), list(sd[k].shape)]
ck.pop("opt", None); ck.pop("opt_g", None); ck.pop("opt_d", None)
if isinstance(ck.get("voices"), list):
ck["voices"] = list(new_voices)
Path(dst).parent.mkdir(parents=True, exist_ok=True)
torch.save(ck, dst); data.commit()
return dict(dst=dst, remapped=done, kept=[v for v in new_voices if v in old_voices], new=[v for v in new_voices if v not in old_voices])
@app.function(image=img, cpu=4.0, memory=16384, timeout=3600, max_containers=1, scaledown_window=60, volumes=VOL)
def bundle_fn(krun: str, dur_ckpt: str, pros_ckpt: str, r2run: str, r2text: str, volcano_sents: list, out: str):
"""per-voice bundle for ../export/: tiny per voice (ek layout: e5.int8dec.onnx + voicepack f32 with the learned offset) and the R2s student per
voice (same ek layout, voice baked in) -> /data/export/<out>/"""
import importlib
import sys
import numpy as np
import torch
sys.path.insert(0, "/opt/recipe")
data.reload()
import onnx_export
od = Path(f"/data/export/{out}"); od.mkdir(parents=True, exist_ok=True)
K, km, _pack, kd, astep = _load_k(krun, "k", "cpu", dur_ckpt, pros_ckpt)
packs = K.load_packs("cpu"); pk = torch.load(pros_ckpt, map_location="cpu", weights_only=False)
info = {}
for vid, v in enumerate(K.VOICES):
pack = packs[v].clone(); pack[..., 128:] += pk["pv"][pk["voices"].index(v)]
np.asarray(pack.squeeze(1).float().numpy(), dtype=np.float32).tofile(od / f"vp-{v}.f32")
kv = K.KDec("k"); kv.load_state_dict(kd.state_dict()); kv.style = torch.nn.Parameter(kd.style[vid:vid + 1].detach().clone())
r = onnx_export.export_k(km, pack, kv.eval(), str(od / f"k-{v}"), volcano_sents)
info[f"k-{v}"] = dict(int8dec_mb=r["int8dec_mb"], cpu=r["int8dec"])
c = json.loads(Path(f"/data/run/{r2run}/config.json").read_text()); os.environ["KLINE_VOICES"] = c["voices"]
K = importlib.reload(K)
tck = torch.load(r2text, map_location="cpu", weights_only=False)
rt = K.R2Text(tck["width"]).eval(); rt.load_state_dict(tck["model"])
ra = K.R2Ac("r2").eval(); ra.load_state_dict(torch.load(f"/data/run/{r2run}/kdec/last.pt", map_location="cpu", weights_only=False)["model"])
info["r2"] = onnx_export.export_r2_ek(rt, ra, str(od / "r2"), volcano_sents, K.VOICES)
data.commit()
files = {f"k-{v}.int8dec.onnx": (od / f"k-{v}/e5.int8dec.onnx").read_bytes() for v in K.VOICES}
files.update({f"vp-{v}.f32": (od / f"vp-{v}.f32").read_bytes() for v in K.VOICES})
files.update({f"r2-{v}.int8dec.onnx": (od / f"r2/r2-{v}.int8dec.onnx").read_bytes() for v in K.VOICES})
return json.loads(json.dumps(info, default=float)), files
@app.local_entrypoint()
def export_release(config: str = "config/export.json", out: str = "out"):
"""the release exports from the finished runs (names in config/export.json): tiny per voice + packs with offsets and nano per voice
(bundle_fn), and nano as one multi-voice graph with a voice-id input (export_r2_fn). Files land in <out>/<name>/ for ../export/."""
c = json.loads((HERE / config).read_text())
vs = json.loads((HERE / c["volcano_ids"]).read_text())["sents"]
od = HERE / out
info, files = bundle_fn.remote(c["tiny_run"], c["dur_ckpt"], c["pros_ckpt"], c["nano_run"], c["nano_text"], vs, c["bundle_out"])
(od / c["bundle_out"]).mkdir(parents=True, exist_ok=True)
for n, b in files.items():
(od / c["bundle_out"] / n).write_bytes(b)
res, files = export_r2_fn.remote(c["nano_run"], "r2", c["nano_text"], vs, c["nano_out"])
(od / c["nano_out"]).mkdir(parents=True, exist_ok=True)
for n, b in files.items():
(od / c["nano_out"] / n).write_bytes(b)
print(json.dumps(dict(bundle=info, nano=res), indent=1, default=str))