gso-orbit-rgba / run_ai_toolkit.py
ysharma's picture
ysharma HF Staff
Loss feed from trainer stdout (sqlite UILogger stays empty); accurate step timing from tqdm elapsed
a85163a verified
Raw History Blame Contribute Delete
12 kB
#!/usr/bin/env python
"""Bootstrap ai-toolkit training for the Qwen-Image-2.1 RGBA orbit LoRA.
Runs inside the job container:
1. clone ostris/ai-toolkit (main), install the system libs cv2 needs
(libGL / glib — the uv base image lacks them), pip install requirements,
then install torchaudio (imported unconditionally by
toolkit/config_modules.py but absent from ai-toolkit requirements)
and trackio (loss dashboard)
2. materialize targets/ + controls/ from the mounted dataset repo (/ds)
with the transparency sentence appended (won the caption A/B)
3. write the training YAML (qwen_image_2 arch, rgba: true, rank 32)
4. launch `python run.py <yaml>`, teeing stdout to /work/train_stdout.log
5. side thread parses the tqdm loss lines from that stdout and pushes
loss -> Trackio. (ai-toolkit's UI logger writes loss_log.db but leaves
the metrics table empty until process exit, so stdout is the source.)
6. on success, upload every saved .safetensors PLUS train_stdout.log and a
loss dump (loss_log.jsonl) to the Hub repo — the job log API truncates
its middle, so the loss curve must live on the Hub.
Timing note: wall clock around run.py includes model load + latent caching,
so the real s/step is taken from the tqdm elapsed clock, not from t0.
Usage:
python run_ai_toolkit.py --steps 50 --resolution 768 \
--trackio-space ysharma/<space_id>
Env: HF_TOKEN (required for upload), dataset repo mounted read-only at /ds.
"""
import argparse
import glob
import json
import os
import re
import sqlite3
import subprocess
import sys
import threading
import time
from pathlib import Path
DS_ROOT = Path("/ds")
AITK_URL = "https://github.com/ostris/ai-toolkit.git"
WORK = Path("/work")
LORA_REPO = "ysharma/orbit-alpha-lora"
PROJECT = "qwen21-rgba-orbit-lora"
TQDM_RE = re.compile(r"(\d+)/(\d+) \[(\d+):(\d+)<[^\]]*?loss: ([0-9.eE+-]+)")
YAML_TEMPLATE = """\
job: extension
config:
name: "orbit_alpha_lora"
process:
- type: 'sd_trainer'
training_folder: "/work/output"
device: cuda:0
network:
type: "lora"
linear: 32
linear_alpha: 32
save:
dtype: float16
save_every: __SAVE_EVERY__
max_step_saves_to_keep: __MAX_SAVES__
push_to_hub: false
datasets:
- folder_path: "/work/train_data/targets"
control_path: "/work/train_data/controls"
caption_ext: "txt"
caption_dropout_rate: 0.0
cache_latents_to_disk: true
resolution: [__RES__]
train:
batch_size: 1
cache_text_embeddings: true
steps: __STEPS__
gradient_accumulation: 1
timestep_type: "weighted"
train_unet: true
train_text_encoder: false
gradient_checkpointing: true
noise_scheduler: "flowmatch"
optimizer: "adamw8bit"
lr: 1e-4
disable_sampling: true
dtype: bf16
model:
name_or_path: "Qwen/Qwen-Image-2.1"
arch: "qwen_image_2"
quantize: false
low_vram: false
model_kwargs:
rgba: true
logging:
log_every: 1
use_ui_logger: true
meta:
name: "[name]"
version: "1.0"
"""
def sh(cmd, **kw):
print(f"\n+ {' '.join(cmd) if isinstance(cmd, list) else cmd}", flush=True)
return subprocess.run(cmd, shell=isinstance(cmd, str), check=True, **kw)
def install_system_libs():
"""cv2 (ai-toolkit dependency) needs libGL.so.1 + glib at import time."""
r1 = subprocess.run(["apt-get", "update"], capture_output=True, text=True)
r2 = subprocess.run(["apt-get", "install", "-y", "libgl1", "libglib2.0-0"],
capture_output=True, text=True)
if r2.returncode == 0:
print("[apt] libgl1 + libglib2.0-0 installed", flush=True)
return
print(f"[apt] failed ({r2.stderr[-300:]}); forcing opencv-python-headless",
flush=True)
sh([sys.executable, "-m", "pip", "install", "--force-reinstall",
"--no-deps", "opencv-python-headless"])
def install_aitk_deps(aitk):
sh([sys.executable, "-m", "pip", "install", "-r",
str(aitk / "requirements.txt")], cwd=str(aitk))
# ai-toolkit's toolkit/config_modules.py does `import torchaudio` at module
# import time, but requirements.txt does not list it. Install it after the
# requirements so pip resolves a build compatible with the torch already
# installed. trackio feeds the loss dashboard from the tail thread.
sh([sys.executable, "-m", "pip", "install", "torchaudio", "trackio"])
v = subprocess.run([sys.executable, "-m", "pip", "show", "trackio"],
capture_output=True, text=True).stdout
print("[deps] " + " | ".join(l.strip() for l in v.splitlines()
if l.startswith(("Name", "Version"))), flush=True)
def materialize():
cmd = [sys.executable, str(DS_ROOT / "materialize_pairs.py"),
"--pairs", str(DS_ROOT / "pairs_train.jsonl"),
"--renders", str(DS_ROOT),
"--out", "/work/train_data", "--alpha-suffix"]
sh(cmd)
for sub in ("targets", "controls"):
n = len(glob.glob(f"/work/train_data/{sub}/*"))
assert n > 0, f"materialized {sub} folder is empty"
print(f"{sub}: {n} files")
def parse_tqdm(text):
"""[(step, total, elapsed_s, loss), ...] from tqdm lines, last wins."""
out = {}
for m in TQDM_RE.finditer(text):
step, total, mm, ss, loss = m.groups()
out[int(step)] = (int(step), int(total), int(mm) * 60 + int(ss),
float(loss))
return out
def tail_loss_to_trackio(space_id, stop_event, state):
"""Tail the trainer's stdout log and push per-step loss to Trackio."""
import trackio
trackio.init(project=PROJECT, space_id=space_id)
logged = set()
while not stop_event.is_set():
try:
text = Path("/work/train_stdout.log").read_text(errors="ignore")
found = parse_tqdm(text)
for step in sorted(found):
if step in logged:
continue
_, _, _, loss = found[step]
trackio.log({"loss": loss}, step=step)
logged.add(step)
state["last_step"] = step
state["last_loss"] = loss
except Exception as e:
print(f"[tail] {type(e).__name__}: {e}", flush=True)
time.sleep(10)
trackio.finish()
def dump_loss_stdout():
"""Dump the parsed tqdm loss curve to JSONL (the reliable source)."""
text = Path("/work/train_stdout.log").read_text(errors="ignore")
found = parse_tqdm(text)
out = Path("/work/loss_log.jsonl")
with open(out, "w") as f:
for step in sorted(found):
_, total, elapsed, loss = found[step]
f.write(json.dumps({"step": step, "loss": loss,
"elapsed_s": elapsed}) + "\n")
print(f"[dump] {len(found)} loss rows -> {out}", flush=True)
return out
def dump_loss_db():
"""Dump the metrics table of loss_log.db to JSONL (best-effort backup)."""
hits = glob.glob("/work/output/**/loss_log.db", recursive=True)
if not hits:
return None
out = Path("/work/loss_db.jsonl")
n = 0
with open(out, "w") as f, sqlite3.connect(f"file:{hits[0]}?mode=ro", uri=True) as conn:
cols = [r[1] for r in conn.execute("PRAGMA table_info(metrics)").fetchall()]
if not cols:
return None
vcol = ("value" if "value" in cols
else "value_text" if "value_text" in cols else cols[-1])
for step, key, val in conn.execute(
f"SELECT step, key, {vcol} FROM metrics ORDER BY step"):
try:
val = float(val)
except (TypeError, ValueError):
continue
f.write(json.dumps({"step": step, "key": key, "value": val}) + "\n")
n += 1
print(f"[dump] {n} sqlite metric rows -> {out}", flush=True)
return out
def upload_artifacts(run_name, extra_files=()):
from huggingface_hub import HfApi
api = HfApi()
dest = f"checkpoints/{run_name}"
for path, rel in extra_files:
if path and Path(path).exists():
api.upload_file(path_or_fileobj=path, path_in_repo=f"{dest}/{rel}",
repo_id=LORA_REPO, repo_type="model")
print(f"[upload] {rel} -> {LORA_REPO}/{dest}/{rel}", flush=True)
ckpts = sorted(glob.glob("/work/output/**/*.safetensors", recursive=True))
assert ckpts, "no .safetensors found under /work/output"
for c in ckpts:
rel = os.path.relpath(c, "/work/output")
api.upload_file(path_or_fileobj=c, path_in_repo=f"{dest}/{rel}",
repo_id=LORA_REPO, repo_type="model")
print(f"[upload] {rel} -> {LORA_REPO}/{dest}/{rel}", flush=True)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--steps", type=int, required=True)
ap.add_argument("--save-every", type=int, default=0)
ap.add_argument("--resolution", type=int, default=768)
ap.add_argument("--max-saves", type=int, default=10)
ap.add_argument("--trackio-space", required=True)
args = ap.parse_args()
save_every = args.save_every or args.steps
run_name = f"steps{args.steps}res{args.resolution}"
state = {"last_step": -1, "last_loss": None}
# 1. ai-toolkit
aitk = WORK / "ai-toolkit"
if not aitk.exists():
subprocess.run(["git", "clone", "--depth", "1", AITK_URL, str(aitk)],
check=True)
install_system_libs()
install_aitk_deps(aitk)
# 2. data
materialize()
# 3. config
yaml_path = WORK / "train_config.yaml"
yaml_path.write_text(YAML_TEMPLATE
.replace("__STEPS__", str(args.steps))
.replace("__SAVE_EVERY__", str(save_every))
.replace("__MAX_SAVES__", str(args.max_saves))
.replace("__RES__", str(args.resolution)))
print(yaml_path.read_text(), flush=True)
# 4+5. train with a loss tail
stop = threading.Event()
t = threading.Thread(target=tail_loss_to_trackio,
args=(args.trackio_space, stop, state), daemon=True)
t.start()
wall0 = time.time()
with open("/work/train_stdout.log", "w") as tee:
proc = subprocess.run([sys.executable, "run.py", str(yaml_path)],
cwd=str(aitk), stdout=tee,
stderr=subprocess.STDOUT)
wall_s = time.time() - wall0
stop.set(); t.join(timeout=30)
# real step timing comes from the tqdm elapsed clock
text = Path("/work/train_stdout.log").read_text(errors="ignore")
found = parse_tqdm(text)
train_s, s_per_step = None, None
if found:
last = found[max(found)]
train_s, s_per_step = float(last[2]), last[2] / last[0]
loss_dump = dump_loss_stdout()
db_dump = dump_loss_db()
if proc.returncode != 0:
tail = open("/work/train_stdout.log").read()[-4000:]
print("TRAIN FAILED\n" + tail, flush=True)
# ship the stdout log even on failure so the loss curve is not lost
try:
upload_artifacts(run_name + "_FAILED",
extra_files=[("/work/train_stdout.log", "train_stdout.log")])
except Exception as e:
print(f"[upload] failure-log upload skipped: {e}", flush=True)
raise SystemExit(proc.returncode)
# 6. ship it
print(f"DONE wall_seconds={wall_s:.1f} train_seconds={train_s} "
f"s_per_step={s_per_step} last_step={state['last_step']} "
f"last_loss={state['last_loss']}", flush=True)
upload_artifacts(run_name, extra_files=[
("/work/train_stdout.log", "train_stdout.log"),
(loss_dump, "loss_log.jsonl"),
(db_dump, "loss_db.jsonl"),
])
print("UPLOADED OK", flush=True)
if __name__ == "__main__":
main()