wajih-rathore commited on
Commit
f717a39
·
verified ·
1 Parent(s): 12720bb

code: per-epoch push

Browse files
code/app.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Transformer Zero: browser app (Gradio, runs on a Hugging Face ZeroGPU Space or any GPU box).
2
+
3
+ Env vars (defaults are the deployed setup):
4
+ TZ_TARGET base model (Qwen/Qwen3-4B-Instruct-2507)
5
+ TZ_ADAPTER LoRA adapter repo (wajih-rathore/transformer-zero), TZ_ADAPTER_DIR subfolder (qwen3-4b-lora); "" = none
6
+ TZ_DRAFT speculative draft (Qwen/Qwen3-0.6B)
7
+ """
8
+ import datetime as dt
9
+ import html
10
+ import os
11
+ import tempfile
12
+ import time
13
+
14
+ import gradio as gr
15
+ import pandas as pd
16
+ import torch
17
+
18
+ try:
19
+ import spaces
20
+ gpu = spaces.GPU
21
+ except ImportError: # not on a ZeroGPU Space: run functions as they are
22
+ def gpu(*a, **k):
23
+ return a[0] if a and callable(a[0]) else (lambda f: f)
24
+
25
+ from tz.data import LABELS, build_messages, load_dataset, note_sentences, parse_output, prompt_text, split_free_text
26
+ from tz.decoder import Qwen3Decoder, greedy_generate
27
+ from tz.explain import explanation_messages, template_explanation
28
+ from tz.speculative import speculative_generate
29
+
30
+ TARGET = os.environ.get("TZ_TARGET", "Qwen/Qwen3-4B-Instruct-2507")
31
+ ADAPTER = os.environ.get("TZ_ADAPTER", "wajih-rathore/transformer-zero")
32
+ ADAPTER_DIR = os.environ.get("TZ_ADAPTER_DIR", "qwen3-4b-lora")
33
+ DRAFT = os.environ.get("TZ_DRAFT", "Qwen/Qwen3-0.6B")
34
+ MAX_CRITERIA, MAX_NOTE_TOKENS = 30, 3000
35
+ NOTICE = "Educational screening prototype only. Not a clinical enrollment decision."
36
+
37
+ from transformers import AutoModelForCausalLM, AutoTokenizer # noqa: E402
38
+
39
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
40
+ dtype = torch.bfloat16 if dev == "cuda" else torch.float32
41
+ tok = AutoTokenizer.from_pretrained(TARGET)
42
+ model = AutoModelForCausalLM.from_pretrained(TARGET, dtype=dtype).to(dev).eval()
43
+ if ADAPTER:
44
+ from peft import PeftModel
45
+ model = PeftModel.from_pretrained(model, ADAPTER, subfolder=ADAPTER_DIR).eval()
46
+ draft_hf = AutoModelForCausalLM.from_pretrained(DRAFT, dtype=dtype).to(dev).eval()
47
+ dec, draft = Qwen3Decoder(model), Qwen3Decoder(draft_hf)
48
+ EOS = {tok.convert_tokens_to_ids("<|im_end|>"), tok.convert_tokens_to_ids("<|endoftext|>")}
49
+ LORA = bool(ADAPTER)
50
+
51
+ # example patients and trials from the validation split (never the test split)
52
+ _df = load_dataset()
53
+ from tz.data import make_split, split_frame # noqa: E402
54
+ _val = split_frame(_df, make_split(_df), "val")
55
+ EXAMPLES = {}
56
+ for (pid, trial), g in _val.groupby(["patient_id", "trial_id"]):
57
+ EXAMPLES[f"{pid} / {trial}: {g.trial_title.iloc[0][:60]}"] = (
58
+ g.note.iloc[0],
59
+ "\n".join(g[g.criterion_type == "inclusion"].criterion_text),
60
+ "\n".join(g[g.criterion_type == "exclusion"].criterion_text))
61
+ if len(EXAMPLES) >= 8:
62
+ break
63
+
64
+
65
+ def _ids(text):
66
+ return tok(text, return_tensors="pt", add_special_tokens=False).input_ids.to(dev)
67
+
68
+
69
+ @torch.no_grad()
70
+ def _hf_batch(prompts, max_new, lora):
71
+ tok.padding_side = "left"
72
+ enc = tok(prompts, return_tensors="pt", padding=True, add_special_tokens=False).to(dev)
73
+ kw = dict(max_new_tokens=max_new, do_sample=False, pad_token_id=tok.pad_token_id, temperature=None, top_p=None, top_k=None)
74
+ if LORA and not lora:
75
+ with model.disable_adapter():
76
+ out = model.generate(**enc, **kw)
77
+ else:
78
+ out = model.generate(**enc, **kw)
79
+ return tok.batch_decode(out[:, enc.input_ids.shape[1]:], skip_special_tokens=True)
80
+
81
+
82
+ def _ours(prompt, max_new, lora, speculative):
83
+ x = _ids(prompt)
84
+ if speculative:
85
+ toks, _ = speculative_generate(dec, draft, x, max_new, k=4, eos_ids=EOS, target_lora=lora and LORA)
86
+ else:
87
+ toks, _ = greedy_generate(dec, x, max_new, eos_ids=EOS, lora=lora and LORA)
88
+ return tok.decode(toks, skip_special_tokens=True)
89
+
90
+
91
+ def verdict(rows):
92
+ """Explicit aggregation rule; the dataset has no patient-level ground truth."""
93
+ labels = [(r["Type"], r["Decision"]) for r in rows]
94
+ if any(l == ("inclusion", "not included") or l == ("exclusion", "excluded") for l in labels):
95
+ return "Likely NOT eligible", "at least one inclusion criterion is not met or one exclusion criterion applies"
96
+ if any(d in ("not enough information", "invalid output") for _, d in labels):
97
+ return "Needs more information", "no criterion rules the patient out, but some cannot be decided from the note"
98
+ return "Likely eligible", "every criterion is met or not applicable based on the note"
99
+
100
+
101
+ @gpu(duration=120)
102
+ def _screen_gpu(sentences, criteria, engine):
103
+ prompts = [prompt_text(tok, build_messages(sentences, t, c)) for t, c in criteria]
104
+ t0 = time.perf_counter()
105
+ if engine.startswith("Fast"):
106
+ raw = _hf_batch(prompts, 64, lora=True)
107
+ else:
108
+ raw = [_ours(p, 64, True, engine.endswith("speculative")) for p in prompts]
109
+ rows, need = [], []
110
+ for (t, c), r in zip(criteria, raw):
111
+ label, ev = parse_output(r, t, len(sentences))
112
+ rows.append({"Type": t, "Criterion": c, "Decision": label or "invalid output", "Evidence IDs": ev,
113
+ "Evidence": " | ".join(f"[{i}] {sentences[i]}" for i in ev)})
114
+ if label and ev:
115
+ need.append(len(rows) - 1)
116
+ exp_prompts = [prompt_text(tok, explanation_messages(rows[i]["Type"], rows[i]["Criterion"], rows[i]["Decision"],
117
+ [(j, sentences[j]) for j in rows[i]["Evidence IDs"]])) for i in need]
118
+ if exp_prompts:
119
+ exps = _hf_batch(exp_prompts, 96, lora=False) if engine.startswith("Fast") else \
120
+ [_ours(p, 96, False, engine.endswith("speculative")) for p in exp_prompts]
121
+ else:
122
+ exps = []
123
+ for i, e in zip(need, exps):
124
+ rows[i]["Explanation"] = e.strip()
125
+ for r in rows:
126
+ r.setdefault("Explanation", template_explanation(r["Decision"]) if r["Decision"] != "invalid output"
127
+ else "The model's answer could not be read.")
128
+ return rows, time.perf_counter() - t0
129
+
130
+
131
+ def screen(note, inc, exc, engine):
132
+ note, inc, exc = (note or "").strip(), (inc or "").strip(), (exc or "").strip()
133
+ if not note:
134
+ raise gr.Error("Paste a patient note first.")
135
+ sentences = split_free_text(note)
136
+ if len(tok(" ".join(sentences)).input_ids) > MAX_NOTE_TOKENS:
137
+ raise gr.Error(f"The note is too long (over {MAX_NOTE_TOKENS} tokens). Shorten it and try again.")
138
+ criteria = [("inclusion", l.strip()) for l in inc.splitlines() if l.strip()] + \
139
+ [("exclusion", l.strip()) for l in exc.splitlines() if l.strip()]
140
+ if not criteria:
141
+ raise gr.Error("Add at least one inclusion or exclusion criterion (one per line).")
142
+ if len(criteria) > MAX_CRITERIA:
143
+ raise gr.Error(f"Too many criteria ({len(criteria)}). The limit is {MAX_CRITERIA} per run.")
144
+ rows, secs = _screen_gpu(sentences, criteria, engine)
145
+ head, why = verdict(rows)
146
+ numbered = "\n".join(f"{i}. {s}" for i, s in enumerate(sentences))
147
+ table = pd.DataFrame([{k: (", ".join(map(str, v)) if k == "Evidence IDs" else v) for k, v in r.items()} for r in rows])
148
+ summary = f"## {head}\nRule: {why}. ({len(rows)} criteria in {secs:.1f} s, engine: {engine})\n\n> {NOTICE}"
149
+ return summary, table, numbered, _report(note, numbered, rows, head, why, engine, secs)
150
+
151
+
152
+ def _report(note, numbered, rows, head, why, engine, secs):
153
+ cells = "".join("<tr>" + "".join(f"<td>{html.escape(str(r[k]))}</td>" for k in
154
+ ("Type", "Criterion", "Decision", "Evidence IDs", "Evidence", "Explanation")) + "</tr>" for r in rows)
155
+ doc = f"""<!doctype html><meta charset="utf-8"><title>Screening report</title>
156
+ <style>body{{font-family:system-ui,sans-serif;max-width:1000px;margin:2rem auto;padding:0 1rem}}td,th{{border:1px solid #ccc;padding:6px;vertical-align:top}}table{{border-collapse:collapse}}.n{{background:#fff3cd;padding:8px}}</style>
157
+ <h1>Trial screening report</h1><p class="n"><b>{NOTICE}</b></p>
158
+ <h2>Overall: {html.escape(head)}</h2><p>Rule: {html.escape(why)}.</p>
159
+ <table><tr><th>Type</th><th>Criterion</th><th>Decision</th><th>Evidence IDs</th><th>Evidence</th><th>Explanation</th></tr>{cells}</table>
160
+ <h3>Patient note (numbered sentences)</h3><pre>{html.escape(numbered)}</pre>
161
+ <h3>Provenance</h3><ul><li>Generated: {dt.datetime.now(dt.timezone.utc).isoformat(timespec='seconds')}</li>
162
+ <li>Model: {TARGET}; LoRA adapter: {ADAPTER or 'none'}/{ADAPTER_DIR if ADAPTER else ''}; draft: {DRAFT}</li>
163
+ <li>Engine: {html.escape(engine)}; greedy decoding; label max 64 tokens, explanation max 96 tokens; {secs:.1f} s</li>
164
+ <li>Explanations: written by the base model (LoRA off) from the cited sentences only.</li></ul>"""
165
+ path = os.path.join(tempfile.mkdtemp(), "screening_report.html")
166
+ open(path, "w", encoding="utf-8").write(doc)
167
+ return path
168
+
169
+
170
+ @gpu(duration=120)
171
+ def lab(prompt, experiment, max_new, k):
172
+ prompt = (prompt or "").strip()
173
+ if not prompt:
174
+ raise gr.Error("Type a prompt first.")
175
+ x = _ids(prompt_text(tok, [{"role": "user", "content": prompt}]))
176
+ max_new, k = int(max_new), int(k)
177
+ runs = []
178
+ if experiment.startswith("KV"):
179
+ for name, cache in (("with KV cache", True), ("no cache (recompute everything)", False)):
180
+ toks, s = greedy_generate(dec, x, max_new, eos_ids=EOS, use_cache=cache, lora=False)
181
+ runs.append((name, toks, s))
182
+ elif experiment.startswith("Attention"):
183
+ names = {"reference": "reference attention", "tiled": "tiled online-softmax", "sdpa": "PyTorch fused SDPA"}
184
+ for name, label in names.items():
185
+ dec.attention = name
186
+ toks, s = greedy_generate(dec, x, max_new, eos_ids=EOS, lora=False)
187
+ runs.append((label, toks, s))
188
+ dec.attention = "reference"
189
+ else:
190
+ toks, s = greedy_generate(dec, x, max_new, eos_ids=EOS, lora=False)
191
+ runs.append(("plain greedy (4B only)", toks, s))
192
+ toks, s = speculative_generate(dec, draft, x, max_new, k=k, eos_ids=EOS)
193
+ runs.append((f"speculative (0.6B drafts {k}, 4B checks)", toks, s))
194
+ base = runs[0][1]
195
+ table = pd.DataFrame([{
196
+ "Method": n, "Same tokens as first row": t == base, "New tokens": s["new_tokens"],
197
+ "Prefill (s)": round(s.get("prefill_s", float("nan")), 3), "Total (s)": round(s["total_s"], 3),
198
+ "Tokens / s": round(s["new_tokens"] / s["total_s"], 1),
199
+ "Acceptance rate": round(s["acceptance_rate"], 2) if "acceptance_rate" in s else None,
200
+ "Peak GPU memory (MB)": round(s["peak_mem_mb"]) if s.get("peak_mem_mb") else None} for n, t, s in runs])
201
+ return table, tok.decode(base, skip_special_tokens=True)
202
+
203
+
204
+ def load_example(name):
205
+ return EXAMPLES[name] if name in EXAMPLES else ("", "", "")
206
+
207
+
208
+ with gr.Blocks(title="Transformer Zero") as demo:
209
+ gr.Markdown(f"# Transformer Zero\nCheck a patient against a clinical trial's criteria, one criterion at a time, "
210
+ f"with the patient sentences that back each decision.\n\n> **{NOTICE}**")
211
+ with gr.Tab("Screen a patient"):
212
+ with gr.Row():
213
+ with gr.Column():
214
+ ex = gr.Dropdown(list(EXAMPLES), label="Load an example (optional)")
215
+ note = gr.Textbox(label="Patient note", lines=8, placeholder="Paste the patient's description here.")
216
+ inc = gr.Textbox(label="Inclusion criteria (one per line)", lines=4)
217
+ exc = gr.Textbox(label="Exclusion criteria (one per line)", lines=4)
218
+ engine = gr.Radio(["Fast (batched)", "Our decoder (KV cache)", "Our decoder + speculative"],
219
+ value="Fast (batched)", label="Engine")
220
+ go = gr.Button("Screen", variant="primary")
221
+ with gr.Column():
222
+ summary = gr.Markdown()
223
+ report = gr.File(label="Download report")
224
+ table = gr.Dataframe(label="Result per criterion", wrap=True)
225
+ with gr.Accordion("Patient note as numbered sentences", open=False):
226
+ numbered = gr.Textbox(show_label=False, lines=8)
227
+ ex.change(load_example, ex, [note, inc, exc])
228
+ go.click(screen, [note, inc, exc, engine], [summary, table, numbered, report])
229
+ with gr.Tab("Inference lab"):
230
+ gr.Markdown("Run the same prompt through different decoding methods and compare speed. "
231
+ "All methods are our own code; matching tokens prove they compute the same answer.")
232
+ prompt = gr.Textbox(label="Prompt", lines=3, value="Explain in three sentences what a clinical trial exclusion criterion is.")
233
+ experiment = gr.Radio(["KV cache vs no cache", "Attention: reference vs tiled vs PyTorch", "Speculative vs plain greedy"],
234
+ value="KV cache vs no cache", label="Experiment")
235
+ with gr.Row():
236
+ max_new = gr.Slider(8, 256, value=64, step=8, label="Tokens to generate")
237
+ k = gr.Slider(1, 8, value=4, step=1, label="Draft tokens per round (speculative)")
238
+ run_btn = gr.Button("Run", variant="primary")
239
+ lab_table = gr.Dataframe(label="Results")
240
+ lab_text = gr.Textbox(label="Generated text", lines=4)
241
+ run_btn.click(lab, [prompt, experiment, max_new, k], [lab_table, lab_text])
242
+
243
+ if __name__ == "__main__":
244
+ demo.launch()
code/notebooks/colab_run.ipynb ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": "# Transformer Zero: Colab run\nSet a GPU runtime and a `HF_TOKEN` secret (Notebook access on), then run top to bottom. Training uploads the best adapter and logs to the HF repo after every epoch."
7
+ },
8
+ {
9
+ "cell_type": "code",
10
+ "metadata": {},
11
+ "execution_count": null,
12
+ "outputs": [],
13
+ "source": "!nvidia-smi --query-gpu=name,memory.total --format=csv\nimport os\nfrom google.colab import userdata\nos.environ['HF_TOKEN'] = userdata.get('HF_TOKEN')"
14
+ },
15
+ {
16
+ "cell_type": "code",
17
+ "metadata": {},
18
+ "execution_count": null,
19
+ "outputs": [],
20
+ "source": "!pip -q install -U transformers peft accelerate scikit-learn 2>&1 | tail -2\n!pip -q uninstall -y torchao # old Colab torchao breaks the new peft import"
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "metadata": {},
25
+ "execution_count": null,
26
+ "outputs": [],
27
+ "source": "import os, subprocess, re, time\nfrom huggingface_hub import snapshot_download, upload_folder\nREPO = 'wajih-rathore/transformer-zero'\nsnapshot_download(REPO, allow_patterns=['code/*'], local_dir='/content/tz')\nos.chdir('/content/tz/code')\ndef push(folder, path_in_repo):\n upload_folder(repo_id=REPO, folder_path=folder, path_in_repo=path_in_repo, commit_message=f'colab: {path_in_repo}')\ndef run(cmd, log=None):\n print('$', cmd, flush=True)\n if log:\n return subprocess.Popen(f'{cmd} > {log} 2>&1', shell=True)\n r = subprocess.run(cmd, shell=True, capture_output=True, text=True)\n print('\n'.join(l for l in (r.stdout + r.stderr).splitlines() if 'arn' not in l and '%|' not in l)[-3000:])\n r.check_returncode()\ndef status(log, proc=None):\n s = open(log).read()\n bars = re.findall(r'(\\d+)/(\\d+) \\[([\\d:]+)<([\\d:?]+)', s)\n print('progress:', bars[-1] if bars else 'starting')\n for l in re.split(r'[\r\n]', s):\n if l.startswith(('VAL', 'DONE', 'Traceback')) or \"'loss'\" in l or 'Error' in l: print(l[:300])\n if proc is not None: print('running' if proc.poll() is None else f'exit code {proc.returncode}')"
28
+ },
29
+ {
30
+ "cell_type": "code",
31
+ "metadata": {},
32
+ "execution_count": null,
33
+ "outputs": [],
34
+ "source": "run('python scripts/benchmark.py --target Qwen/Qwen3-0.6B --draft Qwen/Qwen3-0.6B --parts correctness --repeats 1 --out results/smoke_0.6b.json')"
35
+ },
36
+ {
37
+ "cell_type": "code",
38
+ "metadata": {},
39
+ "execution_count": null,
40
+ "outputs": [],
41
+ "source": "M4 = 'Qwen/Qwen3-4B-Instruct-2507'\nrun(f'python scripts/evaluate.py --model {M4} --name qwen3-4b-base --splits val test')\npush('results', 'results')"
42
+ },
43
+ {
44
+ "cell_type": "code",
45
+ "metadata": {},
46
+ "execution_count": null,
47
+ "outputs": [],
48
+ "source": "train4 = run(f'python scripts/train.py --model {M4} --out runs/qwen3-4b --push {REPO}:runs/qwen3-4b', log='/content/train_4b.log')"
49
+ },
50
+ {
51
+ "cell_type": "code",
52
+ "metadata": {},
53
+ "execution_count": null,
54
+ "outputs": [],
55
+ "source": "status('/content/train_4b.log', train4)"
56
+ },
57
+ {
58
+ "cell_type": "code",
59
+ "metadata": {},
60
+ "execution_count": null,
61
+ "outputs": [],
62
+ "source": "run(f'python scripts/evaluate.py --model {M4} --adapter runs/qwen3-4b/best --name qwen3-4b-lora --splits val test')\npush('results', 'results')"
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "execution_count": null,
68
+ "outputs": [],
69
+ "source": "run(f'python scripts/benchmark.py --target {M4} --draft Qwen/Qwen3-0.6B --adapter runs/qwen3-4b/best --out results/bench_qwen3-4b.json')\npush('results', 'results')"
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "metadata": {},
74
+ "execution_count": null,
75
+ "outputs": [],
76
+ "source": "M17 = 'Qwen/Qwen3-1.7B'\nrun(f'python scripts/evaluate.py --model {M17} --name qwen3-1.7b-base --splits val test')\nrun(f'python scripts/train.py --model {M17} --out runs/qwen3-1.7b --push {REPO}:runs/qwen3-1.7b')\nrun(f'python scripts/evaluate.py --model {M17} --adapter runs/qwen3-1.7b/best --name qwen3-1.7b-lora --splits val test')\npush('results', 'results')"
77
+ }
78
+ ],
79
+ "metadata": {
80
+ "accelerator": "GPU",
81
+ "kernelspec": {
82
+ "name": "python3",
83
+ "display_name": "Python 3"
84
+ }
85
+ },
86
+ "nbformat": 4,
87
+ "nbformat_minor": 5
88
+ }
code/scripts/train.py CHANGED
@@ -30,8 +30,18 @@ ap.add_argument("--accum", type=int, default=4)
30
  ap.add_argument("--max-steps", type=int, default=-1)
31
  ap.add_argument("--parquet", default=None)
32
  ap.add_argument("--smoke", action="store_true")
 
33
  args = ap.parse_args()
34
 
 
 
 
 
 
 
 
 
 
35
  from peft import LoraConfig, get_peft_model # noqa: E402
36
  from transformers import (AutoModelForCausalLM, AutoTokenizer, Qwen3Config, Qwen3ForCausalLM, # noqa: E402
37
  Trainer, TrainerCallback, TrainingArguments)
@@ -89,6 +99,8 @@ class ValidateEachEpoch(TrainerCallback):
89
  model.save_pretrained(out / "best")
90
  (out / "val_metrics.json").write_text(json.dumps(m, indent=2))
91
  pred.drop(columns=["note"]).to_json(out / "val_predictions.jsonl", orient="records", lines=True)
 
 
92
 
93
 
94
  cb = ValidateEachEpoch()
@@ -105,4 +117,5 @@ log = {"args": vars(args), "train_rows": len(train_df), "val_rows": len(val_df),
105
  "best_val_macro_f1": cb.best, "val_history": cb.history, "trainer_log": trainer.state.log_history,
106
  "peak_mem_mb": torch.cuda.max_memory_allocated() / 2**20 if torch.cuda.is_available() else None}
107
  (out / "train_log.json").write_text(json.dumps(log, indent=2))
 
108
  print("DONE", {k: log[k] for k in ("train_s", "best_val_macro_f1", "peak_mem_mb")})
 
30
  ap.add_argument("--max-steps", type=int, default=-1)
31
  ap.add_argument("--parquet", default=None)
32
  ap.add_argument("--smoke", action="store_true")
33
+ ap.add_argument("--push", default=None, help="REPO:FOLDER on the HF Hub; best adapter + logs uploaded after every epoch")
34
  args = ap.parse_args()
35
 
36
+
37
+ def push():
38
+ """Upload progress so a dropped Colab session loses at most one epoch."""
39
+ if args.push:
40
+ from huggingface_hub import upload_folder
41
+ repo, folder = args.push.split(":", 1)
42
+ upload_folder(repo_id=repo, folder_path=str(out), path_in_repo=folder, ignore_patterns=["trainer/*"],
43
+ commit_message=f"train progress: {folder}")
44
+
45
  from peft import LoraConfig, get_peft_model # noqa: E402
46
  from transformers import (AutoModelForCausalLM, AutoTokenizer, Qwen3Config, Qwen3ForCausalLM, # noqa: E402
47
  Trainer, TrainerCallback, TrainingArguments)
 
99
  model.save_pretrained(out / "best")
100
  (out / "val_metrics.json").write_text(json.dumps(m, indent=2))
101
  pred.drop(columns=["note"]).to_json(out / "val_predictions.jsonl", orient="records", lines=True)
102
+ (out / "val_history.json").write_text(json.dumps(self.history, indent=2))
103
+ push()
104
 
105
 
106
  cb = ValidateEachEpoch()
 
117
  "best_val_macro_f1": cb.best, "val_history": cb.history, "trainer_log": trainer.state.log_history,
118
  "peak_mem_mb": torch.cuda.max_memory_allocated() / 2**20 if torch.cuda.is_available() else None}
119
  (out / "train_log.json").write_text(json.dumps(log, indent=2))
120
+ push()
121
  print("DONE", {k: log[k] for k in ("train_s", "best_val_macro_f1", "peak_mem_mb")})