ysharma HF Staff commited on
Commit
a85163a
·
verified ·
1 Parent(s): cc89eca

Loss feed from trainer stdout (sqlite UILogger stays empty); accurate step timing from tqdm elapsed

Browse files
Files changed (1) hide show
  1. run_ai_toolkit.py +70 -51
run_ai_toolkit.py CHANGED
@@ -11,11 +11,15 @@ Runs inside the job container:
11
  with the transparency sentence appended (won the caption A/B)
12
  3. write the training YAML (qwen_image_2 arch, rgba: true, rank 32)
13
  4. launch `python run.py <yaml>`, teeing stdout to /work/train_stdout.log
14
- 5. side thread polls the trainer's SQLite loss_log.db and pushes loss/lr
15
- to Trackio
 
16
  6. on success, upload every saved .safetensors PLUS train_stdout.log and a
17
- dump of the loss SQLite (loss_log.jsonl) to the Hub repo — the job log
18
- API truncates its middle, so the loss curve must live on the Hub.
 
 
 
19
 
20
  Usage:
21
  python run_ai_toolkit.py --steps 50 --resolution 768 \
@@ -27,6 +31,7 @@ import argparse
27
  import glob
28
  import json
29
  import os
 
30
  import sqlite3
31
  import subprocess
32
  import sys
@@ -40,6 +45,8 @@ WORK = Path("/work")
40
  LORA_REPO = "ysharma/orbit-alpha-lora"
41
  PROJECT = "qwen21-rgba-orbit-lora"
42
 
 
 
43
  YAML_TEMPLATE = """\
44
  job: extension
45
  config:
@@ -139,63 +146,63 @@ def materialize():
139
  print(f"{sub}: {n} files")
140
 
141
 
 
 
 
 
 
 
 
 
 
 
142
  def tail_loss_to_trackio(space_id, stop_event, state):
143
- """Poll loss_log.db (schema-agnostic) and push metrics to Trackio."""
144
  import trackio
145
  trackio.init(project=PROJECT, space_id=space_id)
146
- db = None
147
- last_step = -1
148
  while not stop_event.is_set():
149
- if db is None:
150
- hits = glob.glob("/work/output/**/loss_log.db", recursive=True)
151
- if hits:
152
- db = hits[0]
153
- print(f"[tail] polling {db}", flush=True)
154
- if db is not None:
155
- try:
156
- conn = sqlite3.connect(f"file:{db}?mode=ro", uri=True, timeout=10)
157
- try:
158
- cols = [r[1] for r in conn.execute(
159
- "PRAGMA table_info(metrics)").fetchall()]
160
- if cols:
161
- vcol = ("value" if "value" in cols
162
- else "value_text" if "value_text" in cols
163
- else cols[-1])
164
- rows = conn.execute(
165
- f"SELECT step, key, CAST({vcol} AS REAL) FROM metrics "
166
- "WHERE step > ? ORDER BY step", (last_step,)).fetchall()
167
- logs = {}
168
- for step, key, val in rows:
169
- try:
170
- val = float(val)
171
- except (TypeError, ValueError):
172
- continue
173
- logs[key] = val # keep the latest value per key
174
- last_step = max(last_step, step)
175
- if logs:
176
- trackio.log(logs, step=last_step)
177
- state["last_step"] = last_step
178
- state["last_loss"] = logs.get("loss")
179
- finally:
180
- conn.close()
181
- except sqlite3.Error as e:
182
- print(f"[tail] sqlite read skipped: {e}", flush=True)
183
  time.sleep(10)
184
  trackio.finish()
185
 
186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
  def dump_loss_db():
188
- """Dump the metrics table of loss_log.db to JSONL (best-effort)."""
189
  hits = glob.glob("/work/output/**/loss_log.db", recursive=True)
190
  if not hits:
191
- print("[dump] no loss_log.db found", flush=True)
192
  return None
193
- out = Path("/work/loss_log.jsonl")
194
  n = 0
195
  with open(out, "w") as f, sqlite3.connect(f"file:{hits[0]}?mode=ro", uri=True) as conn:
196
  cols = [r[1] for r in conn.execute("PRAGMA table_info(metrics)").fetchall()]
197
  if not cols:
198
- print("[dump] metrics table missing", flush=True)
199
  return None
200
  vcol = ("value" if "value" in cols
201
  else "value_text" if "value_text" in cols else cols[-1])
@@ -207,7 +214,7 @@ def dump_loss_db():
207
  continue
208
  f.write(json.dumps({"step": step, "key": key, "value": val}) + "\n")
209
  n += 1
210
- print(f"[dump] {n} metric rows -> {out}", flush=True)
211
  return out
212
 
213
 
@@ -266,14 +273,24 @@ def main():
266
  t = threading.Thread(target=tail_loss_to_trackio,
267
  args=(args.trackio_space, stop, state), daemon=True)
268
  t.start()
269
- t0 = time.time()
270
  with open("/work/train_stdout.log", "w") as tee:
271
  proc = subprocess.run([sys.executable, "run.py", str(yaml_path)],
272
  cwd=str(aitk), stdout=tee,
273
  stderr=subprocess.STDOUT)
274
- train_s = time.time() - t0
275
  stop.set(); t.join(timeout=30)
276
- loss_dump = dump_loss_db()
 
 
 
 
 
 
 
 
 
 
277
  if proc.returncode != 0:
278
  tail = open("/work/train_stdout.log").read()[-4000:]
279
  print("TRAIN FAILED\n" + tail, flush=True)
@@ -286,11 +303,13 @@ def main():
286
  raise SystemExit(proc.returncode)
287
 
288
  # 6. ship it
289
- print(f"DONE train_seconds={train_s:.1f} s_per_step={train_s / args.steps:.3f} "
290
- f"last_step={state['last_step']} last_loss={state['last_loss']}", flush=True)
 
291
  upload_artifacts(run_name, extra_files=[
292
  ("/work/train_stdout.log", "train_stdout.log"),
293
  (loss_dump, "loss_log.jsonl"),
 
294
  ])
295
  print("UPLOADED OK", flush=True)
296
 
 
11
  with the transparency sentence appended (won the caption A/B)
12
  3. write the training YAML (qwen_image_2 arch, rgba: true, rank 32)
13
  4. launch `python run.py <yaml>`, teeing stdout to /work/train_stdout.log
14
+ 5. side thread parses the tqdm loss lines from that stdout and pushes
15
+ loss -> Trackio. (ai-toolkit's UI logger writes loss_log.db but leaves
16
+ the metrics table empty until process exit, so stdout is the source.)
17
  6. on success, upload every saved .safetensors PLUS train_stdout.log and a
18
+ loss dump (loss_log.jsonl) to the Hub repo — the job log API truncates
19
+ its middle, so the loss curve must live on the Hub.
20
+
21
+ Timing note: wall clock around run.py includes model load + latent caching,
22
+ so the real s/step is taken from the tqdm elapsed clock, not from t0.
23
 
24
  Usage:
25
  python run_ai_toolkit.py --steps 50 --resolution 768 \
 
31
  import glob
32
  import json
33
  import os
34
+ import re
35
  import sqlite3
36
  import subprocess
37
  import sys
 
45
  LORA_REPO = "ysharma/orbit-alpha-lora"
46
  PROJECT = "qwen21-rgba-orbit-lora"
47
 
48
+ TQDM_RE = re.compile(r"(\d+)/(\d+) \[(\d+):(\d+)<[^\]]*?loss: ([0-9.eE+-]+)")
49
+
50
  YAML_TEMPLATE = """\
51
  job: extension
52
  config:
 
146
  print(f"{sub}: {n} files")
147
 
148
 
149
+ def parse_tqdm(text):
150
+ """[(step, total, elapsed_s, loss), ...] from tqdm lines, last wins."""
151
+ out = {}
152
+ for m in TQDM_RE.finditer(text):
153
+ step, total, mm, ss, loss = m.groups()
154
+ out[int(step)] = (int(step), int(total), int(mm) * 60 + int(ss),
155
+ float(loss))
156
+ return out
157
+
158
+
159
  def tail_loss_to_trackio(space_id, stop_event, state):
160
+ """Tail the trainer's stdout log and push per-step loss to Trackio."""
161
  import trackio
162
  trackio.init(project=PROJECT, space_id=space_id)
163
+ logged = set()
 
164
  while not stop_event.is_set():
165
+ try:
166
+ text = Path("/work/train_stdout.log").read_text(errors="ignore")
167
+ found = parse_tqdm(text)
168
+ for step in sorted(found):
169
+ if step in logged:
170
+ continue
171
+ _, _, _, loss = found[step]
172
+ trackio.log({"loss": loss}, step=step)
173
+ logged.add(step)
174
+ state["last_step"] = step
175
+ state["last_loss"] = loss
176
+ except Exception as e:
177
+ print(f"[tail] {type(e).__name__}: {e}", flush=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  time.sleep(10)
179
  trackio.finish()
180
 
181
 
182
+ def dump_loss_stdout():
183
+ """Dump the parsed tqdm loss curve to JSONL (the reliable source)."""
184
+ text = Path("/work/train_stdout.log").read_text(errors="ignore")
185
+ found = parse_tqdm(text)
186
+ out = Path("/work/loss_log.jsonl")
187
+ with open(out, "w") as f:
188
+ for step in sorted(found):
189
+ _, total, elapsed, loss = found[step]
190
+ f.write(json.dumps({"step": step, "loss": loss,
191
+ "elapsed_s": elapsed}) + "\n")
192
+ print(f"[dump] {len(found)} loss rows -> {out}", flush=True)
193
+ return out
194
+
195
+
196
  def dump_loss_db():
197
+ """Dump the metrics table of loss_log.db to JSONL (best-effort backup)."""
198
  hits = glob.glob("/work/output/**/loss_log.db", recursive=True)
199
  if not hits:
 
200
  return None
201
+ out = Path("/work/loss_db.jsonl")
202
  n = 0
203
  with open(out, "w") as f, sqlite3.connect(f"file:{hits[0]}?mode=ro", uri=True) as conn:
204
  cols = [r[1] for r in conn.execute("PRAGMA table_info(metrics)").fetchall()]
205
  if not cols:
 
206
  return None
207
  vcol = ("value" if "value" in cols
208
  else "value_text" if "value_text" in cols else cols[-1])
 
214
  continue
215
  f.write(json.dumps({"step": step, "key": key, "value": val}) + "\n")
216
  n += 1
217
+ print(f"[dump] {n} sqlite metric rows -> {out}", flush=True)
218
  return out
219
 
220
 
 
273
  t = threading.Thread(target=tail_loss_to_trackio,
274
  args=(args.trackio_space, stop, state), daemon=True)
275
  t.start()
276
+ wall0 = time.time()
277
  with open("/work/train_stdout.log", "w") as tee:
278
  proc = subprocess.run([sys.executable, "run.py", str(yaml_path)],
279
  cwd=str(aitk), stdout=tee,
280
  stderr=subprocess.STDOUT)
281
+ wall_s = time.time() - wall0
282
  stop.set(); t.join(timeout=30)
283
+
284
+ # real step timing comes from the tqdm elapsed clock
285
+ text = Path("/work/train_stdout.log").read_text(errors="ignore")
286
+ found = parse_tqdm(text)
287
+ train_s, s_per_step = None, None
288
+ if found:
289
+ last = found[max(found)]
290
+ train_s, s_per_step = float(last[2]), last[2] / last[0]
291
+ loss_dump = dump_loss_stdout()
292
+ db_dump = dump_loss_db()
293
+
294
  if proc.returncode != 0:
295
  tail = open("/work/train_stdout.log").read()[-4000:]
296
  print("TRAIN FAILED\n" + tail, flush=True)
 
303
  raise SystemExit(proc.returncode)
304
 
305
  # 6. ship it
306
+ print(f"DONE wall_seconds={wall_s:.1f} train_seconds={train_s} "
307
+ f"s_per_step={s_per_step} last_step={state['last_step']} "
308
+ f"last_loss={state['last_loss']}", flush=True)
309
  upload_artifacts(run_name, extra_files=[
310
  ("/work/train_stdout.log", "train_stdout.log"),
311
  (loss_dump, "loss_log.jsonl"),
312
+ (db_dump, "loss_db.jsonl"),
313
  ])
314
  print("UPLOADED OK", flush=True)
315