Download scripts/duplex/model/run.py from Trelis/duplex-0: direct link, hf CLI and curl.
- Browser
- Download file 43.1 kB
-
https://huggingface.co/Trelis/duplex-0/resolve/main/scripts/duplex/model/run.py
- Command line
-
hf download hf://Trelis/duplex-0/scripts/duplex/model/run.py
-
curl -L -o run.py https://huggingface.co/Trelis/duplex-0/resolve/main/scripts/duplex/model/run.py
43.1 kB
"""Bounded train/evaluate/generate jobs. No network or paid APIs.
`train` runs on one device, or data parallel under `torchrun --nproc-per-node N`:
every process draws the same batches and trains every Nth window of each, the loss
divides by the whole batch's weights and gradients are summed, so N processes
take the steps of one with the same batch, rate and draws, up to float rounding.
Process 0 writes the reports and checkpoints."""
import argparse
import dataclasses
import json
import math
import os
import resource
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from dataclasses import asdict
from pathlib import Path
import numpy as np
import torch
from torch import distributed as dist
from duplex.evaluation import loss as objective
from duplex.evaluation.loss import frame_nll, loss_and_stats, summarize
from duplex.evaluation.ngram import Floors
from . import checkpoint, streaming
from .network import (
TEXT_HEADS,
TEXT_OPTIONS,
TEXT_SHIFT,
Config,
DuplexModel,
factorization,
tiny_config,
with_text,
)
from .tokens import (
batch,
length_buckets,
read_manifest,
read_selection,
selected_windows,
sha256,
windows,
)
from .transfer import initialize_temporal
# Compilation (with its recompiles for dynamic text shapes) and allocator warmup
# dominate the first steps.
THROUGHPUT_WARMUP_STEPS = 20
# Share of the run's steps spent annealing when --anneal-steps is not given.
ANNEAL_FRACTION = 0.2
# Codebook 0 by frame position in the window: [0, 1), [1, 2), [2, 4), ... [2048, 4096).
POSITION_EDGES = [0, *(2**k for k in range(13))]
# The validation set and measure that pick the best checkpoint and stop a run.
BEST_SET, BEST_MEASURE = "pretraining", "first_codebook_bits_per_second"
def learning_rate(step, peak, warmup_steps, anneal_start, anneal_steps):
"""Rate for the update after `step` completed updates.
Linear warmup to peak, peak held constant, then a 1 - sqrt anneal toward
zero over anneal_steps from anneal_start. A function of the step alone, so
a resume needs no state, and two runs with the same warmup and peak share
every rate before the shorter one's anneal begins.
"""
if step < warmup_steps:
return peak * (step + 1) / warmup_steps
if not anneal_steps or step < anneal_start:
return peak
progress = min(1.0, (step - anneal_start) / anneal_steps)
return peak * (1 - math.sqrt(progress))
def warm_throughput(history, seconds):
"""Steps and frames per second over the steps no slower than three times the
median, and how many steps and seconds were left out."""
if not seconds:
return {}
limit = 3 * float(np.median(seconds))
kept = [(h, s) for h, s in zip(history, seconds, strict=True) if s <= limit]
total = sum(s for _, s in kept)
return {
"warm_steps_per_second": len(kept) / total,
"warm_scored_frames_per_second": sum(h["scored_frames"] for h, _ in kept)
/ total,
"slow_steps": len(seconds) - len(kept),
"slow_seconds": sum(seconds) - total,
}
def draw(frames_of, buckets, batch_size, context, generator):
"""Window indices of one batch and its padded length (None without buckets).
A drawn window trains every one of its frames, so drawing windows uniformly
gives every frame the same rate. A bucket holds rows in inverse proportion to
its padded length, so it is drawn in proportion to its windows times its padded
length, which keeps the rate per window, and per frame, the same in every bucket.
"""
if not buckets:
indices = torch.randint(len(frames_of), (batch_size,), generator=generator)
return indices.tolist(), None
keys = sorted(buckets)
weights = torch.tensor([len(buckets[k]) * k for k in keys], dtype=torch.float64)
padded = keys[torch.multinomial(weights, 1, generator=generator).item()]
group = buckets[padded]
rows = max(1, batch_size * context // padded)
chosen = torch.randint(len(group), (rows,), generator=generator)
return [group[i] for i in chosen.tolist()], padded
def main():
start = time.monotonic()
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("command", choices=("train", "evaluate", "generate"))
p.add_argument("--manifest", type=Path, required=True)
p.add_argument("--manifest-sha256", help="Expected immutable manifest hash")
p.add_argument("--experiment", type=Path, help="Fixed baseline experiment JSON")
p.add_argument("--selection", type=Path)
p.add_argument("--selection-evidence", type=Path)
p.add_argument(
"--allow-provisional-selection",
action="store_true",
help="Explicit diagnostic use only; does not qualify selected material",
)
p.add_argument("--root", type=Path, required=True)
p.add_argument("--checkpoint", type=Path, required=True)
p.add_argument("--output", type=Path, required=True)
p.add_argument("--config", choices=("tiny", "baseline"), default="tiny")
p.add_argument("--device", default="cpu")
p.add_argument(
"--steps", type=int, default=20, help="Total steps, including resumed steps"
)
p.add_argument("--batch-size", type=int, default=1)
p.add_argument("--lr", type=float, default=0.001)
p.add_argument("--seed", type=int, default=42)
p.add_argument("--warmup-steps", type=int, default=0, help="Linear warmup to --lr")
p.add_argument(
"--anneal-steps",
type=int,
help="Final steps that anneal --lr toward zero; default 20%% of --steps, "
"0 keeps --lr constant",
)
p.add_argument(
"--anneal-start",
type=int,
help="Step the anneal begins; default --steps minus --anneal-steps",
)
p.add_argument(
"--bucket-frames",
type=int,
default=0,
help="Batch windows of similar length, padded to a multiple of this; 0 is off",
)
p.add_argument("--resume", action="store_true")
p.add_argument(
"--init-from",
type=Path,
help="Start a new training stage from this checkpoint's weights: "
"fresh optimizer and step count, this run's manifest",
)
p.add_argument(
"--text",
choices=sorted(TEXT_OPTIONS),
default="none",
help="Training option: audio only, track 2's text, or both tracks' text",
)
p.add_argument(
"--listen-delay",
type=int,
help="New model: frames after each word's start that track 1 writes it "
f"(default {-TEXT_SHIFT[0]}); a later stage keeps its checkpoint's",
)
p.add_argument(
"--text-heads",
choices=TEXT_HEADS,
help="New model: one text head for both tracks (default) or one per track",
)
p.add_argument(
"--eval-every",
type=int,
default=0,
help="Score the validation split before training, every this many steps "
"and at the end; 0 is off",
)
p.add_argument(
"--patience",
type=int,
default=0,
help="Stop after this many evaluations in a row without a new best held-out "
"codebook 0; 0 trains to --steps",
)
p.add_argument(
"--item", type=int, default=0, help="Chunk of the split used as the prompt"
)
p.add_argument(
"--overfit", action="store_true", help="Train first train window repeatedly"
)
p.add_argument(
"--split", choices=("train", "validation", "test"), default="validation"
)
p.add_argument(
"--stage-gate",
action="store_true",
help="Explicit acknowledgement for frozen test scoring",
)
p.add_argument("--frames", type=int, default=16)
p.add_argument("--prefix-frames", type=int, default=16)
p.add_argument("--save-every", type=int, default=20)
p.add_argument("--threads", type=int, default=1)
p.add_argument(
"--precision",
choices=("float32", "bf16"),
default="float32",
help="bf16 is the CUDA fast path: bf16 autocast, TF32 and fused AdamW",
)
p.add_argument(
"--compile", action="store_true", help="torch.compile the training forward"
)
p.add_argument(
"--deterministic",
action="store_true",
help="bitwise repeatable CUDA steps, so a resume matches an uninterrupted run",
)
p.add_argument("--nanochat-weights", type=Path)
p.add_argument("--nanochat-metadata", type=Path)
p.add_argument("--nanochat-revision")
preliminary, _ = p.parse_known_args()
if preliminary.experiment:
experiment = json.loads(preliminary.experiment.read_text())
if Config(**experiment["model"]) != Config() or set(experiment) != {
"model",
"training",
}:
p.error("Experiment must specify the unchanged baseline architecture")
if set(experiment["training"]) != {
"batch_size",
"lr",
"seed",
"steps",
"save_every",
"threads",
}:
p.error("Unexpected experiment training fields")
p.set_defaults(config="baseline", **experiment["training"])
args = p.parse_args()
if args.experiment and (
args.config != "baseline"
or args.nanochat_weights
or args.overfit
or args.text != "none"
):
p.error("Fixed baseline experiment requires scratch baseline without overfit")
if not math.isfinite(args.lr) or args.lr <= 0:
p.error("lr must be finite and positive")
if (args.listen_delay is not None or args.text_heads) and (
args.resume or args.init_from or args.experiment
):
p.error("--listen-delay and --text-heads set a new model's layout")
if args.listen_delay is not None and args.listen_delay < 0:
p.error("--listen-delay must be nonnegative")
if args.patience < 0 or (args.patience and not args.eval_every):
p.error("--patience needs --eval-every and must be nonnegative")
if (
min(
args.steps,
args.batch_size,
args.save_every,
args.threads,
args.prefix_frames,
)
< 1
):
p.error("steps/batch-size/save-every/threads/prefix-frames must be positive")
if min(args.warmup_steps, args.bucket_frames, args.eval_every) < 0:
p.error("warmup-steps/bucket-frames/eval-every must be nonnegative")
if args.init_from and (
args.resume
or args.command != "train"
or args.experiment
or args.nanochat_weights
):
p.error(
"--init-from starts a fresh training run without experiment or transfer"
)
if args.resume and args.anneal_steps is None and args.anneal_start is None:
# A resumed run keeps its checkpoint's anneal even when it extends --steps.
saved = torch.load(
args.checkpoint, map_location="cpu", mmap=True, weights_only=True
)
schedule = saved["provenance"].get("schedule", {})
args.anneal_steps = schedule.get("anneal_steps", 0)
args.anneal_start = schedule.get("anneal_start") or 0
if args.anneal_steps is None:
args.anneal_steps = round(ANNEAL_FRACTION * args.steps)
if args.anneal_start is None:
args.anneal_start = args.steps - args.anneal_steps
if args.anneal_steps < 0 or (
args.anneal_steps and args.anneal_start < args.warmup_steps
):
p.error("The anneal must be nonnegative and begin after warmup")
if args.bucket_frames and args.overfit:
p.error("--bucket-frames does not apply to --overfit")
if args.split == "train" and args.command != "generate":
p.error("--split train is only for explicitly in-sample generation diagnostics")
if args.split == "test" and not args.stage_gate:
p.error("Test is reserved for stage gates; pass --stage-gate")
if bool(args.selection) != bool(args.selection_evidence):
p.error("--selection and --selection-evidence must be supplied together")
if args.allow_provisional_selection and not args.selection:
p.error("--allow-provisional-selection requires --selection")
transfer_args = (
args.nanochat_weights,
args.nanochat_metadata,
args.nanochat_revision,
)
if any(transfer_args) and (
not all(transfer_args) or args.resume or args.command != "train"
):
p.error(
"Partial transfer needs all three nanochat flags on a fresh training run"
)
world = int(os.environ.get("WORLD_SIZE", "1"))
rank = int(os.environ.get("RANK", "0"))
if world > 1:
if args.command != "train" or args.overfit or args.deterministic:
p.error(
"Data parallel runs train only, without --overfit or --deterministic"
)
if args.device.startswith("cuda"):
# "cuda" names each process's own device from here on.
torch.cuda.set_device(int(os.environ["LOCAL_RANK"]))
dist.init_process_group("nccl")
else:
dist.init_process_group("gloo")
if rank:
sys.stdout = open(os.devnull, "w") # noqa: SIM115 - for the process's life
fast = args.precision == "bf16"
if fast and not args.device.startswith("cuda"):
p.error("--precision bf16 requires a CUDA device")
torch.backends.cuda.matmul.allow_tf32 = fast
torch.backends.cudnn.allow_tf32 = fast
if args.deterministic:
# The fused attention kernels (flash, memory-efficient, cuDNN) have a
# nondeterministic backward; the math kernel is repeatable but holds
# the full attention matrix. Compiled code varies between processes,
# so the mode is eager only.
if args.compile:
p.error("--deterministic cannot be combined with --compile")
os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
torch.backends.cuda.enable_flash_sdp(False)
torch.backends.cuda.enable_mem_efficient_sdp(False)
torch.backends.cuda.enable_cudnn_sdp(False)
torch.use_deterministic_algorithms(True)
torch.set_num_threads(args.threads)
torch.manual_seed(args.seed)
sampler = torch.Generator().manual_seed(args.seed)
manifest_hash = sha256(args.manifest)
if args.manifest_sha256 and manifest_hash != args.manifest_sha256:
raise ValueError("Expected manifest hash mismatch")
rows = read_manifest(args.manifest)
selection = None
if args.selection:
selection = read_selection(
args.selection, args.manifest, args.selection_evidence
)
if not args.allow_provisional_selection or args.split == "test":
raise ValueError(
"Provisional selection requires explicit diagnostic opt-in; no test use"
)
if args.split == "test" and any(
r.get("split_status") not in ("frozen_source_disjoint", "published_group_split")
for r in rows
):
raise ValueError("Provisional split cannot support a test stage gate")
provenance = {
"arm": "scratch",
"manifest_sha256": manifest_hash,
"codec": rows[0]["codec"],
"seed": args.seed,
"batch_size": args.batch_size,
"overfit": args.overfit,
"loader": "two-track-text-windows-v3",
"text": args.text,
"lr": args.lr,
"schedule": {
"warmup_steps": args.warmup_steps,
"anneal_start": args.anneal_start if args.anneal_steps else None,
"anneal_steps": args.anneal_steps,
"anneal": "1-sqrt to zero",
},
"bucket_frames": args.bucket_frames,
"precision": args.precision,
"compile": args.compile,
"deterministic": args.deterministic,
"experiment_sha256": sha256(args.experiment) if args.experiment else None,
"resume_runtime": {
"device": args.device,
"threads": args.threads,
"torch": str(torch.__version__),
"objective_sha256": sha256(objective.__file__),
"implementation_sha256": {
name: sha256(Path(__file__).with_name(name))
for name in (
"run.py",
"tokens.py",
"network.py",
"kernels.py",
"checkpoint.py",
)
},
},
}
if selection is not None:
provenance["selection"] = {
"sha256": sha256(args.selection),
"evidence_sha256": selection["evidence_sha256"],
"policy_version": selection["policy_version"],
"qualification_status": selection["qualification_status"],
}
if args.resume or args.command != "train":
model, state = checkpoint.load(args.checkpoint, args.device)
if state["provenance"]["codec"] != rows[0]["codec"]:
raise ValueError("Checkpoint codec mismatch")
if state["provenance"]["manifest_sha256"] != provenance["manifest_sha256"]:
raise ValueError(
"Use the checkpoint's frozen train/validation/test candidate pool"
)
if state["provenance"].get("selection") != provenance.get("selection"):
raise ValueError("Checkpoint selection provenance mismatch")
if args.resume and any(
state["provenance"].get(k) != provenance[k]
for k in (
"seed",
"batch_size",
"overfit",
"loader",
"lr",
"schedule",
"bucket_frames",
"text",
"precision",
"compile",
"deterministic",
"experiment_sha256",
"resume_runtime",
)
):
raise ValueError("Resume data/seed/batching provenance mismatch")
if state["provenance"].get("loader") != provenance["loader"]:
raise ValueError(
"Checkpoint predates final chunking; use its original runner"
)
if args.experiment and model.config != Config(**experiment["model"]):
raise ValueError("Checkpoint architecture differs from experiment")
provenance = state["provenance"]
else:
if args.checkpoint.exists():
raise ValueError("Checkpoint exists; use --resume or a new path")
if args.init_from:
# The previous stage's weights and architecture; its optimizer and step stay behind.
model, earlier = checkpoint.load(args.init_from, args.device)
if earlier["provenance"]["codec"] != rows[0]["codec"]:
raise ValueError("Initial checkpoint codec mismatch")
provenance["arm"] = "staged"
provenance["init_from"] = {
"sha256": sha256(args.init_from),
"step": earlier["step"],
"text": model.config.text,
"provenance": earlier["provenance"],
}
if model.config.text != args.text:
model = with_text(model, args.text)
else:
layout = {}
if args.listen_delay is not None:
layout["text_shift"] = (-args.listen_delay, TEXT_SHIFT[1])
if args.text_heads:
layout["text_heads"] = args.text_heads
model = DuplexModel(
dataclasses.replace(
tiny_config(args.text)
if args.config == "tiny"
else Config(text=args.text),
**layout,
)
).to(args.device)
if args.nanochat_weights:
provenance.update(
initialize_temporal(
model,
args.nanochat_weights,
args.nanochat_metadata,
source_revision=args.nanochat_revision,
)
)
report = {
"command": args.command,
"config": asdict(model.config),
"factorization": factorization(model.config),
"provenance": provenance,
"evaluation_manifest_sha256": sha256(args.manifest),
"seed": args.seed,
"split_status": sorted({r.get("split_status", "unspecified") for r in rows}),
"device": args.device,
"torch_version": str(torch.__version__),
"execution": {
"steps": args.steps,
"save_every": args.save_every,
"threads": args.threads,
"processes": world,
},
"cost_usd": None,
"cost_note": "Caller records rental cost; no APIs invoked",
}
def examples(split, keep=None):
chosen = rows if keep is None else [r for r in rows if keep(r)]
if selection is not None:
return selected_windows(
chosen,
args.root,
split,
model.config.context,
selection,
args.text,
model.config.text_shift,
)
return windows(
chosen,
args.root,
split,
model.config.context,
args.text,
model.config.text_shift,
)
def validation_sets():
"""Each named validation set; rows tagged in `validation_sets` belong to
every set they name, and untagged manifests have one set."""
held = [r for r in rows if r["split"] == "validation"]
names = sorted({n for r in held for n in r.get("validation_sets") or ()})
if not names:
return {"validation": examples("validation")}
return {
name: examples(
"validation", lambda r, n=name: n in (r.get("validation_sets") or ())
)
for name in names
}
def codebook0(item):
"""Codebook 0 of each present track of a window, the floors' sequences."""
# A copy, so the window's [frames, 16] int64 array is freed.
return [
item.audio[:, 8 * j].numpy().astype(np.int32)
for j in range(2)
if item.present[j] and len(item)
]
floors = None
def fit_floors():
"""Counted on the training windows, weights chosen on 5% of them."""
items = examples("train")
train, holdout = [], []
rng = np.random.default_rng(args.seed)
for i in range(len(items)):
(holdout if rng.random() < 0.05 else train).extend(codebook0(items[i]))
return Floors(train, holdout)
def score(items):
"""Additive statistics over every window, one at a time; updates nothing.
Odd windows swap their tracks, so a set is fixed and uses both tracks."""
training = model.training
model.eval()
parts, sequences = [], []
bins = len(POSITION_EDGES) - 1
position_nats = np.zeros(bins)
position_frames = np.zeros(bins)
edges = np.array(POSITION_EDGES)
with torch.no_grad():
# Under data parallelism each process scores every Nth window.
for index in range(rank, len(items), world):
item = items[index]
if index % 2:
item = item.swapped()
tokens, valid, text = batch([item], args.device, args.text)
audio, text_logits = model(tokens, valid, text)
scored = valid[..., model.track_of]
_, stats = loss_and_stats(
audio,
tokens,
scored,
model.config.fps,
model.config.codebooks,
text_logits,
None if text is None else text.event_target,
None if text is None else text.event_weight,
text_tracks=None if text is None else text.event_track,
)
parts.append((index, stats))
sequences.append((index, codebook0(item)))
first = (frame_nll(audio, tokens) * scored)[0, :, ::8].sum(-1)
where = np.searchsorted(edges, np.arange(len(item)), side="right") - 1
np.add.at(position_nats, where, first.double().cpu().numpy())
np.add.at(position_frames, where, scored[0].any(-1).cpu().numpy())
model.train(training)
if world > 1:
gathered = [None] * world
dist.all_gather_object(gathered, (parts, sequences))
parts = [x for g in gathered for x in g[0]]
sequences = [x for g in gathered for x in g[1]]
counts = torch.tensor(
np.stack((position_nats, position_frames)), device=args.device
)
dist.all_reduce(counts)
position_nats, position_frames = counts.cpu().numpy()
# Window order, as one process sums them.
parts = [x for _, x in sorted(parts, key=lambda x: x[0])]
sequences = [x for _, xs in sorted(sequences, key=lambda x: x[0]) for x in xs]
result = summarize(parts)
if floors is not None:
bigram, trigram = floors.nats(sequences)
bits = math.log(2) * result["scored_seconds"]
result["first_codebook_floors_bits_per_second"] = {
"bigram": bigram.sum() / bits,
"trigram": trigram.sum() / bits,
}
fps = model.config.fps
result["first_codebook_bits_per_second_by_position"] = [
{
"frames": [int(edges[i]), int(edges[i + 1])],
"scored_frames": int(position_frames[i]),
"bits_per_second": position_nats[i]
/ math.log(2)
/ (position_frames[i] / fps),
}
for i in range(bins)
if position_frames[i]
]
return result
def score_sets(sets):
return {name: score(items) for name, items in sets.items()}
def reduce_sum(tensor):
dist.all_reduce(tensor)
return tensor
def merged(loss, stats, padded):
"""The whole batch's loss, statistics and padded frames, summed over the
processes; each process's loss is its part of the whole batch's."""
keys = sorted(stats)
values = [loss.detach().double(), torch.tensor(float(padded))]
for k in keys:
v = stats[k]
values.extend(float(x) for x in (v if isinstance(v, list) else [v]))
total = reduce_sum(
torch.tensor(
[float(v) for v in values], dtype=torch.float64, device=args.device
)
).tolist()
loss, padded, rest = total[0], int(total[1]), total[2:]
out = {}
for k in keys:
v = stats[k]
n = len(v) if isinstance(v, list) else 1
part, rest = rest[:n], rest[n:]
# Counts stay integers.
if isinstance(v if not isinstance(v, list) else (v or [0.0])[0], int):
part = [round(x) for x in part]
out[k] = part if isinstance(v, list) else part[0]
return loss, out, padded
if args.command == "train":
items = examples("train")
held = validation_sets() if args.eval_every else None
if held is not None:
floors = fit_floors()
best_path = args.checkpoint.with_name(args.checkpoint.stem + ".best.pt")
best = {BEST_MEASURE: math.inf, "since": 0}
validation = []
optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, fused=fast)
# Shapes vary from batch to batch with text and buckets; dynamic from the start,
# the forward compiles once and the cross entropy once for audio and once for
# text, instead of recompiling as each dimension first changes. Compiled, the
# cross entropy reads the bf16 logits without a float32 copy.
forward = torch.compile(model, dynamic=True) if args.compile else model
nll = torch.compile(frame_nll, dynamic=True) if args.compile else frame_nll
step = 0
if args.resume:
checkpoint.resume(state, optimizer, sampler)
step = state["step"]
if args.steps <= step:
raise ValueError("Resume total steps must exceed saved step")
# Checkpoints before the codebook 0 measure kept audio bits instead.
saved = state["provenance"].get("best") or {}
if BEST_MEASURE in saved:
best = {"since": 0, **saved}
buckets = (
length_buckets(items, args.bucket_frames) if args.bucket_frames else {}
)
frames_of = torch.tensor(
[items.frames(i) for i in range(len(items))], dtype=torch.float64
)
model.train()
history = []
timed_steps = timed_frames = timed_scored = 0
timed_wait = 0.0
# Wall time of each step, kept out of the history so that it stays repeatable.
step_seconds = []
utilization = []
timing_start = None
cuda = args.device.startswith("cuda")
# The next batch is built on a worker while the device runs the current step.
# Indices and swaps are drawn here, in step order, and a checkpoint saves the
# sampler as it was before the next batch was drawn, so a resume draws the
# same batches as an uninterrupted run.
workers = ThreadPoolExecutor(1)
def prepare():
before = sampler.get_state()
frames = None
if args.overfit:
indices = [0] * args.batch_size
else:
indices, frames = draw(
frames_of, buckets, args.batch_size, model.config.context, sampler
)
# Each window swaps its tracks with probability one half.
swaps = (torch.rand(len(indices), generator=sampler) < 0.5).tolist()
indices, swaps = indices[rank::world], swaps[rank::world]
def build():
chosen = [
items[i].swapped() if swap else items[i]
for i, swap in zip(indices, swaps, strict=True)
]
return batch(chosen, "cpu", args.text, frames)
return before, workers.submit(build)
earlier_frames = provenance.get("frames_seen", 0) if args.resume else 0
def frames_seen():
"""Real frames trained by this run, resumed processes included; saved
with every checkpoint."""
provenance["frames_seen"] = earlier_frames + sum(
h["scored_frames"] for h in history
)
return provenance["frames_seen"]
def resumable():
"""The sampler as a resume must find it: before any batch not yet trained."""
if pending is None:
return sampler
state = torch.Generator()
state.set_state(pending[0])
return state
def write_progress():
if rank:
return
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(
json.dumps(
{
**report,
"in_progress": True,
"step": step,
"validation": validation,
"history": history,
}
)
+ "\n"
)
def validate():
mark = time.monotonic()
recent = [h["loss"] for h in history[-args.eval_every :]]
sets = score_sets(held)
# Epochs: real frames trained so far over this run's training frames.
seen = frames_seen()
validation.append(
{
"step": step,
"epoch": seen / items.total_frames,
"frames_seen": seen,
"seconds": time.monotonic() - mark,
"sets": sets,
}
)
chosen = sets.get(BEST_SET) or next(iter(sets.values()))
if step and chosen[BEST_MEASURE] < best[BEST_MEASURE]:
best.update(step=step, since=0, **{BEST_MEASURE: chosen[BEST_MEASURE]})
provenance["best"] = dict(best)
if not rank:
checkpoint.save(
best_path, model, optimizer, step, provenance, resumable()
)
elif step:
best["since"] += 1
provenance["best"] = dict(best)
write_progress()
print(
json.dumps(
{
"step": step,
"train_loss_recent_mean": sum(recent) / len(recent)
if recent
else None,
"validation": {
name: {
k: v[k]
for k in (
"bits_per_second",
"first_codebook_bits_per_second",
"first_codebook_floors_bits_per_second",
"text_bits_per_second",
"track_text_bits_per_second",
"track_word_bits_per_token",
)
if k in v
}
for name, v in sets.items()
},
}
),
flush=True,
)
return time.monotonic() - mark
pending = None
if args.eval_every and not args.resume:
validate()
pending = prepare()
while step < args.steps:
waited = started = time.monotonic()
tokens, valid, text = pending[1].result()
tokens, valid = tokens.to(args.device), valid.to(args.device)
if text is not None:
text = dataclasses.replace(
text,
**{
f.name: getattr(text, f.name).to(args.device)
for f in dataclasses.fields(text)
},
)
pending = prepare() if step + 1 < args.steps else None
waited = time.monotonic() - waited
rate = learning_rate(
step, args.lr, args.warmup_steps, args.anneal_start, args.anneal_steps
)
for group in optimizer.param_groups:
group["lr"] = rate
optimizer.zero_grad(set_to_none=True)
with torch.autocast("cuda", torch.bfloat16, enabled=fast):
audio, text_logits = forward(tokens, valid, text)
loss, stats = loss_and_stats(
audio,
tokens,
valid[..., model.track_of],
model.config.fps,
model.config.codebooks,
text_logits,
None if text is None else text.event_target,
None if text is None else text.event_weight,
text_tracks=None if text is None else text.event_track,
nll=nll,
reduce=reduce_sum if world > 1 else None,
)
loss.backward()
padded = tokens.shape[0] * tokens.shape[1]
if world > 1:
# Sum the processes' gradients, then losses and statistics.
grads = [q.grad for q in model.parameters() if q.grad is not None]
flat = reduce_sum(torch.cat([g.reshape(-1) for g in grads]))
for g, part in zip(
grads, flat.split([g.numel() for g in grads]), strict=True
):
g.copy_(part.view_as(g))
loss, stats, padded = merged(loss, stats, padded)
torch.nn.utils.clip_grad_norm_(
model.parameters(), 1.0, error_if_nonfinite=True
)
optimizer.step()
step += 1
history.append(
{
"step": step,
"lr": rate,
"loss": loss.item() if torch.is_tensor(loss) else loss,
**summarize([stats]),
}
)
# The loss read above waits for the device, so this covers the step.
step_seconds.append(time.monotonic() - started)
# The loss read above waits for the device, so wall time covers the step.
if timing_start is None:
if len(history) == THROUGHPUT_WARMUP_STEPS:
timing_start = time.monotonic()
if cuda:
torch.cuda.reset_peak_memory_stats()
else:
timed_steps += 1
timed_frames += padded
timed_scored += history[-1]["scored_frames"]
timed_wait += waited
timed_seconds = time.monotonic() - timing_start
if cuda:
utilization.append(torch.cuda.utilization())
if step % args.save_every == 0 and not rank:
frames_seen()
checkpoint.save(
args.checkpoint, model, optimizer, step, provenance, resumable()
)
if args.eval_every and (step % args.eval_every == 0 or step == args.steps):
# Validation time stays out of the throughput figure.
spent = validate()
if timing_start is not None:
timing_start += spent
if args.patience and best["since"] >= args.patience:
break
workers.shutdown()
frames_seen()
if not rank:
checkpoint.save(
args.checkpoint, model, optimizer, step, provenance, sampler
)
report.update(
step=step,
history=history,
step_seconds=step_seconds,
validation=validation,
best=best if best[BEST_MEASURE] < math.inf else None,
stopped_early=step < args.steps,
best_checkpoint=str(best_path) if best_path.exists() else None,
candidate_train_frames=items.total_frames,
candidate_train_chunks=len(items),
run_exposure_frames=sum(s["scored_frames"] for s in history),
overfit=args.overfit,
throughput=(
{
"steps": timed_steps,
"excluded_warmup_steps": THROUGHPUT_WARMUP_STEPS,
"steps_per_second": timed_steps / timed_seconds,
"padded_frames_per_second": timed_frames / timed_seconds,
"scored_frames_per_second": timed_scored / timed_seconds,
# Waiting for the next batch, with the device idle.
"data_wait_share": timed_wait / timed_seconds,
"gpu_utilization_percent": sum(utilization) / len(utilization)
if utilization
else None,
"peak_gpu_memory_allocated_bytes": torch.cuda.max_memory_allocated()
if cuda
else None,
"peak_gpu_memory_reserved_bytes": torch.cuda.max_memory_reserved()
if cuda
else None,
# Warm: without steps over three times the median, which are
# recompiles for new shapes or checkpoint saves.
**warm_throughput(
history[-timed_steps:], step_seconds[-timed_steps:]
),
"note": "Includes checkpoint saves; padding counts; no evaluation",
}
if timed_steps
else None
),
)
elif args.command == "evaluate":
if args.split == "validation":
floors = fit_floors()
report.update(split=args.split, sets=score_sets(validation_sets()))
else:
report.update(
split=args.split, sets={args.split: score(examples(args.split))}
)
else:
model.eval()
items = examples(args.split)
source = items[args.item]
report["source_chunk"] = items.metadata(args.item)
recording_id = report["source_chunk"]["recording"]["recording_id"]
if selection is not None:
chosen = next(
s for s in selection["selections"] if s["split"] == args.split
)
report["selection_window"] = chosen
prefix = source.audio[: args.prefix_frames]
frames = torch.cat(
(prefix, torch.full((args.frames, 16), streaming.SAMPLE, dtype=torch.long))
)
for j, present in enumerate(source.present):
if not present:
frames[:, 8 * j : 8 * j + 8] = streaming.ABSENT
generator = torch.Generator(args.device).manual_seed(args.seed)
generated, text = streaming.generate(
model, frames.to(args.device), generator=generator
)
generated = generated.clamp(min=0)
args.output.parent.mkdir(parents=True, exist_ok=True)
token_path = args.output.with_suffix(".npy")
np.save(
token_path,
generated.cpu().numpy().T.astype(np.uint16),
allow_pickle=False,
)
report.update(
tokens_path=str(token_path),
tokens_sha256=sha256(token_path),
# Track p's text written at frame s is the words starting at frame
# s + its shift.
text={str(track + 1): ids for track, ids in text.items()},
text_shift_frames={
str(track + 1): shift
for track, shift in enumerate(model.config.text_shift)
},
tracks_present=source.present,
recording_id=recording_id,
prefix_frames=len(prefix),
generated_frames=args.frames,
temperature=streaming.TEMPERATURE,
top_k=streaming.TOP_K,
split=args.split,
in_sample_diagnostic=args.split == "train",
)
if world > 1:
dist.barrier()
dist.destroy_process_group()
if rank:
return
report.update(
runtime_seconds=time.monotonic() - start,
checkpoint_sha256=sha256(args.checkpoint),
peak_process_rss_bytes=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
* 1024,
)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps({k: v for k, v in report.items() if k != "history"}))
if __name__ == "__main__":
main()
"""Bounded train/evaluate/generate jobs. No network or paid APIs.
`train` runs on one device, or data parallel under `torchrun --nproc-per-node N`:
every process draws the same batches and trains every Nth window of each, the loss
divides by the whole batch's weights and gradients are summed, so N processes
take the steps of one with the same batch, rate and draws, up to float rounding.
Process 0 writes the reports and checkpoints."""
import argparse
import dataclasses
import json
import math
import os
import resource
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from dataclasses import asdict
from pathlib import Path
import numpy as np
import torch
from torch import distributed as dist
from duplex.evaluation import loss as objective
from duplex.evaluation.loss import frame_nll, loss_and_stats, summarize
from duplex.evaluation.ngram import Floors
from . import checkpoint, streaming
from .network import (
TEXT_HEADS,
TEXT_OPTIONS,
TEXT_SHIFT,
Config,
DuplexModel,
factorization,
tiny_config,
with_text,
)
from .tokens import (
batch,
length_buckets,
read_manifest,
read_selection,
selected_windows,
sha256,
windows,
)
from .transfer import initialize_temporal
# Compilation (with its recompiles for dynamic text shapes) and allocator warmup
# dominate the first steps.
THROUGHPUT_WARMUP_STEPS = 20
# Share of the run's steps spent annealing when --anneal-steps is not given.
ANNEAL_FRACTION = 0.2
# Codebook 0 by frame position in the window: [0, 1), [1, 2), [2, 4), ... [2048, 4096).
POSITION_EDGES = [0, *(2**k for k in range(13))]
# The validation set and measure that pick the best checkpoint and stop a run.
BEST_SET, BEST_MEASURE = "pretraining", "first_codebook_bits_per_second"
def learning_rate(step, peak, warmup_steps, anneal_start, anneal_steps):
"""Rate for the update after `step` completed updates.
Linear warmup to peak, peak held constant, then a 1 - sqrt anneal toward
zero over anneal_steps from anneal_start. A function of the step alone, so
a resume needs no state, and two runs with the same warmup and peak share
every rate before the shorter one's anneal begins.
"""
if step < warmup_steps:
return peak * (step + 1) / warmup_steps
if not anneal_steps or step < anneal_start:
return peak
progress = min(1.0, (step - anneal_start) / anneal_steps)
return peak * (1 - math.sqrt(progress))
def warm_throughput(history, seconds):
"""Steps and frames per second over the steps no slower than three times the
median, and how many steps and seconds were left out."""
if not seconds:
return {}
limit = 3 * float(np.median(seconds))
kept = [(h, s) for h, s in zip(history, seconds, strict=True) if s <= limit]
total = sum(s for _, s in kept)
return {
"warm_steps_per_second": len(kept) / total,
"warm_scored_frames_per_second": sum(h["scored_frames"] for h, _ in kept)
/ total,
"slow_steps": len(seconds) - len(kept),
"slow_seconds": sum(seconds) - total,
}
def draw(frames_of, buckets, batch_size, context, generator):
"""Window indices of one batch and its padded length (None without buckets).
A drawn window trains every one of its frames, so drawing windows uniformly