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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import copy
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
import os
|
| 8 |
+
import time
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
from safetensors.torch import save_file
|
| 14 |
+
|
| 15 |
+
from audio_dit import AudioDiT
|
| 16 |
+
|
| 17 |
+
def cosine_lr(step, total, base, floor, warmup):
|
| 18 |
+
if step < warmup:
|
| 19 |
+
return base * (step + 1) / max(1, warmup)
|
| 20 |
+
t = (step - warmup) / max(1, total - warmup)
|
| 21 |
+
return floor + 0.5 * (base - floor) * (1 + math.cos(math.pi * t))
|
| 22 |
+
|
| 23 |
+
def load_split(data, split, dev):
|
| 24 |
+
meta = json.load(open(f"{data}/{split}_meta.json"))
|
| 25 |
+
mel = np.load(f"{data}/{split}_mel.npy")
|
| 26 |
+
seq = np.load(f"{data}/{split}_text_seq.npy")
|
| 27 |
+
pool = np.load(f"{data}/{split}_text_pool.npy")
|
| 28 |
+
ci = np.array(meta["pair_clip_idx"], dtype=np.int64)
|
| 29 |
+
return (torch.from_numpy(mel).to(dev), torch.from_numpy(seq).to(dev),
|
| 30 |
+
torch.from_numpy(pool).to(dev), torch.from_numpy(ci).to(dev), meta)
|
| 31 |
+
|
| 32 |
+
def main():
|
| 33 |
+
ap = argparse.ArgumentParser()
|
| 34 |
+
ap.add_argument("--data", default="/root/data")
|
| 35 |
+
ap.add_argument("--out", default="/root/runs/audio_v1")
|
| 36 |
+
ap.add_argument("--steps", type=int, default=90000)
|
| 37 |
+
ap.add_argument("--batch-size", type=int, default=128)
|
| 38 |
+
ap.add_argument("--lr", type=float, default=2e-4)
|
| 39 |
+
ap.add_argument("--min-lr", type=float, default=1e-6)
|
| 40 |
+
ap.add_argument("--warmup", type=int, default=500)
|
| 41 |
+
ap.add_argument("--cfg-dropout", type=float, default=0.1)
|
| 42 |
+
ap.add_argument("--ema", type=float, default=0.9999)
|
| 43 |
+
ap.add_argument("--val-every", type=int, default=2000)
|
| 44 |
+
ap.add_argument("--val-batch", type=int, default=256)
|
| 45 |
+
ap.add_argument("--log-every", type=int, default=200)
|
| 46 |
+
ap.add_argument("--save-every", type=int, default=5000)
|
| 47 |
+
ap.add_argument("--resume", default="")
|
| 48 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 49 |
+
args = ap.parse_args()
|
| 50 |
+
|
| 51 |
+
dev = "cuda"
|
| 52 |
+
os.makedirs(args.out, exist_ok=True)
|
| 53 |
+
torch.manual_seed(args.seed)
|
| 54 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 55 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 56 |
+
|
| 57 |
+
mel_t, seq_t, pool_t, ci_t, meta = load_split(args.data, "development", dev)
|
| 58 |
+
vmel_t, vseq_t, vpool_t, vci_t, vmeta = load_split(args.data, "validation", dev)
|
| 59 |
+
null_seq = torch.from_numpy(np.load(f"{args.data}/null_seq.npy")).to(dev).float()
|
| 60 |
+
null_pool = torch.from_numpy(np.load(f"{args.data}/null_pool.npy")).to(dev).float()
|
| 61 |
+
|
| 62 |
+
N = ci_t.shape[0]
|
| 63 |
+
x_res, y_res = meta["x_res"], meta["y_res"]
|
| 64 |
+
|
| 65 |
+
def mel_batch(mel_tensor, ci_tensor, idx):
|
| 66 |
+
return (mel_tensor[ci_tensor[idx]].float() / 127.5 - 1.0).unsqueeze(1)
|
| 67 |
+
|
| 68 |
+
vg = torch.Generator(device=dev).manual_seed(1234)
|
| 69 |
+
n_val = min(args.val_batch, vci_t.shape[0])
|
| 70 |
+
vidx = torch.arange(n_val, device=dev)
|
| 71 |
+
vx1 = mel_batch(vmel_t, vci_t, vidx)
|
| 72 |
+
vs = vseq_t[vidx].float()
|
| 73 |
+
vp = vpool_t[vidx].float()
|
| 74 |
+
vx0 = torch.randn(vx1.shape, device=dev, generator=vg)
|
| 75 |
+
vt = torch.sigmoid(torch.randn(vx1.shape[0], device=dev, generator=vg))
|
| 76 |
+
|
| 77 |
+
@torch.no_grad()
|
| 78 |
+
def val_loss():
|
| 79 |
+
ema.eval()
|
| 80 |
+
tb = vt.view(-1, 1, 1, 1)
|
| 81 |
+
xt = (1 - tb) * vx0 + tb * vx1
|
| 82 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 83 |
+
v = ema(xt, vt, vs, vp)
|
| 84 |
+
return F.mse_loss(v.float(), vx1 - vx0).item()
|
| 85 |
+
|
| 86 |
+
model = AudioDiT(x_res=x_res, y_res=y_res,
|
| 87 |
+
text_seq_dim=meta["seq_dim"], text_pool_dim=meta["pool_dim"]).to(dev)
|
| 88 |
+
ema = copy.deepcopy(model).eval()
|
| 89 |
+
for p in ema.parameters():
|
| 90 |
+
p.requires_grad_(False)
|
| 91 |
+
opt = torch.optim.AdamW(model.parameters(), lr=args.lr, betas=(0.9, 0.99), weight_decay=0.0)
|
| 92 |
+
|
| 93 |
+
start = 0
|
| 94 |
+
best_val = float("inf")
|
| 95 |
+
if args.resume and os.path.exists(args.resume):
|
| 96 |
+
ck = torch.load(args.resume, map_location=dev)
|
| 97 |
+
model.load_state_dict(ck["model"])
|
| 98 |
+
ema.load_state_dict(ck["ema"])
|
| 99 |
+
opt.load_state_dict(ck["opt"])
|
| 100 |
+
start = ck["step"] + 1
|
| 101 |
+
best_val = ck.get("best_val", float("inf"))
|
| 102 |
+
|
| 103 |
+
B = args.batch_size
|
| 104 |
+
gen = torch.Generator(device=dev).manual_seed(args.seed)
|
| 105 |
+
epochs = args.steps * B / N
|
| 106 |
+
print(f"[train] {N} train pairs ({meta['n_clips']} clips) + {n_val} val, "
|
| 107 |
+
f"{model.num_params()/1e6:.2f}M params, grid {model.grid_h}x{model.grid_w} "
|
| 108 |
+
f"({model.grid_h*model.grid_w} tokens)", flush=True)
|
| 109 |
+
print(f"[train] {args.steps} steps x batch {B} = {epochs:.0f} epochs, resume from {start}", flush=True)
|
| 110 |
+
|
| 111 |
+
logf = open(f"{args.out}/log.jsonl", "a")
|
| 112 |
+
running, t0 = 0.0, time.time()
|
| 113 |
+
for step in range(start, args.steps):
|
| 114 |
+
idx = torch.randint(0, N, (B,), device=dev, generator=gen)
|
| 115 |
+
x1 = mel_batch(mel_t, ci_t, idx)
|
| 116 |
+
s = seq_t[idx].float()
|
| 117 |
+
p = pool_t[idx].float()
|
| 118 |
+
drop = torch.rand(B, device=dev, generator=gen) < args.cfg_dropout
|
| 119 |
+
s = torch.where(drop[:, None, None], null_seq, s)
|
| 120 |
+
p = torch.where(drop[:, None], null_pool, p)
|
| 121 |
+
|
| 122 |
+
x0 = torch.randn(x1.shape, device=dev, generator=gen)
|
| 123 |
+
u = torch.randn(B, device=dev, generator=gen)
|
| 124 |
+
t = torch.sigmoid(u)
|
| 125 |
+
tb = t.view(-1, 1, 1, 1)
|
| 126 |
+
xt = (1 - tb) * x0 + tb * x1
|
| 127 |
+
target = x1 - x0
|
| 128 |
+
|
| 129 |
+
lr = cosine_lr(step, args.steps, args.lr, args.min_lr, args.warmup)
|
| 130 |
+
for g in opt.param_groups:
|
| 131 |
+
g["lr"] = lr
|
| 132 |
+
|
| 133 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 134 |
+
v = model(xt, t, s, p)
|
| 135 |
+
loss = F.mse_loss(v.float(), target)
|
| 136 |
+
opt.zero_grad(set_to_none=True)
|
| 137 |
+
loss.backward()
|
| 138 |
+
gn = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 139 |
+
opt.step()
|
| 140 |
+
with torch.no_grad():
|
| 141 |
+
d = 1 - args.ema
|
| 142 |
+
for pe, pm in zip(ema.parameters(), model.parameters()):
|
| 143 |
+
pe.mul_(args.ema).add_(pm.detach(), alpha=d)
|
| 144 |
+
|
| 145 |
+
running += loss.item()
|
| 146 |
+
if (step + 1) % args.log_every == 0:
|
| 147 |
+
avg = running / args.log_every
|
| 148 |
+
el = time.time() - t0
|
| 149 |
+
sps = args.log_every / el
|
| 150 |
+
eta = (args.steps - step - 1) / sps / 3600
|
| 151 |
+
print(f"[s{step+1:06d}] loss={avg:.5f} lr={lr:.2e} gnorm={gn:.2f} "
|
| 152 |
+
f"{sps:.2f} steps/s eta={eta:.2f}h", flush=True)
|
| 153 |
+
logf.write(json.dumps({"step": step + 1, "loss": avg, "lr": lr,
|
| 154 |
+
"gnorm": float(gn), "steps_per_s": sps}) + "\n")
|
| 155 |
+
logf.flush()
|
| 156 |
+
running, t0 = 0.0, time.time()
|
| 157 |
+
|
| 158 |
+
if (step + 1) % args.val_every == 0 or step + 1 == args.steps:
|
| 159 |
+
vl = val_loss()
|
| 160 |
+
tag = ""
|
| 161 |
+
if vl < best_val:
|
| 162 |
+
best_val = vl
|
| 163 |
+
save_file({k: v.contiguous() for k, v in ema.state_dict().items()},
|
| 164 |
+
f"{args.out}/model_best.safetensors")
|
| 165 |
+
json.dump({"step": step + 1, "val_loss": vl}, open(f"{args.out}/best.json", "w"))
|
| 166 |
+
tag = " (new best, saved model_best.safetensors)"
|
| 167 |
+
print(f"[s{step+1:06d}] val_loss={vl:.5f} (ema, {n_val} held out){tag}", flush=True)
|
| 168 |
+
logf.write(json.dumps({"step": step + 1, "val_loss": vl}) + "\n")
|
| 169 |
+
logf.flush()
|
| 170 |
+
t0 = time.time()
|
| 171 |
+
|
| 172 |
+
if (step + 1) % args.save_every == 0 or step + 1 == args.steps:
|
| 173 |
+
torch.save({"model": model.state_dict(), "ema": ema.state_dict(),
|
| 174 |
+
"opt": opt.state_dict(), "step": step, "best_val": best_val},
|
| 175 |
+
f"{args.out}/ckpt.pt")
|
| 176 |
+
save_file({k: v.contiguous() for k, v in ema.state_dict().items()},
|
| 177 |
+
f"{args.out}/model.safetensors")
|
| 178 |
+
print(f"[s{step+1:06d}] saved", flush=True)
|
| 179 |
+
|
| 180 |
+
json.dump({"dit": {"x_res": x_res, "y_res": y_res, "patch": 16, "dim": 384, "depth": 12,
|
| 181 |
+
"heads": 6, "text_seq_dim": meta["seq_dim"], "text_pool_dim": meta["pool_dim"]},
|
| 182 |
+
"mel": {"sample_rate": meta["sample_rate"], "n_fft": meta["n_fft"],
|
| 183 |
+
"hop_length": meta["hop_length"], "top_db": meta["top_db"]},
|
| 184 |
+
"steps": args.steps, "batch_size": args.batch_size,
|
| 185 |
+
"train_pairs": N, "train_clips": meta["n_clips"], "best_val": best_val},
|
| 186 |
+
open(f"{args.out}/config.json", "w"), indent=2)
|
| 187 |
+
print("TRAINDONE", flush=True)
|
| 188 |
+
|
| 189 |
+
if __name__ == "__main__":
|
| 190 |
+
main()
|