eman-huda commited on
Commit
35f0356
·
verified ·
1 Parent(s): 42108b7

Upload 41 files

Browse files
ABOUT.md ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## About this prototype
2
+
3
+ **Purpose.** Educational research prototype for a Generative AI course assignment. It screens a patient
4
+ record against each inclusion and exclusion criterion of a trial and cites the patient sentences it relied on.
5
+ **It is not a clinical enrollment decision tool.**
6
+
7
+ **Model.** Qwen2.5-1.5B-Instruct (Apache-2.0) fine-tuned with LoRA on the training split of the
8
+ TrialGPT Criterion Annotations dataset (37 patients). Draft model for speculative decoding:
9
+ Qwen2.5-0.5B-Instruct (same tokenizer).
10
+
11
+ **Labels.** Inclusion: included, not included, not enough information, not applicable.
12
+ Exclusion: excluded, not excluded, not enough information, not applicable. Missing information is never
13
+ treated as proof of eligibility or ineligibility.
14
+
15
+ **Explanations.** Built only from the predicted label and the exact cited sentences, so every
16
+ explanation points to text that exists in the record. A decision with no cited sentence is flagged.
17
+
18
+ **Preliminary outcome.** A rule-based aggregation, not a ground-truth label: any exclusion predicted
19
+ "excluded" or inclusion predicted "not included" gives "likely ineligible"; otherwise any
20
+ "not enough information" gives "undetermined"; otherwise "potentially eligible".
21
+
22
+ **Decoding modes.** Explicit KV cache (our own Qwen2 forward pass and cache), Hugging Face forward with a
23
+ DynamicCache driven by our loop, no-cache reference (full recomputation each step), and greedy speculative
24
+ decoding (our implementation). All are greedy, so they should produce identical tokens.
__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """TrialScreen: criterion-level clinical-trial eligibility screening with a fine-tuned
2
+ open-weight decoder, explicit KV-cached decoding, tiled online-softmax attention and
3
+ greedy speculative decoding. Educational research prototype, not a clinical tool."""
4
+ __version__ = "1.0.0"
app.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """TrialScreen browser application (Gradio).
2
+
3
+ Start: python app/app.py then open http://127.0.0.1:7860
4
+ Env vars:
5
+ TS_MODEL target model id (default Qwen/Qwen2.5-1.5B-Instruct)
6
+ TS_ADAPTER LoRA adapter (Hub id or folder; default: local best_adapter if present)
7
+ TS_DRAFT draft model id (default Qwen/Qwen2.5-0.5B-Instruct; 'none' disables)
8
+ TS_DTYPE float32 | bfloat16 | float16 (default: float32 on CPU, fp16/bf16 on GPU)
9
+ TS_SHARE 1 = also create a public gradio.live link
10
+ """
11
+ from __future__ import annotations
12
+ import html, json, os, sys, time, tempfile, traceback
13
+ from pathlib import Path
14
+
15
+ ROOT = Path(__file__).resolve().parents[1]
16
+ sys.path.insert(0, str(ROOT / "src"))
17
+
18
+ import gradio as gr
19
+ import pandas as pd
20
+ import torch
21
+
22
+ from trialscreen.data import split_sentences
23
+ from trialscreen.criteria import parse_criteria
24
+ from trialscreen.modeling import load_model, predict_one, prompt_ids, eos_ids, TARGET_ID, DRAFT_ID
25
+ from trialscreen.decoding import (ExplicitQwen2Decoder, HFCacheDecoder, greedy_cached, greedy_nocache,
26
+ first_mismatch)
27
+ from trialscreen.speculative import speculative_greedy
28
+ from trialscreen.attention import reference_attention, tiled_attention, torch_sdpa
29
+ from trialscreen.explain import aggregate_trial
30
+ from trialscreen.report_export import html_report, provenance, DISCLAIMER
31
+
32
+ MAX_CRITERIA, MAX_NOTE_TOKENS, MAX_CRIT_CHARS = 40, 2500, 1500
33
+ EXAMPLES = json.load(open(ROOT / "app" / "examples.json"))
34
+ MODES = {"KV cache: explicit decoder (ours)": "explicit_cache",
35
+ "KV cache: HF forward + DynamicCache": "hf_cache",
36
+ "No cache: full recompute (reference)": "explicit_nocache",
37
+ "Speculative: 0.5B draft + 1.5B target (ours)": "speculative"}
38
+
39
+ # ------------------------------------------------------------------ model loading
40
+ STATE = {"status": "loading"}
41
+
42
+
43
+ def _load():
44
+ t0 = time.time()
45
+ model_id = os.environ.get("TS_MODEL", TARGET_ID)
46
+ local = ROOT / "checkpoints" / "qwen2.5-1.5b-trialscreen-lora" / "best_adapter"
47
+ adapter = os.environ.get("TS_ADAPTER", str(local) if local.exists() else "")
48
+ adapter = adapter if adapter and adapter.lower() != "none" else None
49
+ dt = {"float32": torch.float32, "bfloat16": torch.bfloat16, "float16": torch.float16}.get(os.environ.get("TS_DTYPE", ""))
50
+ tok, model = load_model(model_id, adapter=adapter, dtype=dt)
51
+ draft_id = os.environ.get("TS_DRAFT", DRAFT_ID)
52
+ draft = None
53
+ if draft_id.lower() != "none":
54
+ try:
55
+ dtok, draft = load_model(draft_id, device=str(model.device), dtype=next(model.parameters()).dtype)
56
+ if dtok.get_vocab() != tok.get_vocab():
57
+ draft, STATE["draft_error"] = None, "draft tokenizer differs from target; speculative disabled"
58
+ except Exception as e:
59
+ STATE["draft_error"] = f"draft not loaded: {e}"
60
+ STATE.update(tok=tok, model=model, draft=draft, model_id=model_id, adapter=adapter, draft_id=draft_id if draft else None,
61
+ device=str(model.device), dtype=str(next(model.parameters()).dtype), status="ready",
62
+ load_s=time.time() - t0)
63
+
64
+
65
+ def status_md():
66
+ if STATE.get("status") != "ready":
67
+ return "Model status: **loading**…"
68
+ s = (f"Model: `{STATE['model_id']}` | adapter: `{STATE['adapter'] or 'none (base model)'}` | draft: "
69
+ f"`{STATE['draft_id'] or 'disabled'}` | device: `{STATE['device']}` ({STATE['dtype']}) | loaded in {STATE['load_s']:.0f}s")
70
+ if STATE.get("draft_error"):
71
+ s += f" \n⚠ {STATE['draft_error']}"
72
+ if not STATE["adapter"]:
73
+ s += " \n⚠ No fine-tuned adapter found: running the BASE model. Set TS_ADAPTER to use the fine-tuned one."
74
+ return s
75
+
76
+
77
+ # ------------------------------------------------------------------ screening
78
+ def _validate(note, criteria_text):
79
+ if not note or len(note.strip()) < 20:
80
+ raise gr.Error("Please paste a patient record (at least one full sentence).")
81
+ if not criteria_text or not criteria_text.strip():
82
+ raise gr.Error("Please enter the trial's eligibility criteria.")
83
+ crits, problems = parse_criteria(criteria_text)
84
+ if problems:
85
+ raise gr.Error("Criteria format problem: " + "; ".join(problems[:3]) +
86
+ ". Use 'Inclusion criteria:' and 'Exclusion criteria:' headings with one criterion per line.")
87
+ if not crits:
88
+ raise gr.Error("No criteria found. Put each criterion on its own line under an 'Inclusion criteria:' or 'Exclusion criteria:' heading.")
89
+ if len(crits) > MAX_CRITERIA:
90
+ raise gr.Error(f"{len(crits)} criteria given; the limit is {MAX_CRITERIA} per run.")
91
+ long = [c for _, c in crits if len(c) > MAX_CRIT_CHARS]
92
+ if long:
93
+ raise gr.Error(f"A criterion is longer than {MAX_CRIT_CHARS} characters; split it into separate lines.")
94
+ sents = split_sentences(note)
95
+ n_tok = len(STATE["tok"](note).input_ids)
96
+ if n_tok > MAX_NOTE_TOKENS:
97
+ raise gr.Error(f"The record has {n_tok} tokens; the limit is {MAX_NOTE_TOKENS}. Shorten it (no silent truncation).")
98
+ return crits, sents
99
+
100
+
101
+ def _highlight(sents, cited):
102
+ out = []
103
+ for i, s in sents:
104
+ if i in cited:
105
+ out.append(f"<li value='{i}' style='background:#fff1b8;border-radius:4px'><b>[{i}]</b> {html.escape(s)}</li>")
106
+ else:
107
+ out.append(f"<li value='{i}'><b>[{i}]</b> {html.escape(s)}</li>")
108
+ return "<ol start='0' style='padding-left:1.4em'>" + "".join(out) + "</ol>"
109
+
110
+
111
+ def screen(note, criteria_text, trial_name, mode_label, attn_backend, k, progress=gr.Progress()):
112
+ if STATE.get("status") != "ready":
113
+ raise gr.Error("The model is still loading. Wait for the status line to say it is ready.")
114
+ crits, sents = _validate(note, criteria_text)
115
+ mode = MODES[mode_label]
116
+ if mode == "speculative" and STATE["draft"] is None:
117
+ raise gr.Error("Speculative mode needs the draft model, which is not loaded. Choose another mode.")
118
+ tok, model, draft = STATE["tok"], STATE["model"], STATE["draft"]
119
+ tgt_dec = ExplicitQwen2Decoder(model, attn_backend) if mode != "hf_cache" else HFCacheDecoder(model)
120
+ dr_dec = ExplicitQwen2Decoder(draft, attn_backend) if mode == "speculative" else None
121
+ results, t0 = [], time.time()
122
+ for j, (ctype, ctext) in enumerate(progress.tqdm(crits, desc="Screening criteria")):
123
+ try:
124
+ r = predict_one(tok, model, note, ctype, ctext, mode=mode, attn_backend=attn_backend,
125
+ draft_model=draft, k=int(k), decoder=tgt_dec, draft_decoder=dr_dec)
126
+ except Exception as e: # one bad criterion must not kill the whole run
127
+ r = {"criterion_type": ctype, "criterion_text": ctext, "label": "invalid output", "evidence": [],
128
+ "evidence_text": [], "explanation": f"Error while running the model: {type(e).__name__}: {e}",
129
+ "raw_output": "", "valid_json": False, "parse_notes": [traceback.format_exc(limit=1)], "decode": {}}
130
+ results.append(r)
131
+ total = time.time() - t0
132
+ verdict = aggregate_trial(results)
133
+ df = pd.DataFrame([{"#": i + 1, "type": r["criterion_type"], "criterion": r["criterion_text"], "prediction": r["label"],
134
+ "evidence IDs": ", ".join(map(str, r["evidence"])) or "-",
135
+ "evidence text": " | ".join(r["evidence_text"]) or "-"} for i, r in enumerate(results)])
136
+ cited = set(i for r in results for i in r["evidence"])
137
+ icon = {"likely ineligible": "🔴", "potentially eligible": "🟢"}.get(verdict["verdict"], "🟡")
138
+ missing = [r["criterion_text"] for r in results if r["label"] == "not enough information"]
139
+ unsupported = [r["criterion_text"] for r in results if r["label"] not in ("not enough information", "invalid output") and not r["evidence"]]
140
+ md = (f"### {icon} Preliminary outcome: **{verdict['verdict']}**\n"
141
+ f"{verdict['n_criteria']} criteria · {verdict['n_blocking']} blocking · {verdict['n_unknown']} undetermined · "
142
+ f"{total:.1f}s with *{mode_label}* \n"
143
+ f"<small>Rule-based aggregation of criterion predictions, not a ground-truth label. Rule: {verdict['rule']}</small>\n\n"
144
+ "**Missing information** (record does not say enough):\n" + ("\n".join(f"- {m}" for m in missing) or "- none") +
145
+ ("\n\n**Decisions without cited evidence** (check these):\n" + "\n".join(f"- {u}" for u in unsupported) if unsupported else ""))
146
+ details = "".join(
147
+ f"<details><summary><b>{i + 1}. [{r['criterion_type']}] {html.escape(r['label'])}</b> — {html.escape(r['criterion_text'][:120])}</summary>"
148
+ f"<p>{html.escape(r['explanation'])}</p><p><small>raw model output: <code>{html.escape(r['raw_output'][:300])}</code>"
149
+ f"{' · notes: ' + html.escape('; '.join(r['parse_notes'])) if r['parse_notes'] else ''}</small></p></details>"
150
+ for i, r in enumerate(results))
151
+ prov = provenance(note, crits, {"model": STATE["model_id"], "adapter": STATE["adapter"], "draft": STATE["draft_id"],
152
+ "decoding": f"greedy, {mode}", "attention_backend": attn_backend,
153
+ "lookahead_k": int(k) if mode == "speculative" else None, "device": STATE["device"],
154
+ "dtype": STATE["dtype"], "runtime_s": round(total, 2)})
155
+ tmp = Path(tempfile.mkdtemp())
156
+ hp = tmp / "screening_report.html"; jp = tmp / "screening_report.json"
157
+ hp.write_text(html_report(trial_name, sents, results, verdict, prov), encoding="utf-8")
158
+ jp.write_text(json.dumps({"trial": trial_name, "verdict": verdict, "results": results, "patient_sentences": sents,
159
+ "provenance": prov, "notice": DISCLAIMER}, indent=1, default=str), encoding="utf-8")
160
+ return md, df, _highlight(sents, cited), details, [str(hp), str(jp)]
161
+
162
+
163
+ def load_example(name):
164
+ ex = next(e for e in EXAMPLES if e["name"] == name)
165
+ return ex["note"], ex["criteria"], ex["trial_id"] or "Example trial"
166
+
167
+
168
+ # ------------------------------------------------------------------ live benchmark
169
+ def bench(note, criteria_text, max_new, k, which, progress=gr.Progress()):
170
+ if STATE.get("status") != "ready":
171
+ raise gr.Error("Model still loading.")
172
+ tok, model, draft = STATE["tok"], STATE["model"], STATE["draft"]
173
+ max_new = int(max_new)
174
+ if which == "Free-text summary of the note (EOS ignored)":
175
+ if not note or len(note.strip()) < 20:
176
+ raise gr.Error("Paste a patient note first (Screening tab or below).")
177
+ msgs = [{"role": "user", "content": "Summarise this patient's history in detail.\n\n" + note}]
178
+ ids = tok(tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True), add_special_tokens=False).input_ids
179
+ eos = ()
180
+ else:
181
+ crits, sents = _validate(note, criteria_text)
182
+ ctype, ctext = crits[0]
183
+ numbered = "\n".join(f"{i}. {s}" for i, s in sents)
184
+ ids = prompt_ids(tok, numbered, ctype, ctext)
185
+ eos = eos_ids(tok)
186
+ ids = torch.tensor([ids], device=model.device)
187
+ rows, ref = [], None
188
+ runs = [("No cache (HF, reference)", lambda: greedy_nocache(HFCacheDecoder(model), ids, max_new, eos)),
189
+ ("No cache (explicit)", lambda: greedy_nocache(ExplicitQwen2Decoder(model, "torch_sdpa"), ids, max_new, eos)),
190
+ ("KV cache (explicit, ours)", lambda: greedy_cached(ExplicitQwen2Decoder(model, "torch_sdpa"), ids, max_new, eos)),
191
+ ("KV cache (explicit + tiled attention)", lambda: greedy_cached(ExplicitQwen2Decoder(model, "tiled"), ids, max_new, eos)),
192
+ ("KV cache (HF DynamicCache)", lambda: greedy_cached(HFCacheDecoder(model), ids, max_new, eos))]
193
+ if draft is not None:
194
+ runs.append((f"Speculative k={int(k)} (ours)", lambda: speculative_greedy(
195
+ ExplicitQwen2Decoder(model, "torch_sdpa"), ExplicitQwen2Decoder(draft, "torch_sdpa"), ids, max_new, k=int(k), eos_ids=eos)))
196
+ for name, fn in progress.tqdm(runs, desc="Running decoders"):
197
+ st = fn()
198
+ toks = st.tokens
199
+ ref = toks if ref is None else ref
200
+ d = st.as_dict()
201
+ rows.append({"method": name, "new tokens": len(toks),
202
+ "prefill ms": round(d.get("prefill_s", 0) * 1000, 1),
203
+ "total ms": round(d["total_s"] * 1000, 1),
204
+ "tokens/s": round(len(toks) / d["total_s"], 1) if d["total_s"] else None,
205
+ "peak GPU MB": round(d["peak_mem_mb"], 0) if d.get("peak_mem_mb") else "n/a (CPU)",
206
+ "same tokens as reference": "yes" if first_mismatch(ref, toks) is None else f"no (first diff at {first_mismatch(ref, toks)})",
207
+ "draft acceptance": round(d["acceptance_rate"], 2) if "acceptance_rate" in d else "-"})
208
+ df = pd.DataFrame(rows)
209
+ base = df.loc[0, "total ms"]
210
+ df["speedup vs no-cache"] = (base / df["total ms"]).round(2)
211
+ text = tok.decode([t for t in ref if t not in eos], skip_special_tokens=True)
212
+ return df, df[["method", "tokens/s"]], f"**Prompt tokens:** {ids.shape[1]} · **Reference output:**\n\n```\n{text[:1500]}\n```"
213
+
214
+
215
+ def attention_check(T, D, block):
216
+ T, D, block = int(T), int(D), int(block)
217
+ dev = STATE.get("device", "cpu")
218
+ torch.manual_seed(0)
219
+ rows = []
220
+ for causal, tq in ((True, T), (True, 1), (False, T)):
221
+ q = torch.randn(1, 4, tq, D, device=dev, dtype=torch.float64)
222
+ k_, v_ = torch.randn(1, 4, T, D, device=dev, dtype=torch.float64), torch.randn(1, 4, T, D, device=dev, dtype=torch.float64)
223
+ truth = reference_attention(q, k_, v_, causal)
224
+ for name, fn in (("reference", reference_attention), ("tiled online-softmax", lambda a, b, c, cz: tiled_attention(a, b, c, cz, block_q=block, block_k=block)),
225
+ ("PyTorch SDPA", torch_sdpa)):
226
+ qq, kk, vv = q.float(), k_.float(), v_.float()
227
+ fn(qq, kk, vv, causal)
228
+ if dev.startswith("cuda"): torch.cuda.synchronize()
229
+ t0 = time.perf_counter(); out = fn(qq, kk, vv, causal)
230
+ if dev.startswith("cuda"): torch.cuda.synchronize()
231
+ ms = (time.perf_counter() - t0) * 1000
232
+ err = (out.double() - truth).abs()
233
+ rows.append({"mask": ("causal" if causal else "none") + (" (decode, 1 query)" if tq == 1 else ""),
234
+ "method": name, "max abs error vs float64": f"{float(err.max()):.2e}",
235
+ "mean abs error": f"{float(err.mean()):.2e}", "time ms (fp32)": round(ms, 2)})
236
+ return pd.DataFrame(rows)
237
+
238
+
239
+ def saved_logs():
240
+ out = []
241
+ for f in sorted((ROOT / "results").glob("*.json")):
242
+ out.append(f"- `{f.name}` ({f.stat().st_size // 1024} KB)")
243
+ return "Benchmark logs from the full GPU runs (also used in the report):\n" + ("\n".join(out) or "- none yet")
244
+
245
+
246
+ # ------------------------------------------------------------------ UI
247
+ CSS = """.notice{background:#fff4e5;border:2px solid #8a5a00;border-radius:12px;padding:10px 14px;font-weight:600}"""
248
+
249
+ with gr.Blocks(title="TrialScreen: clinical trial eligibility screening (educational)") as demo:
250
+ gr.Markdown("# TrialScreen\nCriterion-level clinical trial eligibility screening with evidence citations.")
251
+ gr.HTML(f"<div class='notice'>⚠ {DISCLAIMER}</div>")
252
+ status = gr.Markdown(status_md())
253
+ with gr.Tab("Screen a patient"):
254
+ with gr.Row():
255
+ with gr.Column(scale=1):
256
+ ex = gr.Dropdown([e["name"] for e in EXAMPLES], label="Load an example (validation split or hand-written)", value=None)
257
+ trial = gr.Textbox(label="Trial name or ID", placeholder="e.g. NCT01234567")
258
+ note = gr.Textbox(label="Patient record", lines=10,
259
+ placeholder="Paste a clinical note. Numbered sentences ('0. ...') are kept; otherwise sentences are split and numbered automatically.")
260
+ crit = gr.Textbox(label="Eligibility criteria", lines=10,
261
+ placeholder="Inclusion criteria:\n- ...\nExclusion criteria:\n- ...")
262
+ with gr.Row():
263
+ mode = gr.Dropdown(list(MODES), value=list(MODES)[0], label="Decoding mode")
264
+ attn = gr.Dropdown(["reference", "tiled", "torch_sdpa"], value="torch_sdpa", label="Attention backend (explicit decoder)")
265
+ kk = gr.Slider(1, 8, value=4, step=1, label="Draft lookahead k (speculative)")
266
+ run = gr.Button("Screen patient", variant="primary")
267
+ with gr.Column(scale=1):
268
+ verdict = gr.Markdown()
269
+ table = gr.Dataframe(label="Criterion-level results", wrap=True, interactive=False)
270
+ files = gr.File(label="Download report (HTML + JSON with provenance)", file_count="multiple")
271
+ with gr.Row():
272
+ with gr.Column():
273
+ gr.Markdown("**Patient record with cited sentences highlighted**")
274
+ note_html = gr.HTML()
275
+ with gr.Column():
276
+ gr.Markdown("**Explanations per criterion** (built only from the cited sentences)")
277
+ det = gr.HTML()
278
+ ex.change(load_example, ex, [note, crit, trial])
279
+ run.click(screen, [note, crit, trial, mode, attn, kk], [verdict, table, note_html, det, files])
280
+ with gr.Tab("Inference benchmark"):
281
+ gr.Markdown("Runs every decoding path **live** on the same prompt (from the Screening tab inputs) with greedy decoding, "
282
+ "checks that tokens match the uncached reference, and times them. Single runs: use the repeated, "
283
+ "warmed-up GPU benchmark scripts for report numbers.")
284
+ with gr.Row():
285
+ which = gr.Radio(["Screening prompt (first criterion)", "Free-text summary of the note (EOS ignored)"],
286
+ value="Free-text summary of the note (EOS ignored)", label="Workload")
287
+ mx = gr.Slider(8, 256, value=64, step=8, label="Max new tokens")
288
+ kb = gr.Slider(1, 8, value=4, step=1, label="Speculative lookahead k")
289
+ bbtn = gr.Button("Run comparison", variant="primary")
290
+ btab = gr.Dataframe(label="Decoding comparison", interactive=False, wrap=True)
291
+ bplot = gr.BarPlot(x="method", y="tokens/s", label="Throughput (tokens/s)")
292
+ bout = gr.Markdown()
293
+ bbtn.click(bench, [note, crit, mx, kb, which], [btab, bplot, bout])
294
+ gr.Markdown("### Attention check: reference vs tiled online-softmax vs PyTorch SDPA")
295
+ with gr.Row():
296
+ aT = gr.Slider(16, 2048, value=256, step=16, label="Sequence length T")
297
+ aD = gr.Dropdown([32, 64, 128], value=64, label="Head dim")
298
+ aB = gr.Dropdown([16, 32, 64, 128], value=64, label="Tile size")
299
+ abtn = gr.Button("Run attention check")
300
+ atab = gr.Dataframe(interactive=False)
301
+ abtn.click(attention_check, [aT, aD, aB], atab)
302
+ logs = gr.Markdown()
303
+ with gr.Tab("About"):
304
+ gr.Markdown(open(ROOT / "app" / "ABOUT.md").read())
305
+ demo.load(lambda: (status_md(), saved_logs()), None, [status, logs])
306
+
307
+ if __name__ == "__main__":
308
+ _load()
309
+ demo.queue(default_concurrency_limit=1).launch(server_name=os.environ.get("TS_HOST", "0.0.0.0"),
310
+ server_port=int(os.environ.get("TS_PORT", 7860)),
311
+ share=os.environ.get("TS_SHARE") == "1", css=CSS)
attention.json ADDED
@@ -0,0 +1,918 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "env": {
3
+ "python": "3.13.16",
4
+ "torch": "2.11.0+cu130",
5
+ "transformers": "5.22.2",
6
+ "cuda": true,
7
+ "gpu": "Tesla T4",
8
+ "gpu_mem_gb": 14.6
9
+ },
10
+ "device": "cuda",
11
+ "correctness": [
12
+ {
13
+ "shape": [
14
+ 1,
15
+ 1,
16
+ 4,
17
+ 4,
18
+ 8
19
+ ],
20
+ "blocks": [
21
+ 2,
22
+ 2
23
+ ],
24
+ "causal": true,
25
+ "dtype": "torch.float32",
26
+ "reference": {
27
+ "max_abs_err": 1.2165821128284904e-07,
28
+ "mean_abs_err": 3.186485156861591e-08
29
+ },
30
+ "tiled": {
31
+ "max_abs_err": 1.535511233718978e-07,
32
+ "mean_abs_err": 4.053411784742328e-08
33
+ },
34
+ "torch_sdpa": {
35
+ "max_abs_err": 1.9526879446729595e-07,
36
+ "mean_abs_err": 4.826622901316991e-08
37
+ },
38
+ "tiled_vs_reference_max": 1.1920928955078125e-07,
39
+ "pass": true
40
+ },
41
+ {
42
+ "shape": [
43
+ 1,
44
+ 1,
45
+ 4,
46
+ 4,
47
+ 8
48
+ ],
49
+ "blocks": [
50
+ 2,
51
+ 2
52
+ ],
53
+ "causal": false,
54
+ "dtype": "torch.float32",
55
+ "reference": {
56
+ "max_abs_err": 1.4676216775200146e-07,
57
+ "mean_abs_err": 4.446105541025536e-08
58
+ },
59
+ "tiled": {
60
+ "max_abs_err": 1.4290520577997512e-07,
61
+ "mean_abs_err": 3.9336727529828974e-08
62
+ },
63
+ "torch_sdpa": {
64
+ "max_abs_err": 2.659714573027827e-07,
65
+ "mean_abs_err": 5.878995587571545e-08
66
+ },
67
+ "tiled_vs_reference_max": 1.1920928955078125e-07,
68
+ "pass": true
69
+ },
70
+ {
71
+ "shape": [
72
+ 2,
73
+ 3,
74
+ 17,
75
+ 17,
76
+ 16
77
+ ],
78
+ "blocks": [
79
+ 4,
80
+ 5
81
+ ],
82
+ "causal": true,
83
+ "dtype": "torch.float32",
84
+ "reference": {
85
+ "max_abs_err": 3.250013589362055e-07,
86
+ "mean_abs_err": 3.8495372388551974e-08
87
+ },
88
+ "tiled": {
89
+ "max_abs_err": 3.630552998235004e-07,
90
+ "mean_abs_err": 3.586581535891332e-08
91
+ },
92
+ "torch_sdpa": {
93
+ "max_abs_err": 3.220921360735929e-07,
94
+ "mean_abs_err": 3.9719591272306176e-08
95
+ },
96
+ "tiled_vs_reference_max": 2.384185791015625e-07,
97
+ "pass": true
98
+ },
99
+ {
100
+ "shape": [
101
+ 2,
102
+ 3,
103
+ 17,
104
+ 17,
105
+ 16
106
+ ],
107
+ "blocks": [
108
+ 4,
109
+ 5
110
+ ],
111
+ "causal": false,
112
+ "dtype": "torch.float32",
113
+ "reference": {
114
+ "max_abs_err": 2.506387459799697e-07,
115
+ "mean_abs_err": 3.342653533269883e-08
116
+ },
117
+ "tiled": {
118
+ "max_abs_err": 2.5130779413018445e-07,
119
+ "mean_abs_err": 3.443028837933688e-08
120
+ },
121
+ "torch_sdpa": {
122
+ "max_abs_err": 2.506387459799697e-07,
123
+ "mean_abs_err": 3.4027856315445134e-08
124
+ },
125
+ "tiled_vs_reference_max": 3.5762786865234375e-07,
126
+ "pass": true
127
+ },
128
+ {
129
+ "shape": [
130
+ 1,
131
+ 12,
132
+ 128,
133
+ 128,
134
+ 128
135
+ ],
136
+ "blocks": [
137
+ 64,
138
+ 64
139
+ ],
140
+ "causal": true,
141
+ "dtype": "torch.float32",
142
+ "reference": {
143
+ "max_abs_err": 9.134579943559373e-07,
144
+ "mean_abs_err": 5.151986175594611e-08
145
+ },
146
+ "tiled": {
147
+ "max_abs_err": 9.48897892261158e-07,
148
+ "mean_abs_err": 5.118832500385696e-08
149
+ },
150
+ "torch_sdpa": {
151
+ "max_abs_err": 9.237391391803129e-07,
152
+ "mean_abs_err": 5.21306919115453e-08
153
+ },
154
+ "tiled_vs_reference_max": 1.5795230865478516e-06,
155
+ "pass": true
156
+ },
157
+ {
158
+ "shape": [
159
+ 1,
160
+ 12,
161
+ 128,
162
+ 128,
163
+ 128
164
+ ],
165
+ "blocks": [
166
+ 64,
167
+ 64
168
+ ],
169
+ "causal": false,
170
+ "dtype": "torch.float32",
171
+ "reference": {
172
+ "max_abs_err": 8.398586399671615e-07,
173
+ "mean_abs_err": 4.272009047347097e-08
174
+ },
175
+ "tiled": {
176
+ "max_abs_err": 1.1421988636017844e-06,
177
+ "mean_abs_err": 4.059296447010988e-08
178
+ },
179
+ "torch_sdpa": {
180
+ "max_abs_err": 8.994632847425521e-07,
181
+ "mean_abs_err": 4.303170403188735e-08
182
+ },
183
+ "tiled_vs_reference_max": 9.5367431640625e-07,
184
+ "pass": true
185
+ },
186
+ {
187
+ "shape": [
188
+ 1,
189
+ 12,
190
+ 1,
191
+ 300,
192
+ 128
193
+ ],
194
+ "blocks": [
195
+ 64,
196
+ 64
197
+ ],
198
+ "causal": true,
199
+ "dtype": "torch.float32",
200
+ "reference": {
201
+ "max_abs_err": 1.0677353312615878e-07,
202
+ "mean_abs_err": 1.580579209283271e-08
203
+ },
204
+ "tiled": {
205
+ "max_abs_err": 8.361967723802266e-08,
206
+ "mean_abs_err": 1.3465699308539293e-08
207
+ },
208
+ "torch_sdpa": {
209
+ "max_abs_err": 2.373316811965509e-07,
210
+ "mean_abs_err": 3.375765208510979e-08
211
+ },
212
+ "tiled_vs_reference_max": 1.2665987014770508e-07,
213
+ "pass": true
214
+ },
215
+ {
216
+ "shape": [
217
+ 1,
218
+ 12,
219
+ 1,
220
+ 300,
221
+ 128
222
+ ],
223
+ "blocks": [
224
+ 64,
225
+ 64
226
+ ],
227
+ "causal": false,
228
+ "dtype": "torch.float32",
229
+ "reference": {
230
+ "max_abs_err": 8.513062934450977e-08,
231
+ "mean_abs_err": 1.5403886764766682e-08
232
+ },
233
+ "tiled": {
234
+ "max_abs_err": 8.015984043208135e-08,
235
+ "mean_abs_err": 1.2442668746155655e-08
236
+ },
237
+ "torch_sdpa": {
238
+ "max_abs_err": 2.0830731983778605e-07,
239
+ "mean_abs_err": 2.8928634796252815e-08
240
+ },
241
+ "tiled_vs_reference_max": 8.940696716308594e-08,
242
+ "pass": true
243
+ },
244
+ {
245
+ "shape": [
246
+ 1,
247
+ 12,
248
+ 7,
249
+ 300,
250
+ 128
251
+ ],
252
+ "blocks": [
253
+ 4,
254
+ 64
255
+ ],
256
+ "causal": true,
257
+ "dtype": "torch.float32",
258
+ "reference": {
259
+ "max_abs_err": 1.815328667387206e-07,
260
+ "mean_abs_err": 1.6483526757514907e-08
261
+ },
262
+ "tiled": {
263
+ "max_abs_err": 1.0970480388006187e-07,
264
+ "mean_abs_err": 1.4467037822227354e-08
265
+ },
266
+ "torch_sdpa": {
267
+ "max_abs_err": 3.9551051192465714e-07,
268
+ "mean_abs_err": 3.551441656787015e-08
269
+ },
270
+ "tiled_vs_reference_max": 2.384185791015625e-07,
271
+ "pass": true
272
+ },
273
+ {
274
+ "shape": [
275
+ 1,
276
+ 12,
277
+ 7,
278
+ 300,
279
+ 128
280
+ ],
281
+ "blocks": [
282
+ 4,
283
+ 64
284
+ ],
285
+ "causal": false,
286
+ "dtype": "torch.float32",
287
+ "reference": {
288
+ "max_abs_err": 1.8329098133706978e-07,
289
+ "mean_abs_err": 1.7603450686842315e-08
290
+ },
291
+ "tiled": {
292
+ "max_abs_err": 1.3288373654218866e-07,
293
+ "mean_abs_err": 1.4895347749159169e-08
294
+ },
295
+ "torch_sdpa": {
296
+ "max_abs_err": 3.9190723805093697e-07,
297
+ "mean_abs_err": 3.666496061783309e-08
298
+ },
299
+ "tiled_vs_reference_max": 2.5331974029541016e-07,
300
+ "pass": true
301
+ },
302
+ {
303
+ "shape": [
304
+ 2,
305
+ 4,
306
+ 257,
307
+ 257,
308
+ 64
309
+ ],
310
+ "blocks": [
311
+ 32,
312
+ 48
313
+ ],
314
+ "causal": true,
315
+ "dtype": "torch.float32",
316
+ "reference": {
317
+ "max_abs_err": 8.352325474580979e-07,
318
+ "mean_abs_err": 3.621618277865199e-08
319
+ },
320
+ "tiled": {
321
+ "max_abs_err": 7.233554640551088e-07,
322
+ "mean_abs_err": 3.263671770022755e-08
323
+ },
324
+ "torch_sdpa": {
325
+ "max_abs_err": 8.352325474580979e-07,
326
+ "mean_abs_err": 3.70255893541136e-08
327
+ },
328
+ "tiled_vs_reference_max": 3.5762786865234375e-07,
329
+ "pass": true
330
+ },
331
+ {
332
+ "shape": [
333
+ 2,
334
+ 4,
335
+ 257,
336
+ 257,
337
+ 64
338
+ ],
339
+ "blocks": [
340
+ 32,
341
+ 48
342
+ ],
343
+ "causal": false,
344
+ "dtype": "torch.float32",
345
+ "reference": {
346
+ "max_abs_err": 4.244530561470228e-07,
347
+ "mean_abs_err": 2.9420606681520654e-08
348
+ },
349
+ "tiled": {
350
+ "max_abs_err": 4.2558191692965153e-07,
351
+ "mean_abs_err": 2.2820367009880553e-08
352
+ },
353
+ "torch_sdpa": {
354
+ "max_abs_err": 4.430135455146811e-07,
355
+ "mean_abs_err": 2.988332092569473e-08
356
+ },
357
+ "tiled_vs_reference_max": 3.5762786865234375e-07,
358
+ "pass": true
359
+ },
360
+ {
361
+ "shape": [
362
+ 1,
363
+ 2,
364
+ 1000,
365
+ 1000,
366
+ 64
367
+ ],
368
+ "blocks": [
369
+ 128,
370
+ 128
371
+ ],
372
+ "causal": true,
373
+ "dtype": "torch.float32",
374
+ "reference": {
375
+ "max_abs_err": 5.316010995293219e-07,
376
+ "mean_abs_err": 2.841046518553278e-08
377
+ },
378
+ "tiled": {
379
+ "max_abs_err": 5.761553827920984e-07,
380
+ "mean_abs_err": 2.24833348537403e-08
381
+ },
382
+ "torch_sdpa": {
383
+ "max_abs_err": 5.614034219170172e-07,
384
+ "mean_abs_err": 2.88726851347731e-08
385
+ },
386
+ "tiled_vs_reference_max": 2.980232238769531e-07,
387
+ "pass": true
388
+ },
389
+ {
390
+ "shape": [
391
+ 1,
392
+ 2,
393
+ 1000,
394
+ 1000,
395
+ 64
396
+ ],
397
+ "blocks": [
398
+ 128,
399
+ 128
400
+ ],
401
+ "causal": false,
402
+ "dtype": "torch.float32",
403
+ "reference": {
404
+ "max_abs_err": 4.968404653804548e-07,
405
+ "mean_abs_err": 2.407248995955059e-08
406
+ },
407
+ "tiled": {
408
+ "max_abs_err": 1.942772499680112e-07,
409
+ "mean_abs_err": 1.4490051613037112e-08
410
+ },
411
+ "torch_sdpa": {
412
+ "max_abs_err": 3.478288534419782e-07,
413
+ "mean_abs_err": 2.4493023053609447e-08
414
+ },
415
+ "tiled_vs_reference_max": 4.470348358154297e-07,
416
+ "pass": true
417
+ },
418
+ {
419
+ "shape": [
420
+ 1,
421
+ 1,
422
+ 4,
423
+ 4,
424
+ 8
425
+ ],
426
+ "blocks": [
427
+ 2,
428
+ 2
429
+ ],
430
+ "causal": true,
431
+ "dtype": "torch.float16",
432
+ "reference": {
433
+ "max_abs_err": 0.00041082549035276195,
434
+ "mean_abs_err": 0.00011522373772760558
435
+ },
436
+ "tiled": {
437
+ "max_abs_err": 0.00041082549035276195,
438
+ "mean_abs_err": 0.00011522373772760558
439
+ },
440
+ "torch_sdpa": {
441
+ "max_abs_err": 0.00041082549035276195,
442
+ "mean_abs_err": 0.0001314058138589013
443
+ },
444
+ "tiled_vs_reference_max": 0.0,
445
+ "pass": true
446
+ },
447
+ {
448
+ "shape": [
449
+ 1,
450
+ 1,
451
+ 4,
452
+ 4,
453
+ 8
454
+ ],
455
+ "blocks": [
456
+ 2,
457
+ 2
458
+ ],
459
+ "causal": false,
460
+ "dtype": "torch.float16",
461
+ "reference": {
462
+ "max_abs_err": 0.00039270223568552143,
463
+ "mean_abs_err": 0.0001230078586703983
464
+ },
465
+ "tiled": {
466
+ "max_abs_err": 0.00039270223568552143,
467
+ "mean_abs_err": 0.0001230078586703983
468
+ },
469
+ "torch_sdpa": {
470
+ "max_abs_err": 0.00028349912651898235,
471
+ "mean_abs_err": 0.00011509288664329591
472
+ },
473
+ "tiled_vs_reference_max": 0.0,
474
+ "pass": true
475
+ },
476
+ {
477
+ "shape": [
478
+ 2,
479
+ 3,
480
+ 17,
481
+ 17,
482
+ 16
483
+ ],
484
+ "blocks": [
485
+ 4,
486
+ 5
487
+ ],
488
+ "causal": true,
489
+ "dtype": "torch.float16",
490
+ "reference": {
491
+ "max_abs_err": 0.0010813577334936042,
492
+ "mean_abs_err": 0.00013531023335823145
493
+ },
494
+ "tiled": {
495
+ "max_abs_err": 0.0010813577334936042,
496
+ "mean_abs_err": 0.00013531023335823145
497
+ },
498
+ "torch_sdpa": {
499
+ "max_abs_err": 0.0010813577334936042,
500
+ "mean_abs_err": 0.00014436679506739665
501
+ },
502
+ "tiled_vs_reference_max": 0.0,
503
+ "pass": true
504
+ },
505
+ {
506
+ "shape": [
507
+ 2,
508
+ 3,
509
+ 17,
510
+ 17,
511
+ 16
512
+ ],
513
+ "blocks": [
514
+ 4,
515
+ 5
516
+ ],
517
+ "causal": false,
518
+ "dtype": "torch.float16",
519
+ "reference": {
520
+ "max_abs_err": 0.0011592399316417978,
521
+ "mean_abs_err": 0.00010277492068932831
522
+ },
523
+ "tiled": {
524
+ "max_abs_err": 0.0011592399316417978,
525
+ "mean_abs_err": 0.0001027748841668744
526
+ },
527
+ "torch_sdpa": {
528
+ "max_abs_err": 0.000983106890749319,
529
+ "mean_abs_err": 0.00010992652258956821
530
+ },
531
+ "tiled_vs_reference_max": 5.960464477539063e-08,
532
+ "pass": true
533
+ },
534
+ {
535
+ "shape": [
536
+ 1,
537
+ 12,
538
+ 128,
539
+ 128,
540
+ 128
541
+ ],
542
+ "blocks": [
543
+ 64,
544
+ 64
545
+ ],
546
+ "causal": true,
547
+ "dtype": "torch.float16",
548
+ "reference": {
549
+ "max_abs_err": 0.0014336114037405423,
550
+ "mean_abs_err": 7.123436797291e-05
551
+ },
552
+ "tiled": {
553
+ "max_abs_err": 0.0014336114037405423,
554
+ "mean_abs_err": 7.12455302263752e-05
555
+ },
556
+ "torch_sdpa": {
557
+ "max_abs_err": 0.0014336114037405423,
558
+ "mean_abs_err": 7.660770572952646e-05
559
+ },
560
+ "tiled_vs_reference_max": 0.00048828125,
561
+ "pass": true
562
+ },
563
+ {
564
+ "shape": [
565
+ 1,
566
+ 12,
567
+ 128,
568
+ 128,
569
+ 128
570
+ ],
571
+ "blocks": [
572
+ 64,
573
+ 64
574
+ ],
575
+ "causal": false,
576
+ "dtype": "torch.float16",
577
+ "reference": {
578
+ "max_abs_err": 0.0010286018276117748,
579
+ "mean_abs_err": 4.525026227655339e-05
580
+ },
581
+ "tiled": {
582
+ "max_abs_err": 0.0010286018276117748,
583
+ "mean_abs_err": 4.5247849624714335e-05
584
+ },
585
+ "torch_sdpa": {
586
+ "max_abs_err": 0.0010286018276117748,
587
+ "mean_abs_err": 4.936740715973471e-05
588
+ },
589
+ "tiled_vs_reference_max": 0.00048828125,
590
+ "pass": true
591
+ },
592
+ {
593
+ "shape": [
594
+ 1,
595
+ 12,
596
+ 1,
597
+ 300,
598
+ 128
599
+ ],
600
+ "blocks": [
601
+ 64,
602
+ 64
603
+ ],
604
+ "causal": true,
605
+ "dtype": "torch.float16",
606
+ "reference": {
607
+ "max_abs_err": 0.0001332501823732568,
608
+ "mean_abs_err": 2.9859313516406067e-05
609
+ },
610
+ "tiled": {
611
+ "max_abs_err": 0.0001332501823732568,
612
+ "mean_abs_err": 2.9864940256961036e-05
613
+ },
614
+ "torch_sdpa": {
615
+ "max_abs_err": 0.00014967749078964587,
616
+ "mean_abs_err": 3.266586597674291e-05
617
+ },
618
+ "tiled_vs_reference_max": 7.62939453125e-06,
619
+ "pass": true
620
+ },
621
+ {
622
+ "shape": [
623
+ 1,
624
+ 12,
625
+ 1,
626
+ 300,
627
+ 128
628
+ ],
629
+ "blocks": [
630
+ 64,
631
+ 64
632
+ ],
633
+ "causal": false,
634
+ "dtype": "torch.float16",
635
+ "reference": {
636
+ "max_abs_err": 0.0002011817402571281,
637
+ "mean_abs_err": 3.157318325526313e-05
638
+ },
639
+ "tiled": {
640
+ "max_abs_err": 0.0002011817402571281,
641
+ "mean_abs_err": 3.157380413697954e-05
642
+ },
643
+ "torch_sdpa": {
644
+ "max_abs_err": 0.00018826356237036657,
645
+ "mean_abs_err": 3.3040575141058594e-05
646
+ },
647
+ "tiled_vs_reference_max": 9.5367431640625e-07,
648
+ "pass": true
649
+ },
650
+ {
651
+ "shape": [
652
+ 1,
653
+ 12,
654
+ 7,
655
+ 300,
656
+ 128
657
+ ],
658
+ "blocks": [
659
+ 4,
660
+ 64
661
+ ],
662
+ "causal": true,
663
+ "dtype": "torch.float16",
664
+ "reference": {
665
+ "max_abs_err": 0.0002100282332802017,
666
+ "mean_abs_err": 3.06457682265634e-05
667
+ },
668
+ "tiled": {
669
+ "max_abs_err": 0.0002100282332802017,
670
+ "mean_abs_err": 3.0642497591038674e-05
671
+ },
672
+ "torch_sdpa": {
673
+ "max_abs_err": 0.0002100282332802017,
674
+ "mean_abs_err": 3.3753986196143324e-05
675
+ },
676
+ "tiled_vs_reference_max": 6.103515625e-05,
677
+ "pass": true
678
+ },
679
+ {
680
+ "shape": [
681
+ 1,
682
+ 12,
683
+ 7,
684
+ 300,
685
+ 128
686
+ ],
687
+ "blocks": [
688
+ 4,
689
+ 64
690
+ ],
691
+ "causal": false,
692
+ "dtype": "torch.float16",
693
+ "reference": {
694
+ "max_abs_err": 0.00017242896137376063,
695
+ "mean_abs_err": 3.0456679585009504e-05
696
+ },
697
+ "tiled": {
698
+ "max_abs_err": 0.00017242896137376063,
699
+ "mean_abs_err": 3.0457622671317824e-05
700
+ },
701
+ "torch_sdpa": {
702
+ "max_abs_err": 0.00019116548135492129,
703
+ "mean_abs_err": 3.34736713419009e-05
704
+ },
705
+ "tiled_vs_reference_max": 6.103515625e-05,
706
+ "pass": true
707
+ },
708
+ {
709
+ "shape": [
710
+ 2,
711
+ 4,
712
+ 257,
713
+ 257,
714
+ 64
715
+ ],
716
+ "blocks": [
717
+ 32,
718
+ 48
719
+ ],
720
+ "causal": true,
721
+ "dtype": "torch.float16",
722
+ "reference": {
723
+ "max_abs_err": 0.0013334514594811608,
724
+ "mean_abs_err": 5.465336486569789e-05
725
+ },
726
+ "tiled": {
727
+ "max_abs_err": 0.0013334514594811608,
728
+ "mean_abs_err": 5.465248041798394e-05
729
+ },
730
+ "torch_sdpa": {
731
+ "max_abs_err": 0.0013334514594811608,
732
+ "mean_abs_err": 5.903260036084788e-05
733
+ },
734
+ "tiled_vs_reference_max": 0.000244140625,
735
+ "pass": true
736
+ },
737
+ {
738
+ "shape": [
739
+ 2,
740
+ 4,
741
+ 257,
742
+ 257,
743
+ 64
744
+ ],
745
+ "blocks": [
746
+ 32,
747
+ 48
748
+ ],
749
+ "causal": false,
750
+ "dtype": "torch.float16",
751
+ "reference": {
752
+ "max_abs_err": 0.0004366164173644216,
753
+ "mean_abs_err": 3.3366513268134875e-05
754
+ },
755
+ "tiled": {
756
+ "max_abs_err": 0.0004366164173644216,
757
+ "mean_abs_err": 3.336604332762016e-05
758
+ },
759
+ "torch_sdpa": {
760
+ "max_abs_err": 0.0003887572906857151,
761
+ "mean_abs_err": 3.6301371106619424e-05
762
+ },
763
+ "tiled_vs_reference_max": 0.0001220703125,
764
+ "pass": true
765
+ },
766
+ {
767
+ "shape": [
768
+ 1,
769
+ 2,
770
+ 1000,
771
+ 1000,
772
+ 64
773
+ ],
774
+ "blocks": [
775
+ 128,
776
+ 128
777
+ ],
778
+ "causal": true,
779
+ "dtype": "torch.float16",
780
+ "reference": {
781
+ "max_abs_err": 0.0012365622646322016,
782
+ "mean_abs_err": 3.158613181540662e-05
783
+ },
784
+ "tiled": {
785
+ "max_abs_err": 0.0012365622646322016,
786
+ "mean_abs_err": 3.158781129489352e-05
787
+ },
788
+ "torch_sdpa": {
789
+ "max_abs_err": 0.0012365622646322016,
790
+ "mean_abs_err": 3.4214214869403e-05
791
+ },
792
+ "tiled_vs_reference_max": 0.000244140625,
793
+ "pass": true
794
+ },
795
+ {
796
+ "shape": [
797
+ 1,
798
+ 2,
799
+ 1000,
800
+ 1000,
801
+ 64
802
+ ],
803
+ "blocks": [
804
+ 128,
805
+ 128
806
+ ],
807
+ "causal": false,
808
+ "dtype": "torch.float16",
809
+ "reference": {
810
+ "max_abs_err": 0.00035982249249782994,
811
+ "mean_abs_err": 1.7501874902712585e-05
812
+ },
813
+ "tiled": {
814
+ "max_abs_err": 0.00035982249249782994,
815
+ "mean_abs_err": 1.7502625142655276e-05
816
+ },
817
+ "torch_sdpa": {
818
+ "max_abs_err": 0.00035982249249782994,
819
+ "mean_abs_err": 1.913507111855097e-05
820
+ },
821
+ "tiled_vs_reference_max": 0.0001220703125,
822
+ "pass": true
823
+ }
824
+ ],
825
+ "all_pass": true,
826
+ "performance": [
827
+ {
828
+ "T": 256,
829
+ "heads": 12,
830
+ "head_dim": 128,
831
+ "dtype": "torch.float16",
832
+ "reference": {
833
+ "ms": 0.5706099996132252,
834
+ "extra_peak_mem_mb": 13.59765625
835
+ },
836
+ "tiled_b128": {
837
+ "ms": 1.972371000192652,
838
+ "extra_peak_mem_mb": 8.28125
839
+ },
840
+ "torch_sdpa": {
841
+ "ms": 0.08387500020035077,
842
+ "extra_peak_mem_mb": 0.75
843
+ }
844
+ },
845
+ {
846
+ "T": 512,
847
+ "heads": 12,
848
+ "head_dim": 128,
849
+ "dtype": "torch.float16",
850
+ "reference": {
851
+ "ms": 1.4822440002717485,
852
+ "extra_peak_mem_mb": 45.2734375
853
+ },
854
+ "tiled_b128": {
855
+ "ms": 5.4427400000349735,
856
+ "extra_peak_mem_mb": 9.78125
857
+ },
858
+ "torch_sdpa": {
859
+ "ms": 0.1537445000394655,
860
+ "extra_peak_mem_mb": 1.5
861
+ }
862
+ },
863
+ {
864
+ "T": 1024,
865
+ "heads": 12,
866
+ "head_dim": 128,
867
+ "dtype": "torch.float16",
868
+ "reference": {
869
+ "ms": 4.536613000254874,
870
+ "extra_peak_mem_mb": 163.046875
871
+ },
872
+ "tiled_b128": {
873
+ "ms": 17.767054999694665,
874
+ "extra_peak_mem_mb": 13.525390625
875
+ },
876
+ "torch_sdpa": {
877
+ "ms": 0.27403350031818263,
878
+ "extra_peak_mem_mb": 3.0
879
+ }
880
+ },
881
+ {
882
+ "T": 2048,
883
+ "heads": 12,
884
+ "head_dim": 128,
885
+ "dtype": "torch.float16",
886
+ "reference": {
887
+ "ms": 16.652103499836812,
888
+ "extra_peak_mem_mb": 616.09375
889
+ },
890
+ "tiled_b128": {
891
+ "ms": 63.08115000001635,
892
+ "extra_peak_mem_mb": 22.525390625
893
+ },
894
+ "torch_sdpa": {
895
+ "ms": 0.8313144999192446,
896
+ "extra_peak_mem_mb": 6.0
897
+ }
898
+ },
899
+ {
900
+ "T": 4096,
901
+ "heads": 12,
902
+ "head_dim": 128,
903
+ "dtype": "torch.float16",
904
+ "reference": {
905
+ "ms": 64.80017500007307,
906
+ "extra_peak_mem_mb": 2392.1875
907
+ },
908
+ "tiled_b128": {
909
+ "ms": 241.4875054996628,
910
+ "extra_peak_mem_mb": 40.525390625
911
+ },
912
+ "torch_sdpa": {
913
+ "ms": 3.5911045001739694,
914
+ "extra_peak_mem_mb": 12.0
915
+ }
916
+ }
917
+ ]
918
+ }
attention.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Task 4: reference scaled dot-product attention and tiled online-softmax attention.
2
+
3
+ Shapes: q [B, H, Tq, D], k and v [B, H, Tk, D] (grouped-query attention is handled by the
4
+ caller, which repeats K/V heads). With a KV cache, Tq <= Tk and the queries are the LAST Tq
5
+ positions of the sequence, so query i sits at absolute position (Tk - Tq + i) and may attend
6
+ to key j iff j <= Tk - Tq + i ("bottom-right aligned" causal mask).
7
+
8
+ Both functions accumulate in float32 (float64 for float64 inputs) and cast back to the input dtype.
9
+ """
10
+ from __future__ import annotations
11
+ import math
12
+ import torch
13
+
14
+
15
+ def causal_mask(tq: int, tk: int, device=None) -> torch.Tensor:
16
+ """Boolean [tq, tk]; True = may attend."""
17
+ offset = tk - tq
18
+ qi = torch.arange(tq, device=device).unsqueeze(1) + offset
19
+ kj = torch.arange(tk, device=device).unsqueeze(0)
20
+ return kj <= qi
21
+
22
+
23
+ def reference_attention(q, k, v, causal: bool = True, *, scale: float | None = None):
24
+ """Materialises the full [Tq, Tk] score matrix.
25
+ softmax(x)_j = exp(x_j - max x) / sum_l exp(x_l - max x) (max subtraction for stability)."""
26
+ d = q.shape[-1]
27
+ scale = scale if scale is not None else 1.0 / math.sqrt(d)
28
+ acc = torch.float64 if q.dtype == torch.float64 else torch.float32
29
+ qf, kf, vf = q.to(acc), k.to(acc), v.to(acc)
30
+ scores = torch.matmul(qf, kf.transpose(-1, -2)) * scale # [B,H,Tq,Tk]
31
+ if causal:
32
+ m = causal_mask(q.shape[-2], k.shape[-2], q.device)
33
+ scores = scores.masked_fill(~m, float("-inf"))
34
+ row_max = scores.amax(dim=-1, keepdim=True)
35
+ row_max = torch.where(torch.isfinite(row_max), row_max, torch.zeros_like(row_max)) # fully-masked rows
36
+ p = torch.exp(scores - row_max)
37
+ denom = p.sum(dim=-1, keepdim=True)
38
+ out = torch.matmul(p, vf) / denom.clamp_min(1e-30)
39
+ return out.to(q.dtype)
40
+
41
+
42
+ def tiled_attention(q, k, v, causal: bool = True, *, scale: float | None = None,
43
+ block_q: int = 64, block_k: int = 64):
44
+ """Blocked attention with online softmax (Milakov & Gimelshein 2018; FlashAttention, Dao et al. 2022).
45
+
46
+ For each query tile we stream over key/value tiles keeping, per query row:
47
+ m = running maximum of the scores seen so far
48
+ l = running sum of exp(score - m)
49
+ acc = running sum of exp(score - m) * v
50
+ When a new tile raises the maximum from m to m_new, previous terms are rescaled by
51
+ exp(m - m_new). At the end out = acc / l. Only [block_q, block_k] scores exist at a time,
52
+ so memory is O(Tq*D + block_q*block_k) instead of O(Tq*Tk).
53
+ Key tiles that lie entirely in the causal future of a query tile are skipped.
54
+ """
55
+ B, H, Tq, D = q.shape
56
+ Tk = k.shape[-2]
57
+ scale = scale if scale is not None else 1.0 / math.sqrt(D)
58
+ offset = Tk - Tq
59
+ acc_t = torch.float64 if q.dtype == torch.float64 else torch.float32
60
+ out = torch.empty(B, H, Tq, D, dtype=acc_t, device=q.device)
61
+ for qs in range(0, Tq, block_q):
62
+ qe = min(qs + block_q, Tq)
63
+ qb = q[:, :, qs:qe].to(acc_t) * scale # [B,H,bq,D]
64
+ m = torch.full((B, H, qe - qs, 1), float("-inf"), device=q.device, dtype=acc_t)
65
+ l = torch.zeros((B, H, qe - qs, 1), device=q.device, dtype=acc_t)
66
+ acc = torch.zeros((B, H, qe - qs, D), device=q.device, dtype=acc_t)
67
+ last_visible = (qe - 1) + offset # largest key index any row in this tile may see
68
+ for ks in range(0, Tk, block_k):
69
+ if causal and ks > last_visible:
70
+ break # whole tile is in the future: skip
71
+ ke = min(ks + block_k, Tk)
72
+ kb, vb = k[:, :, ks:ke].to(acc_t), v[:, :, ks:ke].to(acc_t)
73
+ s = torch.matmul(qb, kb.transpose(-1, -2)) # [B,H,bq,bk]
74
+ if causal and ke - 1 > qs + offset: # tile crosses the diagonal: apply mask
75
+ qi = torch.arange(qs, qe, device=q.device).unsqueeze(1) + offset
76
+ kj = torch.arange(ks, ke, device=q.device).unsqueeze(0)
77
+ s = s.masked_fill(kj > qi, float("-inf"))
78
+ m_new = torch.maximum(m, s.amax(dim=-1, keepdim=True))
79
+ m_safe = torch.where(torch.isfinite(m_new), m_new, torch.zeros_like(m_new))
80
+ alpha = torch.exp(torch.where(torch.isfinite(m), m - m_safe, torch.full_like(m, float("-inf"))))
81
+ p = torch.exp(s - m_safe)
82
+ l = alpha * l + p.sum(dim=-1, keepdim=True)
83
+ acc = alpha * acc + torch.matmul(p, vb)
84
+ m = m_new
85
+ out[:, :, qs:qe] = acc / l.clamp_min(1e-30)
86
+ return out.to(q.dtype)
87
+
88
+
89
+ def torch_sdpa(q, k, v, causal: bool = True, *, scale: float | None = None):
90
+ """PyTorch fused/optimised backend, used only as a comparison point."""
91
+ import torch.nn.functional as F
92
+ if causal and q.shape[-2] != k.shape[-2]:
93
+ mask = causal_mask(q.shape[-2], k.shape[-2], q.device)
94
+ return F.scaled_dot_product_attention(q, k, v, attn_mask=mask, scale=scale)
95
+ return F.scaled_dot_product_attention(q, k, v, is_causal=causal, scale=scale)
96
+
97
+
98
+ BACKENDS = {"reference": reference_attention, "tiled": tiled_attention, "torch_sdpa": torch_sdpa}
attention_cpu_quick.json ADDED
@@ -0,0 +1,862 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "env": {
3
+ "python": "3.12.3",
4
+ "torch": "2.15.0+cpu",
5
+ "transformers": "5.22.2",
6
+ "cuda": false
7
+ },
8
+ "device": "cpu",
9
+ "correctness": [
10
+ {
11
+ "shape": [
12
+ 1,
13
+ 1,
14
+ 4,
15
+ 4,
16
+ 8
17
+ ],
18
+ "blocks": [
19
+ 2,
20
+ 2
21
+ ],
22
+ "causal": true,
23
+ "dtype": "torch.float32",
24
+ "reference": {
25
+ "max_abs_err": 1.1725687931729567e-07,
26
+ "mean_abs_err": 2.9335376433136523e-08
27
+ },
28
+ "tiled": {
29
+ "max_abs_err": 1.1909898978146316e-07,
30
+ "mean_abs_err": 3.1560717937955535e-08
31
+ },
32
+ "torch_sdpa": {
33
+ "max_abs_err": 2.3646616886807692e-07,
34
+ "mean_abs_err": 3.494804919545666e-08
35
+ },
36
+ "tiled_vs_reference_max": 1.4901161193847656e-07,
37
+ "pass": true
38
+ },
39
+ {
40
+ "shape": [
41
+ 1,
42
+ 1,
43
+ 4,
44
+ 4,
45
+ 8
46
+ ],
47
+ "blocks": [
48
+ 2,
49
+ 2
50
+ ],
51
+ "causal": false,
52
+ "dtype": "torch.float32",
53
+ "reference": {
54
+ "max_abs_err": 8.699266329514899e-08,
55
+ "mean_abs_err": 2.8101992741706326e-08
56
+ },
57
+ "tiled": {
58
+ "max_abs_err": 1.7561021703471624e-07,
59
+ "mean_abs_err": 4.5280441592505374e-08
60
+ },
61
+ "torch_sdpa": {
62
+ "max_abs_err": 1.2252194248052461e-07,
63
+ "mean_abs_err": 2.8390321463715338e-08
64
+ },
65
+ "tiled_vs_reference_max": 1.1920928955078125e-07,
66
+ "pass": true
67
+ },
68
+ {
69
+ "shape": [
70
+ 2,
71
+ 3,
72
+ 17,
73
+ 17,
74
+ 16
75
+ ],
76
+ "blocks": [
77
+ 4,
78
+ 5
79
+ ],
80
+ "causal": true,
81
+ "dtype": "torch.float32",
82
+ "reference": {
83
+ "max_abs_err": 3.23023136239442e-07,
84
+ "mean_abs_err": 3.490267090149914e-08
85
+ },
86
+ "tiled": {
87
+ "max_abs_err": 3.35794943406853e-07,
88
+ "mean_abs_err": 3.544249767089943e-08
89
+ },
90
+ "torch_sdpa": {
91
+ "max_abs_err": 3.2694433915736454e-07,
92
+ "mean_abs_err": 3.6568687830488763e-08
93
+ },
94
+ "tiled_vs_reference_max": 2.384185791015625e-07,
95
+ "pass": true
96
+ },
97
+ {
98
+ "shape": [
99
+ 2,
100
+ 3,
101
+ 17,
102
+ 17,
103
+ 16
104
+ ],
105
+ "blocks": [
106
+ 4,
107
+ 5
108
+ ],
109
+ "causal": false,
110
+ "dtype": "torch.float32",
111
+ "reference": {
112
+ "max_abs_err": 2.2452636749825672e-07,
113
+ "mean_abs_err": 3.4854188111774424e-08
114
+ },
115
+ "tiled": {
116
+ "max_abs_err": 2.254747906160759e-07,
117
+ "mean_abs_err": 3.480019767865235e-08
118
+ },
119
+ "torch_sdpa": {
120
+ "max_abs_err": 2.6216702808667947e-07,
121
+ "mean_abs_err": 3.757846643705985e-08
122
+ },
123
+ "tiled_vs_reference_max": 3.5762786865234375e-07,
124
+ "pass": true
125
+ },
126
+ {
127
+ "shape": [
128
+ 1,
129
+ 12,
130
+ 128,
131
+ 128,
132
+ 128
133
+ ],
134
+ "blocks": [
135
+ 64,
136
+ 64
137
+ ],
138
+ "causal": true,
139
+ "dtype": "torch.float32",
140
+ "reference": {
141
+ "max_abs_err": 9.677870727031745e-07,
142
+ "mean_abs_err": 5.1866240401221454e-08
143
+ },
144
+ "tiled": {
145
+ "max_abs_err": 8.941690264885338e-07,
146
+ "mean_abs_err": 5.1144709327746014e-08
147
+ },
148
+ "torch_sdpa": {
149
+ "max_abs_err": 8.485777831523933e-07,
150
+ "mean_abs_err": 5.260120562489631e-08
151
+ },
152
+ "tiled_vs_reference_max": 1.1920928955078125e-06,
153
+ "pass": true
154
+ },
155
+ {
156
+ "shape": [
157
+ 1,
158
+ 12,
159
+ 128,
160
+ 128,
161
+ 128
162
+ ],
163
+ "blocks": [
164
+ 64,
165
+ 64
166
+ ],
167
+ "causal": false,
168
+ "dtype": "torch.float32",
169
+ "reference": {
170
+ "max_abs_err": 1.1048535706326135e-06,
171
+ "mean_abs_err": 4.353282208305442e-08
172
+ },
173
+ "tiled": {
174
+ "max_abs_err": 6.366846579952679e-07,
175
+ "mean_abs_err": 4.090662220733632e-08
176
+ },
177
+ "torch_sdpa": {
178
+ "max_abs_err": 1.1048535706326135e-06,
179
+ "mean_abs_err": 4.3815588540722124e-08
180
+ },
181
+ "tiled_vs_reference_max": 1.5497207641601562e-06,
182
+ "pass": true
183
+ },
184
+ {
185
+ "shape": [
186
+ 1,
187
+ 12,
188
+ 1,
189
+ 300,
190
+ 128
191
+ ],
192
+ "blocks": [
193
+ 64,
194
+ 64
195
+ ],
196
+ "causal": true,
197
+ "dtype": "torch.float32",
198
+ "reference": {
199
+ "max_abs_err": 2.947115778084708e-07,
200
+ "mean_abs_err": 2.429470003504172e-08
201
+ },
202
+ "tiled": {
203
+ "max_abs_err": 1.301469574888081e-07,
204
+ "mean_abs_err": 1.667319012588702e-08
205
+ },
206
+ "torch_sdpa": {
207
+ "max_abs_err": 2.947115778084708e-07,
208
+ "mean_abs_err": 2.4848959367844598e-08
209
+ },
210
+ "tiled_vs_reference_max": 2.682209014892578e-07,
211
+ "pass": true
212
+ },
213
+ {
214
+ "shape": [
215
+ 1,
216
+ 12,
217
+ 1,
218
+ 300,
219
+ 128
220
+ ],
221
+ "blocks": [
222
+ 64,
223
+ 64
224
+ ],
225
+ "causal": false,
226
+ "dtype": "torch.float32",
227
+ "reference": {
228
+ "max_abs_err": 1.4582088186942954e-07,
229
+ "mean_abs_err": 2.0267195650057793e-08
230
+ },
231
+ "tiled": {
232
+ "max_abs_err": 8.937245990492393e-08,
233
+ "mean_abs_err": 1.4735564525036104e-08
234
+ },
235
+ "torch_sdpa": {
236
+ "max_abs_err": 1.9783108523574455e-07,
237
+ "mean_abs_err": 2.191691639575331e-08
238
+ },
239
+ "tiled_vs_reference_max": 1.7881393432617188e-07,
240
+ "pass": true
241
+ },
242
+ {
243
+ "shape": [
244
+ 1,
245
+ 12,
246
+ 7,
247
+ 300,
248
+ 128
249
+ ],
250
+ "blocks": [
251
+ 4,
252
+ 64
253
+ ],
254
+ "causal": true,
255
+ "dtype": "torch.float32",
256
+ "reference": {
257
+ "max_abs_err": 4.800062740617506e-07,
258
+ "mean_abs_err": 3.421172706918056e-08
259
+ },
260
+ "tiled": {
261
+ "max_abs_err": 1.269138550363813e-07,
262
+ "mean_abs_err": 1.4280290894487087e-08
263
+ },
264
+ "torch_sdpa": {
265
+ "max_abs_err": 4.353027904802076e-07,
266
+ "mean_abs_err": 3.469895351089288e-08
267
+ },
268
+ "tiled_vs_reference_max": 4.76837158203125e-07,
269
+ "pass": true
270
+ },
271
+ {
272
+ "shape": [
273
+ 1,
274
+ 12,
275
+ 7,
276
+ 300,
277
+ 128
278
+ ],
279
+ "blocks": [
280
+ 4,
281
+ 64
282
+ ],
283
+ "causal": false,
284
+ "dtype": "torch.float32",
285
+ "reference": {
286
+ "max_abs_err": 4.723961299357704e-07,
287
+ "mean_abs_err": 3.471465527479998e-08
288
+ },
289
+ "tiled": {
290
+ "max_abs_err": 1.8560605946627007e-07,
291
+ "mean_abs_err": 1.4604041549048703e-08
292
+ },
293
+ "torch_sdpa": {
294
+ "max_abs_err": 4.425938075480751e-07,
295
+ "mean_abs_err": 3.519863952383722e-08
296
+ },
297
+ "tiled_vs_reference_max": 4.470348358154297e-07,
298
+ "pass": true
299
+ },
300
+ {
301
+ "shape": [
302
+ 2,
303
+ 4,
304
+ 257,
305
+ 257,
306
+ 64
307
+ ],
308
+ "blocks": [
309
+ 32,
310
+ 48
311
+ ],
312
+ "causal": true,
313
+ "dtype": "torch.float32",
314
+ "reference": {
315
+ "max_abs_err": 6.953548001842336e-07,
316
+ "mean_abs_err": 3.678572588071524e-08
317
+ },
318
+ "tiled": {
319
+ "max_abs_err": 6.953548001842336e-07,
320
+ "mean_abs_err": 3.30467117631298e-08
321
+ },
322
+ "torch_sdpa": {
323
+ "max_abs_err": 6.953548001842336e-07,
324
+ "mean_abs_err": 3.725578730675489e-08
325
+ },
326
+ "tiled_vs_reference_max": 3.5762786865234375e-07,
327
+ "pass": true
328
+ },
329
+ {
330
+ "shape": [
331
+ 2,
332
+ 4,
333
+ 257,
334
+ 257,
335
+ 64
336
+ ],
337
+ "blocks": [
338
+ 32,
339
+ 48
340
+ ],
341
+ "causal": false,
342
+ "dtype": "torch.float32",
343
+ "reference": {
344
+ "max_abs_err": 4.511455205802317e-07,
345
+ "mean_abs_err": 2.94892750801417e-08
346
+ },
347
+ "tiled": {
348
+ "max_abs_err": 3.586911044017871e-07,
349
+ "mean_abs_err": 2.3024056065239582e-08
350
+ },
351
+ "torch_sdpa": {
352
+ "max_abs_err": 4.213431981925364e-07,
353
+ "mean_abs_err": 2.976588653476811e-08
354
+ },
355
+ "tiled_vs_reference_max": 4.470348358154297e-07,
356
+ "pass": true
357
+ },
358
+ {
359
+ "shape": [
360
+ 1,
361
+ 2,
362
+ 1000,
363
+ 1000,
364
+ 64
365
+ ],
366
+ "blocks": [
367
+ 128,
368
+ 128
369
+ ],
370
+ "causal": true,
371
+ "dtype": "torch.float32",
372
+ "reference": {
373
+ "max_abs_err": 7.318171661996331e-07,
374
+ "mean_abs_err": 2.579263918807107e-08
375
+ },
376
+ "tiled": {
377
+ "max_abs_err": 7.318171661996331e-07,
378
+ "mean_abs_err": 2.240415382175717e-08
379
+ },
380
+ "torch_sdpa": {
381
+ "max_abs_err": 6.722125214242425e-07,
382
+ "mean_abs_err": 2.48267317496346e-08
383
+ },
384
+ "tiled_vs_reference_max": 4.470348358154297e-07,
385
+ "pass": true
386
+ },
387
+ {
388
+ "shape": [
389
+ 1,
390
+ 2,
391
+ 1000,
392
+ 1000,
393
+ 64
394
+ ],
395
+ "blocks": [
396
+ 128,
397
+ 128
398
+ ],
399
+ "causal": false,
400
+ "dtype": "torch.float32",
401
+ "reference": {
402
+ "max_abs_err": 2.7163703039678744e-07,
403
+ "mean_abs_err": 1.75469427750608e-08
404
+ },
405
+ "tiled": {
406
+ "max_abs_err": 2.567358692029398e-07,
407
+ "mean_abs_err": 1.4230736009406632e-08
408
+ },
409
+ "torch_sdpa": {
410
+ "max_abs_err": 2.451163102767939e-07,
411
+ "mean_abs_err": 1.6391955834459677e-08
412
+ },
413
+ "tiled_vs_reference_max": 1.4901161193847656e-07,
414
+ "pass": true
415
+ },
416
+ {
417
+ "shape": [
418
+ 1,
419
+ 1,
420
+ 4,
421
+ 4,
422
+ 8
423
+ ],
424
+ "blocks": [
425
+ 2,
426
+ 2
427
+ ],
428
+ "causal": true,
429
+ "dtype": "torch.bfloat16",
430
+ "reference": {
431
+ "max_abs_err": 0.0031169871232844537,
432
+ "mean_abs_err": 0.0008288093391584739
433
+ },
434
+ "tiled": {
435
+ "max_abs_err": 0.0031169871232844537,
436
+ "mean_abs_err": 0.0008288093391584739
437
+ },
438
+ "torch_sdpa": {
439
+ "max_abs_err": 0.0031169871232844537,
440
+ "mean_abs_err": 0.0008642316130297834
441
+ },
442
+ "tiled_vs_reference_max": 0.0,
443
+ "pass": true
444
+ },
445
+ {
446
+ "shape": [
447
+ 1,
448
+ 1,
449
+ 4,
450
+ 4,
451
+ 8
452
+ ],
453
+ "blocks": [
454
+ 2,
455
+ 2
456
+ ],
457
+ "causal": false,
458
+ "dtype": "torch.bfloat16",
459
+ "reference": {
460
+ "max_abs_err": 0.007576901301091343,
461
+ "mean_abs_err": 0.001360057984306274
462
+ },
463
+ "tiled": {
464
+ "max_abs_err": 0.007576901301091343,
465
+ "mean_abs_err": 0.001360057984306274
466
+ },
467
+ "torch_sdpa": {
468
+ "max_abs_err": 0.007576901301091343,
469
+ "mean_abs_err": 0.001541342560131863
470
+ },
471
+ "tiled_vs_reference_max": 0.0,
472
+ "pass": true
473
+ },
474
+ {
475
+ "shape": [
476
+ 2,
477
+ 3,
478
+ 17,
479
+ 17,
480
+ 16
481
+ ],
482
+ "blocks": [
483
+ 4,
484
+ 5
485
+ ],
486
+ "causal": true,
487
+ "dtype": "torch.bfloat16",
488
+ "reference": {
489
+ "max_abs_err": 0.012559599257843335,
490
+ "mean_abs_err": 0.0010369836412977892
491
+ },
492
+ "tiled": {
493
+ "max_abs_err": 0.012559599257843335,
494
+ "mean_abs_err": 0.0010369836412977892
495
+ },
496
+ "torch_sdpa": {
497
+ "max_abs_err": 0.012559599257843335,
498
+ "mean_abs_err": 0.0010963785924204012
499
+ },
500
+ "tiled_vs_reference_max": 0.0,
501
+ "pass": true
502
+ },
503
+ {
504
+ "shape": [
505
+ 2,
506
+ 3,
507
+ 17,
508
+ 17,
509
+ 16
510
+ ],
511
+ "blocks": [
512
+ 4,
513
+ 5
514
+ ],
515
+ "causal": false,
516
+ "dtype": "torch.bfloat16",
517
+ "reference": {
518
+ "max_abs_err": 0.0058314656068232384,
519
+ "mean_abs_err": 0.0007939377044326217
520
+ },
521
+ "tiled": {
522
+ "max_abs_err": 0.0058314656068232384,
523
+ "mean_abs_err": 0.0007939377044326217
524
+ },
525
+ "torch_sdpa": {
526
+ "max_abs_err": 0.0058314656068232384,
527
+ "mean_abs_err": 0.000843062224297444
528
+ },
529
+ "tiled_vs_reference_max": 0.0,
530
+ "pass": true
531
+ },
532
+ {
533
+ "shape": [
534
+ 1,
535
+ 12,
536
+ 128,
537
+ 128,
538
+ 128
539
+ ],
540
+ "blocks": [
541
+ 64,
542
+ 64
543
+ ],
544
+ "causal": true,
545
+ "dtype": "torch.bfloat16",
546
+ "reference": {
547
+ "max_abs_err": 0.012845648669523868,
548
+ "mean_abs_err": 0.0005626403209936701
549
+ },
550
+ "tiled": {
551
+ "max_abs_err": 0.012845648669523868,
552
+ "mean_abs_err": 0.0005626499323185544
553
+ },
554
+ "torch_sdpa": {
555
+ "max_abs_err": 0.01250086756572788,
556
+ "mean_abs_err": 0.0006047458788996127
557
+ },
558
+ "tiled_vs_reference_max": 0.001953125,
559
+ "pass": true
560
+ },
561
+ {
562
+ "shape": [
563
+ 1,
564
+ 12,
565
+ 128,
566
+ 128,
567
+ 128
568
+ ],
569
+ "blocks": [
570
+ 64,
571
+ 64
572
+ ],
573
+ "causal": false,
574
+ "dtype": "torch.bfloat16",
575
+ "reference": {
576
+ "max_abs_err": 0.00559653674409355,
577
+ "mean_abs_err": 0.00036087448149727284
578
+ },
579
+ "tiled": {
580
+ "max_abs_err": 0.00559653674409355,
581
+ "mean_abs_err": 0.0003608712339531822
582
+ },
583
+ "torch_sdpa": {
584
+ "max_abs_err": 0.00559653674409355,
585
+ "mean_abs_err": 0.0003940044378704019
586
+ },
587
+ "tiled_vs_reference_max": 0.0009765625,
588
+ "pass": true
589
+ },
590
+ {
591
+ "shape": [
592
+ 1,
593
+ 12,
594
+ 1,
595
+ 300,
596
+ 128
597
+ ],
598
+ "blocks": [
599
+ 64,
600
+ 64
601
+ ],
602
+ "causal": true,
603
+ "dtype": "torch.bfloat16",
604
+ "reference": {
605
+ "max_abs_err": 0.0013842612511065222,
606
+ "mean_abs_err": 0.00022750673233538896
607
+ },
608
+ "tiled": {
609
+ "max_abs_err": 0.0013842612511065222,
610
+ "mean_abs_err": 0.00022755610080492242
611
+ },
612
+ "torch_sdpa": {
613
+ "max_abs_err": 0.0012265852257695165,
614
+ "mean_abs_err": 0.00023815354621773492
615
+ },
616
+ "tiled_vs_reference_max": 0.000244140625,
617
+ "pass": true
618
+ },
619
+ {
620
+ "shape": [
621
+ 1,
622
+ 12,
623
+ 1,
624
+ 300,
625
+ 128
626
+ ],
627
+ "blocks": [
628
+ 64,
629
+ 64
630
+ ],
631
+ "causal": false,
632
+ "dtype": "torch.bfloat16",
633
+ "reference": {
634
+ "max_abs_err": 0.0016523977073409357,
635
+ "mean_abs_err": 0.00024388766322655972
636
+ },
637
+ "tiled": {
638
+ "max_abs_err": 0.0016523977073409357,
639
+ "mean_abs_err": 0.00024388766322655972
640
+ },
641
+ "torch_sdpa": {
642
+ "max_abs_err": 0.0012892500858691092,
643
+ "mean_abs_err": 0.00026911453226223075
644
+ },
645
+ "tiled_vs_reference_max": 0.0,
646
+ "pass": true
647
+ },
648
+ {
649
+ "shape": [
650
+ 1,
651
+ 12,
652
+ 7,
653
+ 300,
654
+ 128
655
+ ],
656
+ "blocks": [
657
+ 4,
658
+ 64
659
+ ],
660
+ "causal": true,
661
+ "dtype": "torch.bfloat16",
662
+ "reference": {
663
+ "max_abs_err": 0.0022469543055876895,
664
+ "mean_abs_err": 0.00023621621721298957
665
+ },
666
+ "tiled": {
667
+ "max_abs_err": 0.0022469543055876895,
668
+ "mean_abs_err": 0.00023627227346012384
669
+ },
670
+ "torch_sdpa": {
671
+ "max_abs_err": 0.0022469543055876895,
672
+ "mean_abs_err": 0.0002577803662330915
673
+ },
674
+ "tiled_vs_reference_max": 0.00048828125,
675
+ "pass": true
676
+ },
677
+ {
678
+ "shape": [
679
+ 1,
680
+ 12,
681
+ 7,
682
+ 300,
683
+ 128
684
+ ],
685
+ "blocks": [
686
+ 4,
687
+ 64
688
+ ],
689
+ "causal": false,
690
+ "dtype": "torch.bfloat16",
691
+ "reference": {
692
+ "max_abs_err": 0.0016663186507077377,
693
+ "mean_abs_err": 0.00024283330114139993
694
+ },
695
+ "tiled": {
696
+ "max_abs_err": 0.0016663186507077377,
697
+ "mean_abs_err": 0.00024281342738288804
698
+ },
699
+ "torch_sdpa": {
700
+ "max_abs_err": 0.002523633791546881,
701
+ "mean_abs_err": 0.0002714033243998184
702
+ },
703
+ "tiled_vs_reference_max": 0.000244140625,
704
+ "pass": true
705
+ },
706
+ {
707
+ "shape": [
708
+ 2,
709
+ 4,
710
+ 257,
711
+ 257,
712
+ 64
713
+ ],
714
+ "blocks": [
715
+ 32,
716
+ 48
717
+ ],
718
+ "causal": true,
719
+ "dtype": "torch.bfloat16",
720
+ "reference": {
721
+ "max_abs_err": 0.008855936887709692,
722
+ "mean_abs_err": 0.0004303511540698291
723
+ },
724
+ "tiled": {
725
+ "max_abs_err": 0.008855936887709692,
726
+ "mean_abs_err": 0.00043034434171890457
727
+ },
728
+ "torch_sdpa": {
729
+ "max_abs_err": 0.00855063841521675,
730
+ "mean_abs_err": 0.0004673215681608276
731
+ },
732
+ "tiled_vs_reference_max": 0.00048828125,
733
+ "pass": true
734
+ },
735
+ {
736
+ "shape": [
737
+ 2,
738
+ 4,
739
+ 257,
740
+ 257,
741
+ 64
742
+ ],
743
+ "blocks": [
744
+ 32,
745
+ 48
746
+ ],
747
+ "causal": false,
748
+ "dtype": "torch.bfloat16",
749
+ "reference": {
750
+ "max_abs_err": 0.004114476781857168,
751
+ "mean_abs_err": 0.00026826984507239695
752
+ },
753
+ "tiled": {
754
+ "max_abs_err": 0.004114476781857168,
755
+ "mean_abs_err": 0.0002682662427758325
756
+ },
757
+ "torch_sdpa": {
758
+ "max_abs_err": 0.004248153154373213,
759
+ "mean_abs_err": 0.0002935257382975162
760
+ },
761
+ "tiled_vs_reference_max": 0.00048828125,
762
+ "pass": true
763
+ },
764
+ {
765
+ "shape": [
766
+ 1,
767
+ 2,
768
+ 1000,
769
+ 1000,
770
+ 64
771
+ ],
772
+ "blocks": [
773
+ 128,
774
+ 128
775
+ ],
776
+ "causal": true,
777
+ "dtype": "torch.bfloat16",
778
+ "reference": {
779
+ "max_abs_err": 0.009091125045569637,
780
+ "mean_abs_err": 0.0002491122620935517
781
+ },
782
+ "tiled": {
783
+ "max_abs_err": 0.009091125045569637,
784
+ "mean_abs_err": 0.00024911302382525657
785
+ },
786
+ "torch_sdpa": {
787
+ "max_abs_err": 0.009091125045569637,
788
+ "mean_abs_err": 0.0002721159914252429
789
+ },
790
+ "tiled_vs_reference_max": 0.0001220703125,
791
+ "pass": true
792
+ },
793
+ {
794
+ "shape": [
795
+ 1,
796
+ 2,
797
+ 1000,
798
+ 1000,
799
+ 64
800
+ ],
801
+ "blocks": [
802
+ 128,
803
+ 128
804
+ ],
805
+ "causal": false,
806
+ "dtype": "torch.bfloat16",
807
+ "reference": {
808
+ "max_abs_err": 0.0015882336474344894,
809
+ "mean_abs_err": 0.00013770671349546093
810
+ },
811
+ "tiled": {
812
+ "max_abs_err": 0.0015882336474344894,
813
+ "mean_abs_err": 0.00013770442922202586
814
+ },
815
+ "torch_sdpa": {
816
+ "max_abs_err": 0.0015882336474344894,
817
+ "mean_abs_err": 0.00015196191828048723
818
+ },
819
+ "tiled_vs_reference_max": 0.00048828125,
820
+ "pass": true
821
+ }
822
+ ],
823
+ "all_pass": true,
824
+ "performance": [
825
+ {
826
+ "T": 128,
827
+ "heads": 12,
828
+ "head_dim": 128,
829
+ "dtype": "torch.float32",
830
+ "reference": {
831
+ "ms": 1.8979640000225118,
832
+ "extra_peak_mem_mb": null
833
+ },
834
+ "tiled_b128": {
835
+ "ms": 2.4560409999594413,
836
+ "extra_peak_mem_mb": null
837
+ },
838
+ "torch_sdpa": {
839
+ "ms": 1.0385260000020935,
840
+ "extra_peak_mem_mb": null
841
+ }
842
+ },
843
+ {
844
+ "T": 256,
845
+ "heads": 12,
846
+ "head_dim": 128,
847
+ "dtype": "torch.float32",
848
+ "reference": {
849
+ "ms": 6.799867000040649,
850
+ "extra_peak_mem_mb": null
851
+ },
852
+ "tiled_b128": {
853
+ "ms": 6.028183000012177,
854
+ "extra_peak_mem_mb": null
855
+ },
856
+ "torch_sdpa": {
857
+ "ms": 3.273119999903429,
858
+ "extra_peak_mem_mb": null
859
+ }
860
+ }
861
+ ]
862
+ }
bench_kv.json ADDED
@@ -0,0 +1,652 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "env": {
3
+ "python": "3.13.16",
4
+ "torch": "2.11.0+cu130",
5
+ "transformers": "5.22.2",
6
+ "cuda": true,
7
+ "gpu": "Tesla T4",
8
+ "gpu_mem_gb": 14.6
9
+ },
10
+ "model": "Qwen/Qwen2.5-1.5B-Instruct",
11
+ "adapter": "/kaggle/working/trialscreen/checkpoints/qwen2.5-1.5b-trialscreen-lora/best_adapter",
12
+ "dtype": "torch.float16",
13
+ "decoding": "greedy, EOS ignored",
14
+ "repeats": 3,
15
+ "warmup": 1,
16
+ "fp32_recheck": [
17
+ {
18
+ "input_tokens": 128,
19
+ "output_tokens": 128,
20
+ "fp16_mismatched_paths": [
21
+ "explicit_cache_refattn"
22
+ ],
23
+ "explicit_cache_refattn": {
24
+ "fp32_tokens_equal_reference": true,
25
+ "fp32_first_mismatch": null
26
+ }
27
+ },
28
+ {
29
+ "input_tokens": 128,
30
+ "output_tokens": 256,
31
+ "fp16_mismatched_paths": [
32
+ "explicit_nocache",
33
+ "explicit_cache",
34
+ "explicit_cache_refattn",
35
+ "hf_cache"
36
+ ],
37
+ "explicit_nocache": {
38
+ "fp32_tokens_equal_reference": true,
39
+ "fp32_first_mismatch": null
40
+ },
41
+ "explicit_cache": {
42
+ "fp32_tokens_equal_reference": true,
43
+ "fp32_first_mismatch": null
44
+ },
45
+ "explicit_cache_refattn": {
46
+ "fp32_tokens_equal_reference": true,
47
+ "fp32_first_mismatch": null
48
+ },
49
+ "hf_cache": {
50
+ "fp32_tokens_equal_reference": true,
51
+ "fp32_first_mismatch": null
52
+ }
53
+ }
54
+ ],
55
+ "kv_bytes_per_token_theory": 28672,
56
+ "results": [
57
+ {
58
+ "input_tokens": 128,
59
+ "output_tokens": 32,
60
+ "modes": {
61
+ "hf_nocache": {
62
+ "prefill_s": 0.04139519199998176,
63
+ "decode_s": 1.2836443900000631,
64
+ "total_s": 1.3245814699998846,
65
+ "tokens_per_s": 24.158574406150183,
66
+ "decode_tokens_per_s": 24.14999063720325,
67
+ "peak_mem_mb": 2964.2041015625,
68
+ "cache_mb": null,
69
+ "tokens_equal_reference": true,
70
+ "first_mismatch": null,
71
+ "mismatch_margin": null
72
+ },
73
+ "explicit_nocache": {
74
+ "prefill_s": 0.03217160199983482,
75
+ "decode_s": 1.176887910000005,
76
+ "total_s": 1.2090595119998397,
77
+ "tokens_per_s": 26.46685269203212,
78
+ "decode_tokens_per_s": 26.340656350187054,
79
+ "peak_mem_mb": 3189.40771484375,
80
+ "cache_mb": null,
81
+ "tokens_equal_reference": true,
82
+ "first_mismatch": null,
83
+ "mismatch_margin": null
84
+ },
85
+ "explicit_cache": {
86
+ "prefill_s": 0.030430168000293634,
87
+ "decode_s": 1.0268804269999237,
88
+ "total_s": 1.0566298319999987,
89
+ "tokens_per_s": 30.284967384869404,
90
+ "decode_tokens_per_s": 30.18851969996922,
91
+ "peak_mem_mb": 3074.623046875,
92
+ "cache_mb": 4.34765625,
93
+ "tokens_equal_reference": true,
94
+ "first_mismatch": null,
95
+ "mismatch_margin": null
96
+ },
97
+ "explicit_cache_refattn": {
98
+ "prefill_s": 0.04333662199996979,
99
+ "decode_s": 1.262058159999924,
100
+ "total_s": 1.305394781999894,
101
+ "tokens_per_s": 24.513657049383397,
102
+ "decode_tokens_per_s": 24.563051832731595,
103
+ "peak_mem_mb": 3074.623046875,
104
+ "cache_mb": 4.34765625,
105
+ "tokens_equal_reference": true,
106
+ "first_mismatch": null,
107
+ "mismatch_margin": null
108
+ },
109
+ "hf_cache": {
110
+ "prefill_s": 0.041701325999838446,
111
+ "decode_s": 1.1307818830000542,
112
+ "total_s": 1.1721233080002094,
113
+ "tokens_per_s": 27.30088189662916,
114
+ "decode_tokens_per_s": 27.414659242465518,
115
+ "peak_mem_mb": 2965.154296875,
116
+ "cache_mb": null,
117
+ "tokens_equal_reference": true,
118
+ "first_mismatch": null,
119
+ "mismatch_margin": null
120
+ }
121
+ }
122
+ },
123
+ {
124
+ "input_tokens": 128,
125
+ "output_tokens": 128,
126
+ "modes": {
127
+ "hf_nocache": {
128
+ "prefill_s": 0.040755073000127595,
129
+ "decode_s": 6.296541116999833,
130
+ "total_s": 6.337929911000174,
131
+ "tokens_per_s": 20.195868650715422,
132
+ "decode_tokens_per_s": 20.169803966993353,
133
+ "peak_mem_mb": 2970.904296875,
134
+ "cache_mb": null,
135
+ "tokens_equal_reference": true,
136
+ "first_mismatch": null,
137
+ "mismatch_margin": null
138
+ },
139
+ "explicit_nocache": {
140
+ "prefill_s": 0.03268261699986397,
141
+ "decode_s": 5.623788957000215,
142
+ "total_s": 5.656471574000079,
143
+ "tokens_per_s": 22.628947803494825,
144
+ "decode_tokens_per_s": 22.582639741826846,
145
+ "peak_mem_mb": 3196.228515625,
146
+ "cache_mb": null,
147
+ "tokens_equal_reference": true,
148
+ "first_mismatch": null,
149
+ "mismatch_margin": null
150
+ },
151
+ "explicit_cache": {
152
+ "prefill_s": 0.02967817799981276,
153
+ "decode_s": 4.224423796999872,
154
+ "total_s": 4.254101974999685,
155
+ "tokens_per_s": 30.08860642086735,
156
+ "decode_tokens_per_s": 30.06327160882714,
157
+ "peak_mem_mb": 3074.623046875,
158
+ "cache_mb": 6.97265625,
159
+ "tokens_equal_reference": true,
160
+ "first_mismatch": null,
161
+ "mismatch_margin": null
162
+ },
163
+ "explicit_cache_refattn": {
164
+ "prefill_s": 0.043873473000076046,
165
+ "decode_s": 5.335237466000308,
166
+ "total_s": 5.3805410899999515,
167
+ "tokens_per_s": 23.78942895499775,
168
+ "decode_tokens_per_s": 23.804001379381653,
169
+ "peak_mem_mb": 3074.623046875,
170
+ "cache_mb": 6.97265625,
171
+ "tokens_equal_reference": false,
172
+ "first_mismatch": 45,
173
+ "mismatch_margin": 0.0
174
+ },
175
+ "hf_cache": {
176
+ "prefill_s": 0.04386625799998001,
177
+ "decode_s": 4.855760313000246,
178
+ "total_s": 4.899732595999922,
179
+ "tokens_per_s": 26.123874618075597,
180
+ "decode_tokens_per_s": 26.15450347909163,
181
+ "peak_mem_mb": 2966.09814453125,
182
+ "cache_mb": null,
183
+ "tokens_equal_reference": true,
184
+ "first_mismatch": null,
185
+ "mismatch_margin": null
186
+ }
187
+ }
188
+ },
189
+ {
190
+ "input_tokens": 128,
191
+ "output_tokens": 256,
192
+ "modes": {
193
+ "hf_nocache": {
194
+ "prefill_s": 0.04067653699985385,
195
+ "decode_s": 16.0347104260004,
196
+ "total_s": 16.075386963000255,
197
+ "tokens_per_s": 15.92496657089622,
198
+ "decode_tokens_per_s": 15.90300000594433,
199
+ "peak_mem_mb": 2984.56298828125,
200
+ "cache_mb": null,
201
+ "tokens_equal_reference": true,
202
+ "first_mismatch": null,
203
+ "mismatch_margin": null
204
+ },
205
+ "explicit_nocache": {
206
+ "prefill_s": 0.035179704999791284,
207
+ "decode_s": 13.885409428000003,
208
+ "total_s": 13.920589132999794,
209
+ "tokens_per_s": 18.390026280793887,
210
+ "decode_tokens_per_s": 18.36460072151644,
211
+ "peak_mem_mb": 3205.32373046875,
212
+ "cache_mb": null,
213
+ "tokens_equal_reference": false,
214
+ "first_mismatch": 163,
215
+ "mismatch_margin": 0.0
216
+ },
217
+ "explicit_cache": {
218
+ "prefill_s": 0.03135377599983258,
219
+ "decode_s": 8.611173279999548,
220
+ "total_s": 8.643471596999916,
221
+ "tokens_per_s": 29.61772907182985,
222
+ "decode_tokens_per_s": 29.612689433653273,
223
+ "peak_mem_mb": 3074.623046875,
224
+ "cache_mb": 10.47265625,
225
+ "tokens_equal_reference": false,
226
+ "first_mismatch": 163,
227
+ "mismatch_margin": 0.0
228
+ },
229
+ "explicit_cache_refattn": {
230
+ "prefill_s": 0.04442052000013064,
231
+ "decode_s": 10.82452259799993,
232
+ "total_s": 10.869705982000141,
233
+ "tokens_per_s": 23.551694997447694,
234
+ "decode_tokens_per_s": 23.557620919662256,
235
+ "peak_mem_mb": 3074.623046875,
236
+ "cache_mb": 10.47265625,
237
+ "tokens_equal_reference": false,
238
+ "first_mismatch": 45,
239
+ "mismatch_margin": 0.0
240
+ },
241
+ "hf_cache": {
242
+ "prefill_s": 0.04424592199984545,
243
+ "decode_s": 9.564428730000145,
244
+ "total_s": 9.60867465199999,
245
+ "tokens_per_s": 26.6425921650615,
246
+ "decode_tokens_per_s": 26.66128915783098,
247
+ "peak_mem_mb": 2972.10400390625,
248
+ "cache_mb": null,
249
+ "tokens_equal_reference": false,
250
+ "first_mismatch": 163,
251
+ "mismatch_margin": 0.0
252
+ }
253
+ }
254
+ },
255
+ {
256
+ "input_tokens": 512,
257
+ "output_tokens": 32,
258
+ "modes": {
259
+ "hf_nocache": {
260
+ "prefill_s": 0.11856701299984707,
261
+ "decode_s": 4.357428823999726,
262
+ "total_s": 4.477470622000055,
263
+ "tokens_per_s": 7.146892230351658,
264
+ "decode_tokens_per_s": 7.114287175331254,
265
+ "peak_mem_mb": 3006.5673828125,
266
+ "cache_mb": null,
267
+ "tokens_equal_reference": true,
268
+ "first_mismatch": null,
269
+ "mismatch_margin": null
270
+ },
271
+ "explicit_nocache": {
272
+ "prefill_s": 0.09162798499983182,
273
+ "decode_s": 3.438287148999734,
274
+ "total_s": 3.5287590799998725,
275
+ "tokens_per_s": 9.068343651276175,
276
+ "decode_tokens_per_s": 9.016117228317743,
277
+ "peak_mem_mb": 3216.6962890625,
278
+ "cache_mb": null,
279
+ "tokens_equal_reference": true,
280
+ "first_mismatch": null,
281
+ "mismatch_margin": null
282
+ },
283
+ "explicit_cache": {
284
+ "prefill_s": 0.07562392999989243,
285
+ "decode_s": 1.0279551799999354,
286
+ "total_s": 1.1012755530000504,
287
+ "tokens_per_s": 29.057214529848494,
288
+ "decode_tokens_per_s": 30.156956843198113,
289
+ "peak_mem_mb": 3101.90869140625,
290
+ "cache_mb": 14.84765625,
291
+ "tokens_equal_reference": true,
292
+ "first_mismatch": null,
293
+ "mismatch_margin": null
294
+ },
295
+ "explicit_cache_refattn": {
296
+ "prefill_s": 0.10784638299992366,
297
+ "decode_s": 1.3035664110002472,
298
+ "total_s": 1.4138341190000574,
299
+ "tokens_per_s": 22.633489721292193,
300
+ "decode_tokens_per_s": 23.780913452819952,
301
+ "peak_mem_mb": 3120.93212890625,
302
+ "cache_mb": 14.84765625,
303
+ "tokens_equal_reference": true,
304
+ "first_mismatch": null,
305
+ "mismatch_margin": null
306
+ },
307
+ "hf_cache": {
308
+ "prefill_s": 0.10966539599985481,
309
+ "decode_s": 1.1684797049997542,
310
+ "total_s": 1.2819255800000064,
311
+ "tokens_per_s": 24.962447508068166,
312
+ "decode_tokens_per_s": 26.530199769286128,
313
+ "peak_mem_mb": 3014.79150390625,
314
+ "cache_mb": null,
315
+ "tokens_equal_reference": true,
316
+ "first_mismatch": null,
317
+ "mismatch_margin": null
318
+ }
319
+ }
320
+ },
321
+ {
322
+ "input_tokens": 512,
323
+ "output_tokens": 128,
324
+ "modes": {
325
+ "hf_nocache": {
326
+ "prefill_s": 0.12143381099986073,
327
+ "decode_s": 19.144767605000197,
328
+ "total_s": 19.266201416000058,
329
+ "tokens_per_s": 6.643759049134588,
330
+ "decode_tokens_per_s": 6.633666316577818,
331
+ "peak_mem_mb": 3022.39306640625,
332
+ "cache_mb": null,
333
+ "tokens_equal_reference": true,
334
+ "first_mismatch": null,
335
+ "mismatch_margin": null
336
+ },
337
+ "explicit_nocache": {
338
+ "prefill_s": 0.09335073600004762,
339
+ "decode_s": 14.81296856500012,
340
+ "total_s": 14.906319301000167,
341
+ "tokens_per_s": 8.586962174586693,
342
+ "decode_tokens_per_s": 8.573568454068948,
343
+ "peak_mem_mb": 3223.51708984375,
344
+ "cache_mb": null,
345
+ "tokens_equal_reference": true,
346
+ "first_mismatch": null,
347
+ "mismatch_margin": null
348
+ },
349
+ "explicit_cache": {
350
+ "prefill_s": 0.07605032600031336,
351
+ "decode_s": 4.2748423650000404,
352
+ "total_s": 4.349893513999632,
353
+ "tokens_per_s": 29.42600769146342,
354
+ "decode_tokens_per_s": 29.708697808322295,
355
+ "peak_mem_mb": 3101.90869140625,
356
+ "cache_mb": 17.47265625,
357
+ "tokens_equal_reference": true,
358
+ "first_mismatch": null,
359
+ "mismatch_margin": null
360
+ },
361
+ "explicit_cache_refattn": {
362
+ "prefill_s": 0.11093382299986843,
363
+ "decode_s": 5.378496889999951,
364
+ "total_s": 5.48943071299982,
365
+ "tokens_per_s": 23.317536315173125,
366
+ "decode_tokens_per_s": 23.61254502835664,
367
+ "peak_mem_mb": 3120.93212890625,
368
+ "cache_mb": 17.47265625,
369
+ "tokens_equal_reference": true,
370
+ "first_mismatch": null,
371
+ "mismatch_margin": null
372
+ },
373
+ "hf_cache": {
374
+ "prefill_s": 0.11373577199992724,
375
+ "decode_s": 4.781249634999767,
376
+ "total_s": 4.886412978999942,
377
+ "tokens_per_s": 26.195084318517136,
378
+ "decode_tokens_per_s": 26.562093531016014,
379
+ "peak_mem_mb": 3014.79150390625,
380
+ "cache_mb": null,
381
+ "tokens_equal_reference": true,
382
+ "first_mismatch": null,
383
+ "mismatch_margin": null
384
+ }
385
+ }
386
+ },
387
+ {
388
+ "input_tokens": 512,
389
+ "output_tokens": 256,
390
+ "modes": {
391
+ "hf_nocache": {
392
+ "prefill_s": 0.1190551280001273,
393
+ "decode_s": 42.30723943000021,
394
+ "total_s": 42.42261904499992,
395
+ "tokens_per_s": 6.034516627284309,
396
+ "decode_tokens_per_s": 6.0273372461919275,
397
+ "peak_mem_mb": 3046.556640625,
398
+ "cache_mb": null,
399
+ "tokens_equal_reference": true,
400
+ "first_mismatch": null,
401
+ "mismatch_margin": null
402
+ },
403
+ "explicit_nocache": {
404
+ "prefill_s": 0.09181152100018153,
405
+ "decode_s": 31.60840039599998,
406
+ "total_s": 31.698679511000137,
407
+ "tokens_per_s": 8.076046193380465,
408
+ "decode_tokens_per_s": 8.067475633226605,
409
+ "peak_mem_mb": 3232.6123046875,
410
+ "cache_mb": null,
411
+ "tokens_equal_reference": true,
412
+ "first_mismatch": null,
413
+ "mismatch_margin": null
414
+ },
415
+ "explicit_cache": {
416
+ "prefill_s": 0.07497068700013187,
417
+ "decode_s": 8.539205928999763,
418
+ "total_s": 8.614478938000047,
419
+ "tokens_per_s": 29.717409705506043,
420
+ "decode_tokens_per_s": 29.86226144681691,
421
+ "peak_mem_mb": 3101.90869140625,
422
+ "cache_mb": 20.97265625,
423
+ "tokens_equal_reference": true,
424
+ "first_mismatch": null,
425
+ "mismatch_margin": null
426
+ },
427
+ "explicit_cache_refattn": {
428
+ "prefill_s": 0.10896174500021516,
429
+ "decode_s": 10.756328363000193,
430
+ "total_s": 10.863865443000122,
431
+ "tokens_per_s": 23.564356659530205,
432
+ "decode_tokens_per_s": 23.706974294049395,
433
+ "peak_mem_mb": 3120.93212890625,
434
+ "cache_mb": 20.97265625,
435
+ "tokens_equal_reference": true,
436
+ "first_mismatch": null,
437
+ "mismatch_margin": null
438
+ },
439
+ "hf_cache": {
440
+ "prefill_s": 0.10617155300042214,
441
+ "decode_s": 9.62624697199999,
442
+ "total_s": 9.740776547000223,
443
+ "tokens_per_s": 26.281272213234164,
444
+ "decode_tokens_per_s": 26.49007455779208,
445
+ "peak_mem_mb": 3014.79150390625,
446
+ "cache_mb": null,
447
+ "tokens_equal_reference": true,
448
+ "first_mismatch": null,
449
+ "mismatch_margin": null
450
+ }
451
+ }
452
+ },
453
+ {
454
+ "input_tokens": 1024,
455
+ "output_tokens": 32,
456
+ "modes": {
457
+ "hf_nocache": {
458
+ "prefill_s": 0.27901941400023134,
459
+ "decode_s": 9.330587455000114,
460
+ "total_s": 9.61076237799989,
461
+ "tokens_per_s": 3.329600581245415,
462
+ "decode_tokens_per_s": 3.32240602743481,
463
+ "peak_mem_mb": 3113.7255859375,
464
+ "cache_mb": null,
465
+ "tokens_equal_reference": true,
466
+ "first_mismatch": null,
467
+ "mismatch_margin": null
468
+ },
469
+ "explicit_nocache": {
470
+ "prefill_s": 0.1762782830001015,
471
+ "decode_s": 6.0300998849997995,
472
+ "total_s": 6.206378167999901,
473
+ "tokens_per_s": 5.155986170000415,
474
+ "decode_tokens_per_s": 5.140876700419869,
475
+ "peak_mem_mb": 3253.0810546875,
476
+ "cache_mb": null,
477
+ "tokens_equal_reference": true,
478
+ "first_mismatch": null,
479
+ "mismatch_margin": null
480
+ },
481
+ "explicit_cache": {
482
+ "prefill_s": 0.16770410800017999,
483
+ "decode_s": 1.0361290689997986,
484
+ "total_s": 1.2038331769999786,
485
+ "tokens_per_s": 26.581756186306343,
486
+ "decode_tokens_per_s": 29.919052488243647,
487
+ "peak_mem_mb": 3138.28955078125,
488
+ "cache_mb": 28.84765625,
489
+ "tokens_equal_reference": true,
490
+ "first_mismatch": null,
491
+ "mismatch_margin": null
492
+ },
493
+ "explicit_cache_refattn": {
494
+ "prefill_s": 0.27626364000025205,
495
+ "decode_s": 1.3120880970000144,
496
+ "total_s": 1.5916917230001673,
497
+ "tokens_per_s": 20.104395554488057,
498
+ "decode_tokens_per_s": 23.626462331972256,
499
+ "peak_mem_mb": 3248.83642578125,
500
+ "cache_mb": 28.84765625,
501
+ "tokens_equal_reference": true,
502
+ "first_mismatch": null,
503
+ "mismatch_margin": null
504
+ },
505
+ "hf_cache": {
506
+ "prefill_s": 0.2697717400001238,
507
+ "decode_s": 1.1655697589999363,
508
+ "total_s": 1.4353414990000601,
509
+ "tokens_per_s": 22.294345995216474,
510
+ "decode_tokens_per_s": 26.596434714124815,
511
+ "peak_mem_mb": 3132.05517578125,
512
+ "cache_mb": null,
513
+ "tokens_equal_reference": true,
514
+ "first_mismatch": null,
515
+ "mismatch_margin": null
516
+ }
517
+ }
518
+ },
519
+ {
520
+ "input_tokens": 1024,
521
+ "output_tokens": 128,
522
+ "modes": {
523
+ "hf_nocache": {
524
+ "prefill_s": 0.27626948999977685,
525
+ "decode_s": 40.35098881700014,
526
+ "total_s": 40.62725830699992,
527
+ "tokens_per_s": 3.1505940920937334,
528
+ "decode_tokens_per_s": 3.147382597635229,
529
+ "peak_mem_mb": 3140.05126953125,
530
+ "cache_mb": null,
531
+ "tokens_equal_reference": true,
532
+ "first_mismatch": null,
533
+ "mismatch_margin": null
534
+ },
535
+ "explicit_nocache": {
536
+ "prefill_s": 0.1782898930000556,
537
+ "decode_s": 25.487879752000026,
538
+ "total_s": 25.665845194999747,
539
+ "tokens_per_s": 4.987172603415263,
540
+ "decode_tokens_per_s": 4.9827604820693,
541
+ "peak_mem_mb": 3259.90185546875,
542
+ "cache_mb": null,
543
+ "tokens_equal_reference": true,
544
+ "first_mismatch": null,
545
+ "mismatch_margin": null
546
+ },
547
+ "explicit_cache": {
548
+ "prefill_s": 0.1664767090001078,
549
+ "decode_s": 4.283362536999903,
550
+ "total_s": 4.4498392460000105,
551
+ "tokens_per_s": 28.765084067937966,
552
+ "decode_tokens_per_s": 29.64960329716842,
553
+ "peak_mem_mb": 3138.28955078125,
554
+ "cache_mb": 31.47265625,
555
+ "tokens_equal_reference": true,
556
+ "first_mismatch": null,
557
+ "mismatch_margin": null
558
+ },
559
+ "explicit_cache_refattn": {
560
+ "prefill_s": 0.274512188999779,
561
+ "decode_s": 5.354731128000367,
562
+ "total_s": 5.632045753000057,
563
+ "tokens_per_s": 22.727088097929148,
564
+ "decode_tokens_per_s": 23.717343964462692,
565
+ "peak_mem_mb": 3248.83642578125,
566
+ "cache_mb": 31.47265625,
567
+ "tokens_equal_reference": true,
568
+ "first_mismatch": null,
569
+ "mismatch_margin": null
570
+ },
571
+ "hf_cache": {
572
+ "prefill_s": 0.27100409800004854,
573
+ "decode_s": 4.781407987999955,
574
+ "total_s": 5.052412086000004,
575
+ "tokens_per_s": 25.33443389439313,
576
+ "decode_tokens_per_s": 26.561213834656183,
577
+ "peak_mem_mb": 3132.05517578125,
578
+ "cache_mb": null,
579
+ "tokens_equal_reference": true,
580
+ "first_mismatch": null,
581
+ "mismatch_margin": null
582
+ }
583
+ }
584
+ },
585
+ {
586
+ "input_tokens": 1024,
587
+ "output_tokens": 256,
588
+ "modes": {
589
+ "hf_nocache": {
590
+ "prefill_s": 0.28001466000023356,
591
+ "decode_s": 87.70607535599993,
592
+ "total_s": 87.98740933999989,
593
+ "tokens_per_s": 2.9095071888157076,
594
+ "decode_tokens_per_s": 2.9074382699824635,
595
+ "peak_mem_mb": 3178.21484375,
596
+ "cache_mb": null,
597
+ "tokens_equal_reference": true,
598
+ "first_mismatch": null,
599
+ "mismatch_margin": null
600
+ },
601
+ "explicit_nocache": {
602
+ "prefill_s": 0.17921891799960576,
603
+ "decode_s": 53.68922958500025,
604
+ "total_s": 53.868448502999854,
605
+ "tokens_per_s": 4.752318047284093,
606
+ "decode_tokens_per_s": 4.749555953234281,
607
+ "peak_mem_mb": 3268.9970703125,
608
+ "cache_mb": null,
609
+ "tokens_equal_reference": true,
610
+ "first_mismatch": null,
611
+ "mismatch_margin": null
612
+ },
613
+ "explicit_cache": {
614
+ "prefill_s": 0.16375905199993213,
615
+ "decode_s": 8.518601337000291,
616
+ "total_s": 8.682360389000223,
617
+ "tokens_per_s": 29.48506955831149,
618
+ "decode_tokens_per_s": 29.934491580491635,
619
+ "peak_mem_mb": 3138.28955078125,
620
+ "cache_mb": 34.97265625,
621
+ "tokens_equal_reference": true,
622
+ "first_mismatch": null,
623
+ "mismatch_margin": null
624
+ },
625
+ "explicit_cache_refattn": {
626
+ "prefill_s": 0.27404768099995636,
627
+ "decode_s": 10.675581305999913,
628
+ "total_s": 10.952955072999885,
629
+ "tokens_per_s": 23.372687853989767,
630
+ "decode_tokens_per_s": 23.88628709676768,
631
+ "peak_mem_mb": 3248.83642578125,
632
+ "cache_mb": 34.97265625,
633
+ "tokens_equal_reference": true,
634
+ "first_mismatch": null,
635
+ "mismatch_margin": null
636
+ },
637
+ "hf_cache": {
638
+ "prefill_s": 0.2689084870003171,
639
+ "decode_s": 9.653962325000066,
640
+ "total_s": 9.924135726000259,
641
+ "tokens_per_s": 25.795697183917508,
642
+ "decode_tokens_per_s": 26.41402477194754,
643
+ "peak_mem_mb": 3132.05517578125,
644
+ "cache_mb": null,
645
+ "tokens_equal_reference": true,
646
+ "first_mismatch": null,
647
+ "mismatch_margin": null
648
+ }
649
+ }
650
+ }
651
+ ]
652
+ }
bench_kv_tiny_cpu_quick.json ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "env": {
3
+ "python": "3.12.3",
4
+ "torch": "2.15.0+cpu",
5
+ "transformers": "5.22.2",
6
+ "cuda": false
7
+ },
8
+ "model": "/tmp/tiny-qwen",
9
+ "adapter": null,
10
+ "dtype": "torch.float32",
11
+ "decoding": "greedy, EOS ignored",
12
+ "repeats": 1,
13
+ "warmup": 1,
14
+ "kv_bytes_per_token_theory": 256,
15
+ "results": [
16
+ {
17
+ "input_tokens": 32,
18
+ "output_tokens": 8,
19
+ "modes": {
20
+ "hf_nocache": {
21
+ "prefill_s": 0.007317987000078574,
22
+ "decode_s": 0.08488595699998314,
23
+ "total_s": 0.09220394400006171,
24
+ "tokens_per_s": 86.76418440402773,
25
+ "decode_tokens_per_s": 82.46358110801991,
26
+ "peak_mem_mb": null,
27
+ "cache_mb": null,
28
+ "tokens_equal_reference": true,
29
+ "first_mismatch": null,
30
+ "mismatch_margin": null
31
+ },
32
+ "explicit_nocache": {
33
+ "prefill_s": 0.01265770899999552,
34
+ "decode_s": 0.06466986500004168,
35
+ "total_s": 0.0773275740000372,
36
+ "tokens_per_s": 103.45598065699244,
37
+ "decode_tokens_per_s": 108.24206916150959,
38
+ "peak_mem_mb": null,
39
+ "cache_mb": null,
40
+ "tokens_equal_reference": true,
41
+ "first_mismatch": null,
42
+ "mismatch_margin": null
43
+ },
44
+ "explicit_cache": {
45
+ "prefill_s": 0.005451218999951379,
46
+ "decode_s": 0.013251598000010745,
47
+ "total_s": 0.018702816999962124,
48
+ "tokens_per_s": 427.7430506867602,
49
+ "decode_tokens_per_s": 528.2381792742524,
50
+ "peak_mem_mb": null,
51
+ "cache_mb": 0.009521484375,
52
+ "tokens_equal_reference": true,
53
+ "first_mismatch": null,
54
+ "mismatch_margin": null
55
+ },
56
+ "explicit_cache_refattn": {
57
+ "prefill_s": 0.0056102620000046954,
58
+ "decode_s": 0.013915139999994608,
59
+ "total_s": 0.019525401999999303,
60
+ "tokens_per_s": 409.7226781809811,
61
+ "decode_tokens_per_s": 503.049196774356,
62
+ "peak_mem_mb": null,
63
+ "cache_mb": 0.009521484375,
64
+ "tokens_equal_reference": true,
65
+ "first_mismatch": null,
66
+ "mismatch_margin": null
67
+ },
68
+ "hf_cache": {
69
+ "prefill_s": 0.005608906000020397,
70
+ "decode_s": 0.014035755000008976,
71
+ "total_s": 0.019644661000029373,
72
+ "tokens_per_s": 407.23532974114636,
73
+ "decode_tokens_per_s": 498.7262886816935,
74
+ "peak_mem_mb": null,
75
+ "cache_mb": null,
76
+ "tokens_equal_reference": true,
77
+ "first_mismatch": null,
78
+ "mismatch_margin": null
79
+ }
80
+ }
81
+ },
82
+ {
83
+ "input_tokens": 32,
84
+ "output_tokens": 16,
85
+ "modes": {
86
+ "hf_nocache": {
87
+ "prefill_s": 0.012575818999948751,
88
+ "decode_s": 0.20483556700003192,
89
+ "total_s": 0.21741138599998067,
90
+ "tokens_per_s": 73.59320178383584,
91
+ "decode_tokens_per_s": 73.22946995820146,
92
+ "peak_mem_mb": null,
93
+ "cache_mb": null,
94
+ "tokens_equal_reference": true,
95
+ "first_mismatch": null,
96
+ "mismatch_margin": null
97
+ },
98
+ "explicit_nocache": {
99
+ "prefill_s": 0.013488909999978205,
100
+ "decode_s": 0.13026361799995811,
101
+ "total_s": 0.14375252799993632,
102
+ "tokens_per_s": 111.30239045261929,
103
+ "decode_tokens_per_s": 115.15110842387952,
104
+ "peak_mem_mb": null,
105
+ "cache_mb": null,
106
+ "tokens_equal_reference": true,
107
+ "first_mismatch": null,
108
+ "mismatch_margin": null
109
+ },
110
+ "explicit_cache": {
111
+ "prefill_s": 0.0054928939999854265,
112
+ "decode_s": 0.027969528999960858,
113
+ "total_s": 0.033462422999946284,
114
+ "tokens_per_s": 478.1482799385354,
115
+ "decode_tokens_per_s": 536.2979119176798,
116
+ "peak_mem_mb": null,
117
+ "cache_mb": 0.011474609375,
118
+ "tokens_equal_reference": true,
119
+ "first_mismatch": null,
120
+ "mismatch_margin": null
121
+ },
122
+ "explicit_cache_refattn": {
123
+ "prefill_s": 0.00561342200001036,
124
+ "decode_s": 0.02960321299997304,
125
+ "total_s": 0.0352166349999834,
126
+ "tokens_per_s": 454.3307445474999,
127
+ "decode_tokens_per_s": 506.70175565110657,
128
+ "peak_mem_mb": null,
129
+ "cache_mb": 0.011474609375,
130
+ "tokens_equal_reference": true,
131
+ "first_mismatch": null,
132
+ "mismatch_margin": null
133
+ },
134
+ "hf_cache": {
135
+ "prefill_s": 0.005777425000019321,
136
+ "decode_s": 0.03093212199996742,
137
+ "total_s": 0.03670954699998674,
138
+ "tokens_per_s": 435.8539210523567,
139
+ "decode_tokens_per_s": 484.932782820907,
140
+ "peak_mem_mb": null,
141
+ "cache_mb": null,
142
+ "tokens_equal_reference": true,
143
+ "first_mismatch": null,
144
+ "mismatch_margin": null
145
+ }
146
+ }
147
+ },
148
+ {
149
+ "input_tokens": 64,
150
+ "output_tokens": 8,
151
+ "modes": {
152
+ "hf_nocache": {
153
+ "prefill_s": 0.022042528000042694,
154
+ "decode_s": 0.17682645099989713,
155
+ "total_s": 0.19886897899993983,
156
+ "tokens_per_s": 40.22749068371503,
157
+ "decode_tokens_per_s": 39.586837604991985,
158
+ "peak_mem_mb": null,
159
+ "cache_mb": null,
160
+ "tokens_equal_reference": true,
161
+ "first_mismatch": null,
162
+ "mismatch_margin": null
163
+ },
164
+ "explicit_nocache": {
165
+ "prefill_s": 0.02301887299995542,
166
+ "decode_s": 0.18032055200001196,
167
+ "total_s": 0.20333942499996738,
168
+ "tokens_per_s": 39.34308361500129,
169
+ "decode_tokens_per_s": 38.81975694040431,
170
+ "peak_mem_mb": null,
171
+ "cache_mb": null,
172
+ "tokens_equal_reference": true,
173
+ "first_mismatch": null,
174
+ "mismatch_margin": null
175
+ },
176
+ "explicit_cache": {
177
+ "prefill_s": 0.021187446999988424,
178
+ "decode_s": 0.017618621999986317,
179
+ "total_s": 0.03880606899997474,
180
+ "tokens_per_s": 206.15332101803992,
181
+ "decode_tokens_per_s": 397.3068949436248,
182
+ "peak_mem_mb": null,
183
+ "cache_mb": 0.017333984375,
184
+ "tokens_equal_reference": true,
185
+ "first_mismatch": null,
186
+ "mismatch_margin": null
187
+ },
188
+ "explicit_cache_refattn": {
189
+ "prefill_s": 0.021761546999982784,
190
+ "decode_s": 0.01979657499998666,
191
+ "total_s": 0.041558121999969444,
192
+ "tokens_per_s": 192.50148021621098,
193
+ "decode_tokens_per_s": 353.5965185899438,
194
+ "peak_mem_mb": null,
195
+ "cache_mb": 0.017333984375,
196
+ "tokens_equal_reference": true,
197
+ "first_mismatch": null,
198
+ "mismatch_margin": null
199
+ },
200
+ "hf_cache": {
201
+ "prefill_s": 0.02218399900004897,
202
+ "decode_s": 0.02140362499994808,
203
+ "total_s": 0.04358762399999705,
204
+ "tokens_per_s": 183.53833647827514,
205
+ "decode_tokens_per_s": 327.0474043540279,
206
+ "peak_mem_mb": null,
207
+ "cache_mb": null,
208
+ "tokens_equal_reference": true,
209
+ "first_mismatch": null,
210
+ "mismatch_margin": null
211
+ }
212
+ }
213
+ },
214
+ {
215
+ "input_tokens": 64,
216
+ "output_tokens": 16,
217
+ "modes": {
218
+ "hf_nocache": {
219
+ "prefill_s": 0.02384031100007178,
220
+ "decode_s": 0.41284213199992337,
221
+ "total_s": 0.43668244299999515,
222
+ "tokens_per_s": 36.63989761090573,
223
+ "decode_tokens_per_s": 36.333500961580114,
224
+ "peak_mem_mb": null,
225
+ "cache_mb": null,
226
+ "tokens_equal_reference": true,
227
+ "first_mismatch": null,
228
+ "mismatch_margin": null
229
+ },
230
+ "explicit_nocache": {
231
+ "prefill_s": 0.023022617000037826,
232
+ "decode_s": 0.41483446099994126,
233
+ "total_s": 0.4378570779999791,
234
+ "tokens_per_s": 36.5416041076325,
235
+ "decode_tokens_per_s": 36.15900174696944,
236
+ "peak_mem_mb": null,
237
+ "cache_mb": null,
238
+ "tokens_equal_reference": true,
239
+ "first_mismatch": null,
240
+ "mismatch_margin": null
241
+ },
242
+ "explicit_cache": {
243
+ "prefill_s": 0.02272177500003636,
244
+ "decode_s": 0.03686474999994971,
245
+ "total_s": 0.05958652499998607,
246
+ "tokens_per_s": 268.5170850289347,
247
+ "decode_tokens_per_s": 406.8927634127578,
248
+ "peak_mem_mb": null,
249
+ "cache_mb": 0.019287109375,
250
+ "tokens_equal_reference": true,
251
+ "first_mismatch": null,
252
+ "mismatch_margin": null
253
+ },
254
+ "explicit_cache_refattn": {
255
+ "prefill_s": 0.021946311000078822,
256
+ "decode_s": 0.03566101100000196,
257
+ "total_s": 0.057607322000080785,
258
+ "tokens_per_s": 277.74247169444124,
259
+ "decode_tokens_per_s": 420.6274465970461,
260
+ "peak_mem_mb": null,
261
+ "cache_mb": 0.019287109375,
262
+ "tokens_equal_reference": true,
263
+ "first_mismatch": null,
264
+ "mismatch_margin": null
265
+ },
266
+ "hf_cache": {
267
+ "prefill_s": 0.022241731999997683,
268
+ "decode_s": 0.039285696000092685,
269
+ "total_s": 0.06152742800009037,
270
+ "tokens_per_s": 260.04662505925813,
271
+ "decode_tokens_per_s": 381.818359536372,
272
+ "peak_mem_mb": null,
273
+ "cache_mb": null,
274
+ "tokens_equal_reference": true,
275
+ "first_mismatch": null,
276
+ "mismatch_margin": null
277
+ }
278
+ }
279
+ }
280
+ ]
281
+ }
bench_speculative.json ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "env": {
3
+ "python": "3.13.16",
4
+ "torch": "2.11.0+cu130",
5
+ "transformers": "5.22.2",
6
+ "cuda": true,
7
+ "gpu": "Tesla T4",
8
+ "gpu_mem_gb": 14.6
9
+ },
10
+ "target": "Qwen/Qwen2.5-1.5B-Instruct",
11
+ "target_adapter": "/kaggle/working/trialscreen/checkpoints/qwen2.5-1.5b-trialscreen-lora/best_adapter",
12
+ "draft": "Qwen/Qwen2.5-0.5B-Instruct",
13
+ "draft_adapter": "none",
14
+ "vocab_equal": true,
15
+ "dtype": "torch.float16",
16
+ "workloads": {
17
+ "screening": {
18
+ "n_prompts": 20,
19
+ "greedy": {
20
+ "total_s": 9.580427507999957,
21
+ "new_tokens": 277,
22
+ "peak_mem_mb": 4079.42578125,
23
+ "tokens_per_s": 28.91311476118329
24
+ },
25
+ "speculative": {
26
+ "2": {
27
+ "equal": 20,
28
+ "mismatches": [],
29
+ "drafted": 213,
30
+ "accepted": 168,
31
+ "rounds": 108,
32
+ "total_s": 11.221827956000197,
33
+ "new_tokens": 277,
34
+ "peak_mem_mb": 4079.42578125,
35
+ "target_forwards": 128,
36
+ "draft_forwards": 233,
37
+ "acceptance_rate": 0.7887323943661971,
38
+ "tokens_per_round": 2.564814814814815,
39
+ "tokens_per_s": 24.684035532008927,
40
+ "speedup_vs_greedy": 0.8537314549433455,
41
+ "token_equal_rate": 1.0
42
+ },
43
+ "4": {
44
+ "equal": 20,
45
+ "mismatches": [],
46
+ "drafted": 294,
47
+ "accepted": 194,
48
+ "rounds": 83,
49
+ "total_s": 12.488911663996078,
50
+ "new_tokens": 277,
51
+ "peak_mem_mb": 4079.42578125,
52
+ "target_forwards": 103,
53
+ "draft_forwards": 314,
54
+ "acceptance_rate": 0.6598639455782312,
55
+ "tokens_per_round": 3.3373493975903616,
56
+ "tokens_per_s": 22.179674854979982,
57
+ "speedup_vs_greedy": 0.7671146826683941,
58
+ "token_equal_rate": 1.0
59
+ },
60
+ "6": {
61
+ "equal": 20,
62
+ "mismatches": [],
63
+ "drafted": 312,
64
+ "accepted": 210,
65
+ "rounds": 64,
66
+ "total_s": 12.542053050000504,
67
+ "new_tokens": 277,
68
+ "peak_mem_mb": 4079.42578125,
69
+ "target_forwards": 84,
70
+ "draft_forwards": 332,
71
+ "acceptance_rate": 0.6730769230769231,
72
+ "tokens_per_round": 4.328125,
73
+ "tokens_per_s": 22.085698321933734,
74
+ "speedup_vs_greedy": 0.7638643745012362,
75
+ "token_equal_rate": 1.0
76
+ }
77
+ },
78
+ "hf_assisted_reference_equal_first_prompt": true
79
+ },
80
+ "summary": {
81
+ "n_prompts": 2,
82
+ "greedy": {
83
+ "total_s": 8.67052252600024,
84
+ "new_tokens": 256,
85
+ "peak_mem_mb": 4092.28759765625,
86
+ "tokens_per_s": 29.525325519002394
87
+ },
88
+ "speculative": {
89
+ "2": {
90
+ "equal": 2,
91
+ "mismatches": [],
92
+ "drafted": 218,
93
+ "accepted": 146,
94
+ "rounds": 109,
95
+ "total_s": 10.110633794000023,
96
+ "new_tokens": 256,
97
+ "peak_mem_mb": 4092.28759765625,
98
+ "target_forwards": 111,
99
+ "draft_forwards": 220,
100
+ "acceptance_rate": 0.6697247706422018,
101
+ "tokens_per_round": 2.3486238532110093,
102
+ "tokens_per_s": 25.31987659882595,
103
+ "speedup_vs_greedy": 0.8575646890846358,
104
+ "token_equal_rate": 1.0
105
+ },
106
+ "4": {
107
+ "equal": 1,
108
+ "mismatches": [
109
+ {
110
+ "position": 52
111
+ }
112
+ ],
113
+ "drafted": 337,
114
+ "accepted": 169,
115
+ "rounds": 85,
116
+ "total_s": 12.693173349999597,
117
+ "new_tokens": 256,
118
+ "peak_mem_mb": 4092.28759765625,
119
+ "target_forwards": 87,
120
+ "draft_forwards": 339,
121
+ "acceptance_rate": 0.5014836795252225,
122
+ "tokens_per_round": 3.011764705882353,
123
+ "tokens_per_s": 20.168321422948825,
124
+ "speedup_vs_greedy": 0.6830854890987931,
125
+ "token_equal_rate": 0.5
126
+ },
127
+ "6": {
128
+ "equal": 2,
129
+ "mismatches": [],
130
+ "drafted": 411,
131
+ "accepted": 185,
132
+ "rounds": 70,
133
+ "total_s": 14.188820639999904,
134
+ "new_tokens": 256,
135
+ "peak_mem_mb": 4092.28759765625,
136
+ "target_forwards": 72,
137
+ "draft_forwards": 413,
138
+ "acceptance_rate": 0.45012165450121655,
139
+ "tokens_per_round": 3.657142857142857,
140
+ "tokens_per_s": 18.042373393480414,
141
+ "speedup_vs_greedy": 0.6110812692604661,
142
+ "token_equal_rate": 1.0
143
+ }
144
+ },
145
+ "hf_assisted_reference_equal_first_prompt": false
146
+ }
147
+ }
148
+ }
bench_speculative_tiny_cpu_quick.json ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "env": {
3
+ "python": "3.12.3",
4
+ "torch": "2.15.0+cpu",
5
+ "transformers": "5.22.2",
6
+ "cuda": false
7
+ },
8
+ "target": "/tmp/tiny-qwen",
9
+ "target_adapter": null,
10
+ "draft": "/tmp/tiny-draft",
11
+ "draft_adapter": "none",
12
+ "vocab_equal": true,
13
+ "dtype": "torch.float32",
14
+ "workloads": {
15
+ "screening": {
16
+ "n_prompts": 3,
17
+ "greedy": {
18
+ "total_s": 0.6003616039999997,
19
+ "new_tokens": 144,
20
+ "peak_mem_mb": null,
21
+ "tokens_per_s": 239.85544551913094
22
+ },
23
+ "speculative": {
24
+ "2": {
25
+ "equal": 3,
26
+ "mismatches": [],
27
+ "drafted": 279,
28
+ "accepted": 0,
29
+ "rounds": 141,
30
+ "total_s": 1.4528351579999708,
31
+ "new_tokens": 144,
32
+ "peak_mem_mb": 0,
33
+ "target_forwards": 144,
34
+ "draft_forwards": 282,
35
+ "acceptance_rate": 0.0,
36
+ "tokens_per_round": 1.0212765957446808,
37
+ "tokens_per_s": 99.11654409453857,
38
+ "speedup_vs_greedy": 0.4132344958023185,
39
+ "token_equal_rate": 1.0
40
+ },
41
+ "4": {
42
+ "equal": 3,
43
+ "mismatches": [],
44
+ "drafted": 546,
45
+ "accepted": 0,
46
+ "rounds": 141,
47
+ "total_s": 2.028350060999969,
48
+ "new_tokens": 144,
49
+ "peak_mem_mb": 0,
50
+ "target_forwards": 144,
51
+ "draft_forwards": 549,
52
+ "acceptance_rate": 0.0,
53
+ "tokens_per_round": 1.0212765957446808,
54
+ "tokens_per_s": 70.9936626663982,
55
+ "speedup_vs_greedy": 0.2959852027238452,
56
+ "token_equal_rate": 1.0
57
+ }
58
+ },
59
+ "hf_assisted_reference_equal_first_prompt": true
60
+ },
61
+ "summary": {
62
+ "n_prompts": 1,
63
+ "greedy": {
64
+ "total_s": 0.07453514999997424,
65
+ "new_tokens": 32,
66
+ "peak_mem_mb": null,
67
+ "tokens_per_s": 429.3276393756645
68
+ },
69
+ "speculative": {
70
+ "2": {
71
+ "equal": 1,
72
+ "mismatches": [],
73
+ "drafted": 61,
74
+ "accepted": 0,
75
+ "rounds": 31,
76
+ "total_s": 0.20508030099995267,
77
+ "new_tokens": 32,
78
+ "peak_mem_mb": 0,
79
+ "target_forwards": 32,
80
+ "draft_forwards": 62,
81
+ "acceptance_rate": 0.0,
82
+ "tokens_per_round": 1.032258064516129,
83
+ "tokens_per_s": 156.0364395993713,
84
+ "speedup_vs_greedy": 0.3634437322187831,
85
+ "token_equal_rate": 1.0
86
+ },
87
+ "4": {
88
+ "equal": 1,
89
+ "mismatches": [],
90
+ "drafted": 118,
91
+ "accepted": 0,
92
+ "rounds": 31,
93
+ "total_s": 0.302032911000083,
94
+ "new_tokens": 32,
95
+ "peak_mem_mb": 0,
96
+ "target_forwards": 32,
97
+ "draft_forwards": 119,
98
+ "acceptance_rate": 0.0,
99
+ "tokens_per_round": 1.032258064516129,
100
+ "tokens_per_s": 105.94871894603303,
101
+ "speedup_vs_greedy": 0.24677823934211512,
102
+ "token_equal_rate": 1.0
103
+ }
104
+ },
105
+ "hf_assisted_reference_equal_first_prompt": true
106
+ }
107
+ }
108
+ }
criteria.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parse a free-text eligibility-criteria block into (type, text) pairs."""
2
+ from __future__ import annotations
3
+ import re
4
+
5
+ _HEAD = re.compile(r"^\s*(inclusion|exclusion)(\s+criteria)?\s*:?\s*$", re.I)
6
+ _INLINE = re.compile(r"^\s*(inc|inclusion|exc|exclusion)\s*[:\-]\s*(.+)$", re.I)
7
+ _BULLET = re.compile(r"^\s*(?:[-*\u2022]|\d+[.)])\s*")
8
+
9
+
10
+ def parse_criteria(block: str):
11
+ """Accepts either section headers ('Inclusion criteria:' / 'Exclusion criteria:') followed by
12
+ one criterion per line (bullets or numbers optional), or per-line prefixes 'I: ...' / 'E: ...'.
13
+ Returns (criteria, problems)."""
14
+ out, problems, section = [], [], None
15
+ for n, raw in enumerate(block.replace("\r", "").split("\n"), 1):
16
+ line = raw.strip()
17
+ if not line:
18
+ continue
19
+ m = _HEAD.match(line)
20
+ if m:
21
+ section = m.group(1).lower(); continue
22
+ m = _INLINE.match(line)
23
+ if m and not _HEAD.match(line):
24
+ t = "inclusion" if m.group(1).lower().startswith("inc") else "exclusion"
25
+ out.append((t, _BULLET.sub("", m.group(2)).strip())); continue
26
+ m = re.match(r"^\s*([IE])\s*:\s*(.+)$", line)
27
+ if m:
28
+ out.append(("inclusion" if m.group(1) == "I" else "exclusion", m.group(2).strip())); continue
29
+ text = _BULLET.sub("", line).strip()
30
+ if section is None:
31
+ problems.append(f"line {n} has no section: add 'Inclusion criteria:' or 'Exclusion criteria:' above it")
32
+ continue
33
+ if len(text) < 3:
34
+ problems.append(f"line {n} is too short to be a criterion"); continue
35
+ out.append((section, text))
36
+ return out, problems
data.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dataset loading, the prescribed patient-grouped split, sentence parsing and prompts.
2
+
3
+ Only these columns are ever used as model input: note, criterion_type, criterion_text.
4
+ Targets: expert_eligibility, expert_sentences.
5
+ Columns produced by GPT-4 (gpt4_explanation, gpt4_sentences, gpt4_eligibility,
6
+ explanation_correctness) are dropped immediately after loading so they cannot leak.
7
+ """
8
+ from __future__ import annotations
9
+ import json, re, hashlib
10
+ from dataclasses import dataclass, asdict
11
+ from pathlib import Path
12
+ import numpy as np
13
+ import pandas as pd
14
+
15
+ from .labels import labels_for
16
+
17
+ DATASET_ID = "ncbi/TrialGPT-Criterion-Annotations"
18
+ LEAKY_COLUMNS = ["gpt4_explanation", "gpt4_sentences", "gpt4_eligibility", "explanation_correctness"]
19
+ SEED = 42
20
+ N_TRAIN, N_VAL, N_TEST = 37, 8, 8
21
+ SENT_RE = re.compile(r"^\s*(\d+)\.\s+(.*)$")
22
+
23
+
24
+ def load_raw(cache_dir: str | Path = "data/raw") -> pd.DataFrame:
25
+ """Download the single parquet file of the dataset (public domain) and load it."""
26
+ from huggingface_hub import hf_hub_download
27
+ p = hf_hub_download(DATASET_ID, "data/train-00000-of-00001.parquet",
28
+ repo_type="dataset", local_dir=str(cache_dir))
29
+ return pd.read_parquet(p)
30
+
31
+
32
+ def drop_leaky(df: pd.DataFrame) -> pd.DataFrame:
33
+ return df.drop(columns=[c for c in LEAKY_COLUMNS if c in df.columns])
34
+
35
+
36
+ def make_split(df: pd.DataFrame) -> dict[str, list[str]]:
37
+ """Prescribed split: sort unique patient IDs, shuffle with default_rng(42),
38
+ first 37 train, next 8 validation, remaining 8 test."""
39
+ ids = np.array(sorted(df["patient_id"].unique()))
40
+ if len(ids) != N_TRAIN + N_VAL + N_TEST:
41
+ raise ValueError(f"expected 53 patients, found {len(ids)}")
42
+ rng = np.random.default_rng(SEED)
43
+ rng.shuffle(ids)
44
+ return {"train": ids[:N_TRAIN].tolist(),
45
+ "validation": ids[N_TRAIN:N_TRAIN + N_VAL].tolist(),
46
+ "test": ids[N_TRAIN + N_VAL:].tolist()}
47
+
48
+
49
+ def check_no_leakage(split: dict[str, list[str]], df: pd.DataFrame) -> None:
50
+ s = {k: set(v) for k, v in split.items()}
51
+ assert not (s["train"] & s["validation"]), "train/validation patient overlap"
52
+ assert not (s["train"] & s["test"]), "train/test patient overlap"
53
+ assert not (s["validation"] & s["test"]), "validation/test patient overlap"
54
+ assert set().union(*s.values()) == set(df["patient_id"]), "split does not cover all patients"
55
+ for col in LEAKY_COLUMNS:
56
+ assert col not in df.columns, f"leaky column {col} still present"
57
+
58
+
59
+ def split_sentences(note: str) -> list[tuple[int, str]]:
60
+ """Return [(sentence_id, text)]. Dataset notes are already numbered '0. ...'.
61
+ Unnumbered free text (from the app) is split into sentences and numbered from 0."""
62
+ lines = [l for l in note.replace("\r", "").split("\n") if l.strip()]
63
+ parsed = [SENT_RE.match(l) for l in lines]
64
+ if lines and all(parsed):
65
+ out = [(int(m.group(1)), m.group(2).strip()) for m in parsed]
66
+ if [i for i, _ in out] == list(range(len(out))):
67
+ return out
68
+ text = " ".join(l.strip() for l in lines)
69
+ # transparent splitter: break after . ! ? when followed by space and a capital/digit
70
+ parts = re.split(r"(?<=[.!?])\s+(?=[A-Z0-9\"(])", text)
71
+ parts = [p.strip() for p in parts if p.strip()]
72
+ return list(enumerate(parts))
73
+
74
+
75
+ def numbered_note(sentences: list[tuple[int, str]]) -> str:
76
+ return "\n".join(f"{i}. {s}" for i, s in sentences)
77
+
78
+
79
+ SYSTEM_PROMPT = (
80
+ "You are a clinical-trial eligibility screening assistant used for research. "
81
+ "Judge one eligibility criterion against one patient note. Use only facts stated in the note. "
82
+ "Absence of a fact is not evidence for or against eligibility: if the note does not say enough, "
83
+ "answer 'not enough information'. Answer with one JSON object and nothing else."
84
+ )
85
+
86
+
87
+ def build_user_prompt(note_numbered: str, criterion_type: str, criterion_text: str) -> str:
88
+ labels = labels_for(criterion_type)
89
+ return (
90
+ f"Patient note (each sentence has an ID):\n{note_numbered}\n\n"
91
+ f"Criterion type: {criterion_type.lower()}\n"
92
+ f"Criterion: {criterion_text.strip()}\n\n"
93
+ f"Allowed labels: {', '.join(labels)}\n"
94
+ 'Return JSON: {"evidence": [sentence IDs that support the decision], "label": "<one allowed label>"}'
95
+ )
96
+
97
+
98
+ def build_messages(note_numbered: str, criterion_type: str, criterion_text: str):
99
+ return [{"role": "system", "content": SYSTEM_PROMPT},
100
+ {"role": "user", "content": build_user_prompt(note_numbered, criterion_type, criterion_text)}]
101
+
102
+
103
+ def target_json(label: str, evidence: list[int]) -> str:
104
+ # evidence first, label second: the model commits to cited sentences before the decision
105
+ return json.dumps({"evidence": sorted(set(int(i) for i in evidence)), "label": label})
106
+
107
+
108
+ @dataclass
109
+ class Record:
110
+ annotation_id: int
111
+ patient_id: str
112
+ trial_id: str
113
+ criterion_type: str
114
+ criterion_text: str
115
+ note: str # numbered note
116
+ n_sentences: int
117
+ label: str # expert_eligibility
118
+ evidence: list # expert_sentences
119
+
120
+ def to_dict(self):
121
+ return asdict(self)
122
+
123
+
124
+ def invalid_annotations(df: pd.DataFrame) -> list[int]:
125
+ """Annotations that cannot form a valid input (missing/empty criterion text).
126
+ In the released dataset this is exactly one row: annotation 883 (train patient sigir-201519,
127
+ exclusion, expert label 'not excluded', no evidence)."""
128
+ bad = df["criterion_text"].map(lambda x: not isinstance(x, str) or not x.strip())
129
+ return df.loc[bad, "annotation_id"].astype(int).tolist()
130
+
131
+
132
+ def to_records(df: pd.DataFrame) -> list[Record]:
133
+ """Skips annotations without criterion text (see invalid_annotations); callers record them."""
134
+ recs = []
135
+ bad = set(invalid_annotations(df))
136
+ for r in df.itertuples(index=False):
137
+ if int(r.annotation_id) in bad:
138
+ continue
139
+ sents = split_sentences(r.note)
140
+ recs.append(Record(int(r.annotation_id), r.patient_id, r.trial_id, r.criterion_type.lower(),
141
+ r.criterion_text, numbered_note(sents), len(sents),
142
+ r.expert_eligibility, json.loads(r.expert_sentences)))
143
+ return recs
144
+
145
+
146
+ def save_jsonl(recs, path):
147
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
148
+ with open(path, "w") as f:
149
+ for r in recs:
150
+ f.write(json.dumps(r.to_dict() if hasattr(r, "to_dict") else r) + "\n")
151
+
152
+
153
+ def load_jsonl(path) -> list[Record]:
154
+ with open(path) as f:
155
+ return [Record(**json.loads(l)) for l in f if l.strip()]
156
+
157
+
158
+ def file_sha256(path) -> str:
159
+ h = hashlib.sha256()
160
+ with open(path, "rb") as f:
161
+ h.update(f.read())
162
+ return h.hexdigest()
decoding.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Task 3: explicit KV-cached autoregressive decoding.
2
+
3
+ Two decoders share one interface (forward(new_tokens) -> logits for those tokens,
4
+ cache_len, crop(n), reset()):
5
+
6
+ * ExplicitQwen2Decoder: our own forward pass for the Qwen2 architecture (RMSNorm, RoPE,
7
+ grouped-query attention, SwiGLU MLP) that reads the weights of a loaded Hugging Face
8
+ model and keeps its OWN pre-allocated key/value cache. Positional handling, causal
9
+ masking and cache growth are written out explicitly here; attention can use the
10
+ reference, tiled online-softmax (Task 4) or PyTorch SDPA backend.
11
+ * HFCacheDecoder: drives the Hugging Face model forward pass with an explicit
12
+ DynamicCache, passing position ids / cache positions ourselves. Used as an
13
+ independent cross-check and as the fast path for bulk evaluation.
14
+
15
+ greedy_nocache() is the reference path without cache reuse: every step recomputes the
16
+ whole sequence from scratch. greedy_cached() prefills once and then feeds one token per step.
17
+ """
18
+ from __future__ import annotations
19
+ import time
20
+ from dataclasses import dataclass, field
21
+ import torch
22
+ import torch.nn.functional as F
23
+ from .attention import BACKENDS
24
+
25
+
26
+ # ----------------------------------------------------------------------------- utils
27
+ def sync(device):
28
+ if torch.cuda.is_available() and str(device).startswith("cuda"):
29
+ torch.cuda.synchronize()
30
+
31
+
32
+ def reset_peak(device):
33
+ if torch.cuda.is_available() and str(device).startswith("cuda"):
34
+ torch.cuda.reset_peak_memory_stats()
35
+
36
+
37
+ def peak_mem_mb(device):
38
+ if torch.cuda.is_available() and str(device).startswith("cuda"):
39
+ return torch.cuda.max_memory_allocated() / 2**20
40
+ return None
41
+
42
+
43
+ # ----------------------------------------------------------------------------- explicit cache
44
+ class ExplicitKVCache:
45
+ """Pre-allocated per-layer K/V buffers of shape [B, n_kv_heads, max_len, head_dim].
46
+
47
+ `length` is the number of valid positions. Appending writes new keys/values at
48
+ [length, length+T) and returns a view over [0, length+T). Cropping (needed when
49
+ speculative drafts are rejected) only moves `length` back: stale entries beyond it
50
+ are simply overwritten later, so no memory is freed or copied.
51
+ Cache size = 2 * layers * kv_heads * head_dim * max_len * bytes_per_element.
52
+ """
53
+
54
+ def __init__(self, n_layers, batch, n_kv, max_len, head_dim, dtype, device):
55
+ self.k = [torch.zeros(batch, n_kv, max_len, head_dim, dtype=dtype, device=device) for _ in range(n_layers)]
56
+ self.v = [torch.zeros(batch, n_kv, max_len, head_dim, dtype=dtype, device=device) for _ in range(n_layers)]
57
+ self.length = 0
58
+ self.max_len = max_len
59
+
60
+ def update(self, layer, k_new, v_new, start):
61
+ T = k_new.shape[2]
62
+ if start + T > self.max_len:
63
+ raise RuntimeError(f"KV cache overflow: need {start + T} > max_len {self.max_len}")
64
+ self.k[layer][:, :, start:start + T] = k_new
65
+ self.v[layer][:, :, start:start + T] = v_new
66
+ return self.k[layer][:, :, :start + T], self.v[layer][:, :, :start + T]
67
+
68
+ def crop(self, n):
69
+ self.length = min(self.length, n)
70
+
71
+ def nbytes_used(self):
72
+ per_pos = sum(t[:, :, :1].numel() * t.element_size() for t in self.k + self.v)
73
+ return per_pos * self.length
74
+
75
+
76
+ def rotate_half(x):
77
+ x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
78
+ return torch.cat((-x2, x1), dim=-1)
79
+
80
+
81
+ class ExplicitQwen2Decoder:
82
+ """Hand-written Qwen2 forward pass with an explicit KV cache (batch size 1)."""
83
+
84
+ def __init__(self, hf_model, attn_backend="reference", max_len=2048):
85
+ cfg = hf_model.config
86
+ self.cfg = cfg
87
+ self.m = hf_model.model if hasattr(hf_model, "model") else hf_model
88
+ self.lm_head = hf_model.lm_head
89
+ self.n_layers = cfg.num_hidden_layers
90
+ self.n_heads = cfg.num_attention_heads
91
+ self.n_kv = cfg.num_key_value_heads
92
+ self.head_dim = getattr(cfg, "head_dim", None) or cfg.hidden_size // cfg.num_attention_heads
93
+ self.eps = cfg.rms_norm_eps
94
+ theta = getattr(cfg, "rope_theta", None)
95
+ if theta is None: # newer transformers keep it in rope_parameters
96
+ theta = (getattr(cfg, "rope_parameters", None) or {}).get("rope_theta", 10000.0)
97
+ self.theta = float(theta)
98
+ self.attn = BACKENDS[attn_backend]
99
+ self.attn_backend = attn_backend
100
+ self.device = self.lm_head.weight.device
101
+ self.dtype = self.lm_head.weight.dtype
102
+ self.max_len = max_len
103
+ # RoPE inverse frequencies: theta^(-2i/d), i = 0..d/2-1
104
+ self.inv_freq = 1.0 / (self.theta ** (torch.arange(0, self.head_dim, 2, device=self.device,
105
+ dtype=torch.float32) / self.head_dim))
106
+ self.reset()
107
+
108
+ # -- interface ------------------------------------------------------------
109
+ def reset(self):
110
+ self.cache = ExplicitKVCache(self.n_layers, 1, self.n_kv, self.max_len, self.head_dim,
111
+ self.dtype, self.device)
112
+
113
+ @property
114
+ def cache_len(self):
115
+ return self.cache.length
116
+
117
+ def crop(self, n):
118
+ self.cache.crop(n)
119
+
120
+ @torch.no_grad()
121
+ def forward(self, ids: torch.Tensor, use_cache: bool = True, logits_to_keep: int = 0):
122
+ """ids [1, T] are the NEW tokens. Their absolute positions are
123
+ cache_len .. cache_len+T-1. Returns logits [1, T, vocab] (float32), or only the last
124
+ `logits_to_keep` positions when it is > 0 (greedy decoding needs just the last one; the
125
+ full [T, 151936] float32 logits tensor would cost ~0.6 MB per position).
126
+ use_cache=False runs on a temporary empty cache (no reuse)."""
127
+ if not use_cache:
128
+ saved = self.cache
129
+ self.reset()
130
+ start = self.cache.length
131
+ T = ids.shape[1]
132
+ pos = torch.arange(start, start + T, device=self.device, dtype=torch.float32)
133
+ freqs = torch.outer(pos, self.inv_freq) # [T, d/2]
134
+ emb = torch.cat((freqs, freqs), dim=-1) # [T, d]
135
+ cos, sin = emb.cos().to(self.dtype)[None, None], emb.sin().to(self.dtype)[None, None]
136
+
137
+ h = self.m.embed_tokens(ids)
138
+ for i, layer in enumerate(self.m.layers):
139
+ x = self._rmsnorm(h, layer.input_layernorm.weight)
140
+ a = layer.self_attn
141
+ q = a.q_proj(x).view(1, T, self.n_heads, self.head_dim).transpose(1, 2)
142
+ k = a.k_proj(x).view(1, T, self.n_kv, self.head_dim).transpose(1, 2)
143
+ v = a.v_proj(x).view(1, T, self.n_kv, self.head_dim).transpose(1, 2)
144
+ # rotary position embedding applied BEFORE caching: cached keys keep their positions
145
+ q = q * cos + rotate_half(q) * sin
146
+ k = k * cos + rotate_half(k) * sin
147
+ k_all, v_all = self.cache.update(i, k, v, start) # [1, n_kv, start+T, d]
148
+ rep = self.n_heads // self.n_kv # grouped-query attention
149
+ k_all = k_all.repeat_interleave(rep, dim=1)
150
+ v_all = v_all.repeat_interleave(rep, dim=1)
151
+ # causal: query at absolute pos start+t sees keys 0..start+t (bottom-right aligned)
152
+ o = self.attn(q, k_all, v_all, causal=True)
153
+ o = o.transpose(1, 2).reshape(1, T, self.n_heads * self.head_dim)
154
+ h = h + a.o_proj(o)
155
+ x = self._rmsnorm(h, layer.post_attention_layernorm.weight)
156
+ mlp = layer.mlp
157
+ h = h + mlp.down_proj(F.silu(mlp.gate_proj(x)) * mlp.up_proj(x))
158
+ if logits_to_keep:
159
+ h = h[:, -logits_to_keep:]
160
+ h = self._rmsnorm(h, self.m.norm.weight)
161
+ logits = self.lm_head(h).float()
162
+ self.cache.length = start + T
163
+ if not use_cache:
164
+ self.cache = saved
165
+ return logits
166
+
167
+ def _rmsnorm(self, x, w):
168
+ xf = x.float()
169
+ xf = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps)
170
+ return w * xf.to(x.dtype)
171
+
172
+
173
+ class HFCacheDecoder:
174
+ """Same interface on top of the Hugging Face forward pass with an explicit DynamicCache.
175
+ We pass position_ids and cache_position ourselves; the library handles masking inside
176
+ the model given the cache length."""
177
+
178
+ def __init__(self, hf_model):
179
+ self.model = hf_model
180
+ self.device = next(hf_model.parameters()).device
181
+ self.reset()
182
+
183
+ def reset(self):
184
+ from transformers import DynamicCache
185
+ self.cache = DynamicCache()
186
+ self._len = 0
187
+
188
+ @property
189
+ def cache_len(self):
190
+ return self._len
191
+
192
+ def crop(self, n):
193
+ if n < self._len:
194
+ # negative argument = number of tokens to remove; works across transformers versions
195
+ self.cache.crop(n - self._len)
196
+ self._len = n
197
+
198
+ @torch.no_grad()
199
+ def forward(self, ids, use_cache: bool = True, logits_to_keep: int = 0):
200
+ if not use_cache:
201
+ out = self.model(input_ids=ids, use_cache=False, logits_to_keep=logits_to_keep)
202
+ return out.logits.float()
203
+ T = ids.shape[1]
204
+ pos = torch.arange(self._len, self._len + T, device=self.device)
205
+ out = self.model(input_ids=ids, past_key_values=self.cache, use_cache=True,
206
+ position_ids=pos[None], cache_position=pos, logits_to_keep=logits_to_keep)
207
+ self._len += T
208
+ return out.logits.float()
209
+
210
+
211
+ # ----------------------------------------------------------------------------- greedy loops
212
+ @dataclass
213
+ class GenStats:
214
+ tokens: list = field(default_factory=list)
215
+ prompt_len: int = 0
216
+ prefill_s: float = 0.0
217
+ decode_s: float = 0.0
218
+ total_s: float = 0.0
219
+ peak_mem_mb: float | None = None
220
+ cache_mb: float | None = None
221
+
222
+ @property
223
+ def n_new(self):
224
+ return len(self.tokens)
225
+
226
+ @property
227
+ def decode_tok_s(self):
228
+ return (self.n_new - 1) / self.decode_s if self.decode_s > 0 and self.n_new > 1 else None
229
+
230
+ @property
231
+ def tok_s(self):
232
+ return self.n_new / self.total_s if self.total_s > 0 else None
233
+
234
+ def as_dict(self):
235
+ return {"prompt_len": self.prompt_len, "new_tokens": self.n_new, "prefill_s": self.prefill_s,
236
+ "decode_s": self.decode_s, "total_s": self.total_s, "tokens_per_s": self.tok_s,
237
+ "decode_tokens_per_s": self.decode_tok_s, "peak_mem_mb": self.peak_mem_mb,
238
+ "cache_mb": self.cache_mb}
239
+
240
+
241
+ @torch.no_grad()
242
+ def greedy_cached(dec, prompt_ids: torch.Tensor, max_new_tokens: int, eos_ids=()):
243
+ """Prefill the prompt once, then feed exactly one new token per step, reusing the cache."""
244
+ device = prompt_ids.device
245
+ dec.reset(); reset_peak(device)
246
+ st = GenStats(prompt_len=prompt_ids.shape[1])
247
+ sync(device); t0 = time.perf_counter()
248
+ logits = dec.forward(prompt_ids, logits_to_keep=1) # prefill: whole prompt, cache grows to P
249
+ nxt = int(logits[0, -1].argmax())
250
+ sync(device); t1 = time.perf_counter()
251
+ st.tokens.append(nxt)
252
+ while len(st.tokens) < max_new_tokens and nxt not in eos_ids:
253
+ logits = dec.forward(torch.tensor([[nxt]], device=device)) # decode: 1 token, cache +1
254
+ nxt = int(logits[0, -1].argmax())
255
+ st.tokens.append(nxt)
256
+ sync(device); t2 = time.perf_counter()
257
+ st.prefill_s, st.decode_s, st.total_s = t1 - t0, t2 - t1, t2 - t0
258
+ st.peak_mem_mb = peak_mem_mb(device)
259
+ if isinstance(dec, ExplicitQwen2Decoder):
260
+ st.cache_mb = dec.cache.nbytes_used() / 2**20
261
+ return st
262
+
263
+
264
+ @torch.no_grad()
265
+ def greedy_nocache(dec, prompt_ids: torch.Tensor, max_new_tokens: int, eos_ids=()):
266
+ """Reference path: every step reruns the full sequence (prompt + generated) with no reuse.
267
+ 'prefill' here is the first step, so the comparison with the cached path is like for like."""
268
+ device = prompt_ids.device
269
+ dec.reset(); reset_peak(device)
270
+ st = GenStats(prompt_len=prompt_ids.shape[1])
271
+ seq = prompt_ids
272
+ sync(device); t0 = time.perf_counter(); t1 = None
273
+ while True:
274
+ logits = dec.forward(seq, use_cache=False, logits_to_keep=1)
275
+ nxt = int(logits[0, -1].argmax())
276
+ if t1 is None:
277
+ sync(device); t1 = time.perf_counter()
278
+ st.tokens.append(nxt)
279
+ if len(st.tokens) >= max_new_tokens or nxt in eos_ids:
280
+ break
281
+ seq = torch.cat([seq, torch.tensor([[nxt]], device=device)], dim=1)
282
+ sync(device); t2 = time.perf_counter()
283
+ st.prefill_s, st.decode_s, st.total_s = t1 - t0, t2 - t1, t2 - t0
284
+ st.peak_mem_mb = peak_mem_mb(device)
285
+ return st
286
+
287
+
288
+ def first_mismatch(a, b):
289
+ for i, (x, y) in enumerate(zip(a, b)):
290
+ if x != y:
291
+ return i
292
+ return None if len(a) == len(b) else min(len(a), len(b))
error_cases.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Error-analysis worksheet (test split, fine-tuned model)
2
+
3
+ 87 of 206 predictions differ from the expert label or evidence set.
4
+
5
+
6
+ ## over-confident: decided despite missing information (28)
7
+
8
+ - annotation 169 (sigir-201410, NCT02097186, exclusion): criterion: 'Patients with an estimated pre-operative glomerular filtration rate < 30mls/min/1.73m2' | expert: not enough information [] | model: not excluded [] | raw: '{"evidence": [], "label": "not excluded"}'
9
+ - annotation 174 (sigir-201410, NCT02097186, exclusion): criterion: 'Patients with previous axillary surgery' | expert: not enough information [] | model: not excluded [] | raw: '{"evidence": [], "label": "not excluded"}'
10
+ - annotation 193 (sigir-201411, NCT01526382, exclusion): criterion: 'Patients were moribund.' | expert: not enough information [0, 1, 2, 3, 4] | model: not excluded [] | raw: '{"evidence": [], "label": "not excluded"}'
11
+ - annotation 315 (sigir-201417, NCT01745731, exclusion): criterion: 'BMI> 40 kg/m2.' | expert: not enough information [] | model: not excluded [] | raw: '{"evidence": [], "label": "not excluded"}'
12
+
13
+ ## right label, partial evidence (20)
14
+
15
+ - annotation 166 (sigir-201410, NCT02097186, exclusion): criterion: 'Significant upper limb peripheral arterial disease' | expert: not excluded [] | model: not excluded [2] | raw: '{"evidence": [2], "label": "not excluded"}'
16
+ - annotation 189 (sigir-201411, NCT01526382, inclusion): criterion: 'at least 1 of 3 signs of hypoperfusion (urine output < 0.5mL/kg of body weight per hour for 1 hour or more; neurologic dysfunction defined by confusion, psychos' | expert: not enough information [] | model: not enough information [2] | raw: '{"evidence": [2], "label": "not enough information"}'
17
+ - annotation 307 (sigir-201417, NCT01745731, inclusion): criterion: 'Patient selection should be cautious, covering basically 5 types of liver damage which must be submitted prior to liver volumetry: Metastatic Disease subsidiary' | expert: not enough information [3] | model: not enough information [0, 1, 2, 3, 4] | raw: '{"evidence": [0, 1, 2, 3, 4], "label": "not enough information"}'
18
+ - annotation 309 (sigir-201417, NCT01745731, exclusion): criterion: 'Different tumor records current disease or any disease hematologic.' | expert: not excluded [] | model: not excluded [0] | raw: '{"evidence": [0], "label": "not excluded"}'
19
+
20
+ ## missed available evidence (predicted not enough information) (14)
21
+
22
+ - annotation 161 (sigir-201410, NCT02097186, inclusion): criterion: 'Patients undergoing elective carotid endarterectomy' | expert: not included [] | model: not enough information [0, 1, 2] | raw: '{"evidence": [0, 1, 2], "label": "not enough information"}'
23
+ - annotation 162 (sigir-201410, NCT02097186, inclusion): criterion: 'Patients undergoing open abdominal aortic aneurysm repair' | expert: not included [] | model: not enough information [0, 1, 2] | raw: '{"evidence": [0, 1, 2], "label": "not enough information"}'
24
+ - annotation 163 (sigir-201410, NCT02097186, inclusion): criterion: 'Patients undergoing endovascular abdominal aneurysm repair' | expert: not included [] | model: not enough information [0, 1, 2] | raw: '{"evidence": [0, 1, 2], "label": "not enough information"}'
25
+ - annotation 177 (sigir-201410, NCT02264964, inclusion): criterion: 'Maintenance hemodialysis after central vena catheterization.' | expert: not included [] | model: not enough information [] | raw: '{"evidence": [], "label": "not enough information"}'
26
+
27
+ ## right label, wrong evidence (14)
28
+
29
+ - annotation 176 (sigir-201410, NCT02264964, inclusion): criterion: 'No medical history of central vena catheterization.' | expert: included [0] | model: included [] | raw: '{"evidence": [], "label": "included"}'
30
+ - annotation 179 (sigir-201410, NCT02264964, exclusion): criterion: 'Had been performed central venous puncture or catheterization before.' | expert: not excluded [0] | model: not excluded [] | raw: '{"evidence": [], "label": "not excluded"}'
31
+ - annotation 197 (sigir-201411, NCT01723137, exclusion): criterion: 'Decreased level of consciousness' | expert: not excluded [0, 5] | model: not excluded [] | raw: '{"evidence": [], "label": "not excluded"}'
32
+ - annotation 319 (sigir-201417, NCT01745731, exclusion): criterion: 'Difficulty in monitoring.' | expert: not excluded [5] | model: not excluded [] | raw: '{"evidence": [], "label": "not excluded"}'
33
+
34
+ ## unsupported decision (no evidence cited) (9)
35
+
36
+ - annotation 322 (sigir-201417, NCT01745731, exclusion): criterion: 'Pregnant women or women of childbearing age who do not have adequate contraception.' | expert: not excluded [0] | model: not applicable [] | raw: '{"evidence": [], "label": "not applicable"}'
37
+ - annotation 683 (sigir-20158, NCT02562040, exclusion): criterion: 'Previous tonsillectomy, including partial tonsillectomy' | expert: not applicable [] | model: not excluded [] | raw: '{"evidence": [], "label": "not excluded"}'
38
+ - annotation 693 (sigir-20158, NCT00393913, exclusion): criterion: 'Suspected diagnosis of a sleep disorder other than OSA (i.e., periodic leg movements, narcolepsy, insomnia, central sleep apnea, sleep hypoventilation syndrome)' | expert: not applicable [] | model: not excluded [] | raw: '{"evidence": [], "label": "not excluded"}'
39
+ - annotation 697 (sigir-20158, NCT00393913, exclusion): criterion: 'Pregnant' | expert: not applicable [] | model: not excluded [] | raw: '{"evidence": [], "label": "not excluded"}'
40
+
41
+ ## contradictory polarity (1)
42
+
43
+ - annotation 164 (sigir-201410, NCT02097186, inclusion): criterion: 'Patients undergoing surgical lower limb revascularisation (suprainguinal or infrainguinal)' | expert: not included [] | model: included [0, 2] | raw: '{"evidence": [0, 2], "label": "included"}'
44
+
45
+ ## applicability confusion (1)
46
+
47
+ - annotation 767 (sigir-201513, NCT00315042, exclusion): criterion: 'Symptoms that collectively suggest nonstreptococcal T/P (eg, laryngitis, coryza, conjunctivitis, diarrhea, cough)' | expert: not applicable [0] | model: not excluded [0, 1, 2] | raw: '{"evidence": [0, 1, 2], "label": "not excluded"}'
evaluate.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run criterion-level predictions over a split and compute the common metrics."""
2
+ from __future__ import annotations
3
+ import time
4
+ import torch
5
+ from .modeling import predict_one
6
+ from .metrics import evaluate_rows
7
+
8
+
9
+ @torch.no_grad()
10
+ def predict_records(tok, model, recs, mode="hf_cache", max_new_tokens=48, log=print, every=25):
11
+ rows, t0 = [], time.time()
12
+ model.eval()
13
+ for i, r in enumerate(recs):
14
+ out = predict_one(tok, model, r.note, r.criterion_type, r.criterion_text, mode=mode,
15
+ max_new_tokens=max_new_tokens)
16
+ rows.append({"annotation_id": r.annotation_id, "patient_id": r.patient_id, "trial_id": r.trial_id,
17
+ "criterion_type": r.criterion_type, "criterion_text": r.criterion_text,
18
+ "gold_label": r.label, "pred_label": out["label"],
19
+ "gold_evidence": r.evidence, "pred_evidence": out["evidence"],
20
+ "valid_json": out["valid_json"], "raw_output": out["raw_output"],
21
+ "parse_notes": out["parse_notes"], "explanation": out["explanation"],
22
+ "prompt_tokens": out["prompt_tokens"], "latency_s": out["latency_s"]})
23
+ if log and (i + 1) % every == 0:
24
+ log(f" {i + 1}/{len(recs)} done, {time.time() - t0:.0f}s")
25
+ return rows
26
+
27
+
28
+ def evaluate_split(tok, model, recs, **kw):
29
+ rows = predict_records(tok, model, recs, **kw)
30
+ return rows, evaluate_rows(rows)
examples.json ADDED
@@ -0,0 +1,522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "name": "Validation patient sigir-201415 / NCT00180739 (31 criteria)",
4
+ "patient_id": "sigir-201415",
5
+ "trial_id": "NCT00180739",
6
+ "note": "0. A 36-year-old woman presents to the emergency department with 12 weeks of amenorrhea, vaginal spotting that has increased since yesterday, lower abdominal tenderness, nausea and vomiting.\n1. The physical exam reveals overall tender abdomen, 18-week sized uterus, and cervical dilation of 2 cm.\n2. The complete blood count and biochemical profile are normal.\n3. Point of care pregnancy test with cut-off sensitivity of 25 mIU/ml Beta-HCG is negative.\n4. The ultrasound reports enlarged uterus (12 cm x 9 cm x 7 cms) with multiple cystic areas in the interior.\n5. The differential diagnosis includes vesicular mole vs fibroid degeneration.\n6. The patient will provide informed consent, and will comply with the trial protocol without any practical issues.",
7
+ "criteria": "Inclusion criteria:\n- 1. Subject with uterine fibroids, who desire pregnancy within 12 months and has the one of the following criteria: Women 20-40 age. Women age < 46 years old who plan to have egg donation. Women above 38 should test for normal ovarian function as judged by endocrinological evaluation. If the couple has failed to conceive for more that 1 year, the woman should test for normal ovarian function as judged by endocrinological evaluation, and the male must have adequate sperm test. Women undergoing fertility treatment or plan to have sperm donation.\n- 2. Use or non use of non-steroidal treatments for excessive vaginal bleeding such as antifibrinolytic agents (e.g. Tranexamic acid) or non-steroidal anti-inflammatory drugs (e.g. Mefanamic Acid) has been maintained for the three months prior to the planned date of the study procedure and the patient has agreed to maintain this use or non-use through the 6-month follow-up period.\n- 3. Clinically normal PAP smear within timing of National Guidelines in the country of the clinical site.\n- 4. Able and willing to give consent and able to attend all study visits\n- 5. Able to communicate sensations during the MRgFUS procedure\n- 6. Having uterine fibroids that are device accessible (i.e., positioned in the uterus such that they can be accessed without being shielded by bowel or bone).\n- 7. Tumor(s) are clearly visible on non-contrast MRI.\n- 8. Largest fibroid 8 cm in diameter or 12 cm if receiving GnRH\n\nExclusion criteria:\n- 1. Patient is pregnant as confirmed by pregnancy test at time of screening\n- 2. Uterine size >20 weeks as evaluated by US or MR.\n- 3. Patients who are considered high risk pregnancy due to uterine factors (e.g. abnormal uterus, uterine scars, cerclage) except fibroids.\n- 4. Patients with fibroid that is more than 50% sub-mucosal or with hysteroscopically resectable\n- 5. Patients with adenomyosis\n- 6. Patient is on dialysis\n- 7. Hematocrit is < 25\n- 8. Patient has hemolytic anemia\n- 9. Patient has unstable cardiac status including: \u00a7 Unstable angina pectoris on medication\u00a7 Documented myocardial infarction within 6 months of protocol entry\u00a7 Congestive heart failure requiring medication (other than diuretic)\u00a7 Currently taking anti-arrhythmic drugs\u00a7 Severe hypertension (diastolic BP>100 on medication)\u00a7 Presence of cardiac pacemaker\n- 10. Patient has an ASA score of >2\n- 11. Patient has severe cerebrovascular disease (multiple CVA or CVA within 6 months)\n- 12. Patient is on anti-coagulation therapy or has an underlying bleeding disorder\n- 13. Evidence of uterine pathology other than leiomyoma\n- 14. Patient has an active pelvic infection or history of pelvic inflammatory disease\n- 15. Patient has an undiagnosed pelvic mass outside the uterus.\n- 16. Patient weight >110 kg\n- 17. Subject with extensive abdominal scarring in an area of the abdomen directly anterior to the treatment area.\n- 18. Subject with standard contraindications for MR imaging such as non-MRI compatable implanted metallic devices.\n- 19. Known intolerance to the MRI contrast agent (e.g. Gadolinium or Magnevist).\n- 20. Individuals who are not able or willing to tolerate the required prolonged stationary prone position during treatment (approximately 3 hours.)\n- 21. Patient with an intrauterine contraceptive device anywhere in the treatment beam path.\n- 22. Women who are breast feeding.\n- 23. Five or more fibroids, bigger then 3cm diameter, each",
8
+ "gold": [
9
+ {
10
+ "type": "inclusion",
11
+ "criterion": "1. Subject with uterine fibroids, who desire pregnancy within 12 months and has the one of the following criteria: Women 20-40 age. Women age < 46 years old who plan to have egg donation. Women above 38 should test for normal ovarian function as judged by endocrinological evaluation. If the couple has failed to conceive for more that 1 year, the woman should test for normal ovarian function as judged by endocrinological evaluation, and the male must have adequate sperm test. Women undergoing fertility treatment or plan to have sperm donation.",
12
+ "label": "not enough information",
13
+ "evidence": [
14
+ 0,
15
+ 3,
16
+ 5
17
+ ]
18
+ },
19
+ {
20
+ "type": "inclusion",
21
+ "criterion": "2. Use or non use of non-steroidal treatments for excessive vaginal bleeding such as antifibrinolytic agents (e.g. Tranexamic acid) or non-steroidal anti-inflammatory drugs (e.g. Mefanamic Acid) has been maintained for the three months prior to the planned date of the study procedure and the patient has agreed to maintain this use or non-use through the 6-month follow-up period.",
22
+ "label": "not enough information",
23
+ "evidence": []
24
+ },
25
+ {
26
+ "type": "inclusion",
27
+ "criterion": "3. Clinically normal PAP smear within timing of National Guidelines in the country of the clinical site.",
28
+ "label": "not enough information",
29
+ "evidence": []
30
+ },
31
+ {
32
+ "type": "inclusion",
33
+ "criterion": "4. Able and willing to give consent and able to attend all study visits",
34
+ "label": "included",
35
+ "evidence": [
36
+ 6
37
+ ]
38
+ },
39
+ {
40
+ "type": "inclusion",
41
+ "criterion": "5. Able to communicate sensations during the MRgFUS procedure",
42
+ "label": "not enough information",
43
+ "evidence": [
44
+ 6
45
+ ]
46
+ },
47
+ {
48
+ "type": "inclusion",
49
+ "criterion": "6. Having uterine fibroids that are device accessible (i.e., positioned in the uterus such that they can be accessed without being shielded by bowel or bone).",
50
+ "label": "not enough information",
51
+ "evidence": [
52
+ 4
53
+ ]
54
+ },
55
+ {
56
+ "type": "inclusion",
57
+ "criterion": "7. Tumor(s) are clearly visible on non-contrast MRI.",
58
+ "label": "not enough information",
59
+ "evidence": []
60
+ },
61
+ {
62
+ "type": "inclusion",
63
+ "criterion": "8. Largest fibroid 8 cm in diameter or 12 cm if receiving GnRH",
64
+ "label": "not enough information",
65
+ "evidence": [
66
+ 4
67
+ ]
68
+ },
69
+ {
70
+ "type": "exclusion",
71
+ "criterion": "1. Patient is pregnant as confirmed by pregnancy test at time of screening",
72
+ "label": "not excluded",
73
+ "evidence": [
74
+ 3
75
+ ]
76
+ },
77
+ {
78
+ "type": "exclusion",
79
+ "criterion": "2. Uterine size >20 weeks as evaluated by US or MR.",
80
+ "label": "not excluded",
81
+ "evidence": [
82
+ 1
83
+ ]
84
+ },
85
+ {
86
+ "type": "exclusion",
87
+ "criterion": "3. Patients who are considered high risk pregnancy due to uterine factors (e.g. abnormal uterus, uterine scars, cerclage) except fibroids.",
88
+ "label": "not enough information",
89
+ "evidence": [
90
+ 4
91
+ ]
92
+ },
93
+ {
94
+ "type": "exclusion",
95
+ "criterion": "4. Patients with fibroid that is more than 50% sub-mucosal or with hysteroscopically resectable",
96
+ "label": "not enough information",
97
+ "evidence": []
98
+ },
99
+ {
100
+ "type": "exclusion",
101
+ "criterion": "5. Patients with adenomyosis",
102
+ "label": "not enough information",
103
+ "evidence": []
104
+ },
105
+ {
106
+ "type": "exclusion",
107
+ "criterion": "6. Patient is on dialysis",
108
+ "label": "not excluded",
109
+ "evidence": []
110
+ },
111
+ {
112
+ "type": "exclusion",
113
+ "criterion": "7. Hematocrit is < 25",
114
+ "label": "not excluded",
115
+ "evidence": [
116
+ 2
117
+ ]
118
+ },
119
+ {
120
+ "type": "exclusion",
121
+ "criterion": "8. Patient has hemolytic anemia",
122
+ "label": "not excluded",
123
+ "evidence": []
124
+ },
125
+ {
126
+ "type": "exclusion",
127
+ "criterion": "9. Patient has unstable cardiac status including: \u00a7 Unstable angina pectoris on medication\u00a7 Documented myocardial infarction within 6 months of protocol entry\u00a7 Congestive heart failure requiring medication (other than diuretic)\u00a7 Currently taking anti-arrhythmic drugs\u00a7 Severe hypertension (diastolic BP>100 on medication)\u00a7 Presence of cardiac pacemaker",
128
+ "label": "not excluded",
129
+ "evidence": []
130
+ },
131
+ {
132
+ "type": "exclusion",
133
+ "criterion": "10. Patient has an ASA score of >2",
134
+ "label": "not enough information",
135
+ "evidence": []
136
+ },
137
+ {
138
+ "type": "exclusion",
139
+ "criterion": "11. Patient has severe cerebrovascular disease (multiple CVA or CVA within 6 months)",
140
+ "label": "not excluded",
141
+ "evidence": []
142
+ },
143
+ {
144
+ "type": "exclusion",
145
+ "criterion": "12. Patient is on anti-coagulation therapy or has an underlying bleeding disorder",
146
+ "label": "not excluded",
147
+ "evidence": []
148
+ },
149
+ {
150
+ "type": "exclusion",
151
+ "criterion": "13. Evidence of uterine pathology other than leiomyoma",
152
+ "label": "excluded",
153
+ "evidence": [
154
+ 5
155
+ ]
156
+ },
157
+ {
158
+ "type": "exclusion",
159
+ "criterion": "14. Patient has an active pelvic infection or history of pelvic inflammatory disease",
160
+ "label": "not excluded",
161
+ "evidence": []
162
+ },
163
+ {
164
+ "type": "exclusion",
165
+ "criterion": "15. Patient has an undiagnosed pelvic mass outside the uterus.",
166
+ "label": "not excluded",
167
+ "evidence": []
168
+ },
169
+ {
170
+ "type": "exclusion",
171
+ "criterion": "16. Patient weight >110 kg",
172
+ "label": "not enough information",
173
+ "evidence": []
174
+ },
175
+ {
176
+ "type": "exclusion",
177
+ "criterion": "17. Subject with extensive abdominal scarring in an area of the abdomen directly anterior to the treatment area.",
178
+ "label": "not excluded",
179
+ "evidence": []
180
+ },
181
+ {
182
+ "type": "exclusion",
183
+ "criterion": "18. Subject with standard contraindications for MR imaging such as non-MRI compatable implanted metallic devices.",
184
+ "label": "not excluded",
185
+ "evidence": []
186
+ },
187
+ {
188
+ "type": "exclusion",
189
+ "criterion": "19. Known intolerance to the MRI contrast agent (e.g. Gadolinium or Magnevist).",
190
+ "label": "not excluded",
191
+ "evidence": []
192
+ },
193
+ {
194
+ "type": "exclusion",
195
+ "criterion": "20. Individuals who are not able or willing to tolerate the required prolonged stationary prone position during treatment (approximately 3 hours.)",
196
+ "label": "not excluded",
197
+ "evidence": [
198
+ 6
199
+ ]
200
+ },
201
+ {
202
+ "type": "exclusion",
203
+ "criterion": "21. Patient with an intrauterine contraceptive device anywhere in the treatment beam path.",
204
+ "label": "not excluded",
205
+ "evidence": []
206
+ },
207
+ {
208
+ "type": "exclusion",
209
+ "criterion": "22. Women who are breast feeding.",
210
+ "label": "not excluded",
211
+ "evidence": []
212
+ },
213
+ {
214
+ "type": "exclusion",
215
+ "criterion": "23. Five or more fibroids, bigger then 3cm diameter, each",
216
+ "label": "not enough information",
217
+ "evidence": []
218
+ }
219
+ ]
220
+ },
221
+ {
222
+ "name": "Validation patient sigir-20141 / NCT01397994 (21 criteria)",
223
+ "patient_id": "sigir-20141",
224
+ "trial_id": "NCT01397994",
225
+ "note": "0. A 58-year-old African-American woman presents to the ER with episodic pressing/burning anterior chest pain that began two days earlier for the first time in her life.\n1. The pain started while she was walking, radiates to the back, and is accompanied by nausea, diaphoresis and mild dyspnea, but is not increased on inspiration.\n2. The latest episode of pain ended half an hour prior to her arrival.\n3. She is known to have hypertension and obesity.\n4. She denies smoking, diabetes, hypercholesterolemia, or a family history of heart disease.\n5. She currently takes no medications.\n6. Physical examination is normal.\n7. The EKG shows nonspecific changes.\n8. The patient will provide informed consent, and will comply with the trial protocol without any practical issues.",
226
+ "criteria": "Inclusion criteria:\n- Patients of chronic stable angina with abnormal Exercise Myocardial Perfusion Spect Scan with reversible and partially reversible ischemic changes.\n- Male and female\n- Age 25 to 65 years\n- Patient must understand and be willing, able and likely to comply with all study procedures and restrictions and comprehends the diary cards.\n- Patient must be able to give voluntary written informed consent.\n\nExclusion criteria:\n- Hypertension of > 170/100 mm of Hg\n- Valvular heart disease and cardiomyopathy\n- Myocardial infarction in < 6 months\n- Unstable angina\n- Congestive cardiac failure\n- Severe anemia (Hb 7G/dl)\n- Cardiac arrhythmias or II or III degree AV block\n- Significant liver or renal dysfunction\n- IDDM (Type-1 diabetes mellitus)\n- Systolic blood pressure < 100 mm Hg\n- Pregnant and nursing women\n- Known hypersensitivity to nicorandil\n- On calcium channel blockers\n- Patients not eligible for Tc 99m SPECT\n- Patients in whom beta blockers are contraindicated\n- Geographical inaccessibility for treatment or follow-up evaluations",
227
+ "gold": [
228
+ {
229
+ "type": "inclusion",
230
+ "criterion": "Patients of chronic stable angina with abnormal Exercise Myocardial Perfusion Spect Scan with reversible and partially reversible ischemic changes.",
231
+ "label": "not enough information",
232
+ "evidence": [
233
+ 0,
234
+ 1,
235
+ 2
236
+ ]
237
+ },
238
+ {
239
+ "type": "inclusion",
240
+ "criterion": "Male and female",
241
+ "label": "included",
242
+ "evidence": [
243
+ 0
244
+ ]
245
+ },
246
+ {
247
+ "type": "inclusion",
248
+ "criterion": "Age 25 to 65 years",
249
+ "label": "included",
250
+ "evidence": [
251
+ 0
252
+ ]
253
+ },
254
+ {
255
+ "type": "inclusion",
256
+ "criterion": "Patient must understand and be willing, able and likely to comply with all study procedures and restrictions and comprehends the diary cards.",
257
+ "label": "included",
258
+ "evidence": [
259
+ 8
260
+ ]
261
+ },
262
+ {
263
+ "type": "inclusion",
264
+ "criterion": "Patient must be able to give voluntary written informed consent.",
265
+ "label": "included",
266
+ "evidence": [
267
+ 8
268
+ ]
269
+ },
270
+ {
271
+ "type": "exclusion",
272
+ "criterion": "Hypertension of > 170/100 mm of Hg",
273
+ "label": "not excluded",
274
+ "evidence": []
275
+ },
276
+ {
277
+ "type": "exclusion",
278
+ "criterion": "Valvular heart disease and cardiomyopathy",
279
+ "label": "not excluded",
280
+ "evidence": []
281
+ },
282
+ {
283
+ "type": "exclusion",
284
+ "criterion": "Myocardial infarction in < 6 months",
285
+ "label": "not excluded",
286
+ "evidence": []
287
+ },
288
+ {
289
+ "type": "exclusion",
290
+ "criterion": "Unstable angina",
291
+ "label": "not enough information",
292
+ "evidence": [
293
+ 0,
294
+ 1,
295
+ 2
296
+ ]
297
+ },
298
+ {
299
+ "type": "exclusion",
300
+ "criterion": "Congestive cardiac failure",
301
+ "label": "not excluded",
302
+ "evidence": []
303
+ },
304
+ {
305
+ "type": "exclusion",
306
+ "criterion": "Severe anemia (Hb 7G/dl)",
307
+ "label": "not excluded",
308
+ "evidence": []
309
+ },
310
+ {
311
+ "type": "exclusion",
312
+ "criterion": "Cardiac arrhythmias or II or III degree AV block",
313
+ "label": "not excluded",
314
+ "evidence": []
315
+ },
316
+ {
317
+ "type": "exclusion",
318
+ "criterion": "Significant liver or renal dysfunction",
319
+ "label": "not excluded",
320
+ "evidence": []
321
+ },
322
+ {
323
+ "type": "exclusion",
324
+ "criterion": "IDDM (Type-1 diabetes mellitus)",
325
+ "label": "not excluded",
326
+ "evidence": [
327
+ 4
328
+ ]
329
+ },
330
+ {
331
+ "type": "exclusion",
332
+ "criterion": "Systolic blood pressure < 100 mm Hg",
333
+ "label": "not excluded",
334
+ "evidence": [
335
+ 3
336
+ ]
337
+ },
338
+ {
339
+ "type": "exclusion",
340
+ "criterion": "Pregnant and nursing women",
341
+ "label": "not enough information",
342
+ "evidence": []
343
+ },
344
+ {
345
+ "type": "exclusion",
346
+ "criterion": "Known hypersensitivity to nicorandil",
347
+ "label": "not excluded",
348
+ "evidence": []
349
+ },
350
+ {
351
+ "type": "exclusion",
352
+ "criterion": "On calcium channel blockers",
353
+ "label": "not excluded",
354
+ "evidence": [
355
+ 5
356
+ ]
357
+ },
358
+ {
359
+ "type": "exclusion",
360
+ "criterion": "Patients not eligible for Tc 99m SPECT",
361
+ "label": "not enough information",
362
+ "evidence": []
363
+ },
364
+ {
365
+ "type": "exclusion",
366
+ "criterion": "Patients in whom beta blockers are contraindicated",
367
+ "label": "not enough information",
368
+ "evidence": []
369
+ },
370
+ {
371
+ "type": "exclusion",
372
+ "criterion": "Geographical inaccessibility for treatment or follow-up evaluations",
373
+ "label": "not excluded",
374
+ "evidence": [
375
+ 8
376
+ ]
377
+ }
378
+ ]
379
+ },
380
+ {
381
+ "name": "Validation patient sigir-201515 / NCT01550588 (18 criteria)",
382
+ "patient_id": "sigir-201515",
383
+ "trial_id": "NCT01550588",
384
+ "note": "0. Karen is a 72-year-old woman with hypertension and type 2 diabetes, who was hospitalized for cryptogenic stroke two weeks ago.\n1. At the time, computed tomography was negative for brain hemorrhage and she was given thrombolytic therapy with resolution of her symptoms.\n2. Transesophageal echocardiogram and magnetic resonance angiogram of brain and great vessels found no evidence of abnormalities.\n3. She presents currently with a blood pressure of 120/70 mm Hg, normal glucose, and normal sinus rhythm on a 12-lead electrocardiogram.\n4. She reports history of occasional palpitations, shortness of breath and chest pain lasting for a few minutes and then stopping on their own.\n5. The patient will provide informed consent, and will comply with the trial protocol without any practical issues.",
385
+ "criteria": "Inclusion criteria:\n- Subjects who have had a cryptogenic stroke within the previous 3 months, radiologically verified\n- Subjects who have been diagnosed with a high-risk* Patent Foramen Ovale (PFO), echocardiographically verified (*PFO size \u2265 2 mm or atrial septal aneurysm or hypermobility by TEE)\n- Subjects willing to participate in follow-up visits\n- Absence of other potential causes of stroke\n\nExclusion criteria:\n- Any identifiable cause of thromboembolic cause other than PFO\n- Subjects with intracardiac thrombus or tumor, dilated cardiomyopathy, prosthetic heart valve or mitral stenosis, endocarditis\n- Subjects with significant atherosclerosis or dissection of the aorta, collagen vascular disease, arteritis, vasculitis and coagulopathy\n- Subjects who have an acute or recent (within 6 months) myocardial infarction or unstable angina\n- Subjects who have a non-vascular origin of the neurological symptoms after brain imaging (CT scan or MRI)\n- History of intracranial bleeding, confirmed arterio-venous malformation,aneurysm or uncontrolled coagulopathy\n- Pre-existing neurological disorders or intracranial disease, e.g. multiple sclerosis\n- Subjects with left ventricular aneurysm or akinesis\n- Subjects with atrial fibrillation/atrial flutter (chronic or intermittent)\n- Subjects with another source of right to left shunt identified at baseline, including an atrial septal defect and/or fenestrated septum\n- Subjects who could not undergo the TEE examination\n- Subjects with contraindication to aspirin or Clopidogrel therapy\n- Pregnant or desire to become pregnant within the next year\n- Subjects who have a underlying malignancy",
386
+ "gold": [
387
+ {
388
+ "type": "inclusion",
389
+ "criterion": "Subjects who have had a cryptogenic stroke within the previous 3 months, radiologically verified",
390
+ "label": "included",
391
+ "evidence": [
392
+ 0
393
+ ]
394
+ },
395
+ {
396
+ "type": "inclusion",
397
+ "criterion": "Subjects who have been diagnosed with a high-risk* Patent Foramen Ovale (PFO), echocardiographically verified (*PFO size \u2265 2 mm or atrial septal aneurysm or hypermobility by TEE)",
398
+ "label": "not enough information",
399
+ "evidence": []
400
+ },
401
+ {
402
+ "type": "inclusion",
403
+ "criterion": "Subjects willing to participate in follow-up visits",
404
+ "label": "included",
405
+ "evidence": [
406
+ 5
407
+ ]
408
+ },
409
+ {
410
+ "type": "inclusion",
411
+ "criterion": "Absence of other potential causes of stroke",
412
+ "label": "not enough information",
413
+ "evidence": [
414
+ 0
415
+ ]
416
+ },
417
+ {
418
+ "type": "exclusion",
419
+ "criterion": "Any identifiable cause of thromboembolic cause other than PFO",
420
+ "label": "not excluded",
421
+ "evidence": [
422
+ 0
423
+ ]
424
+ },
425
+ {
426
+ "type": "exclusion",
427
+ "criterion": "Subjects with intracardiac thrombus or tumor, dilated cardiomyopathy, prosthetic heart valve or mitral stenosis, endocarditis",
428
+ "label": "not excluded",
429
+ "evidence": []
430
+ },
431
+ {
432
+ "type": "exclusion",
433
+ "criterion": "Subjects with significant atherosclerosis or dissection of the aorta, collagen vascular disease, arteritis, vasculitis and coagulopathy",
434
+ "label": "not excluded",
435
+ "evidence": []
436
+ },
437
+ {
438
+ "type": "exclusion",
439
+ "criterion": "Subjects who have an acute or recent (within 6 months) myocardial infarction or unstable angina",
440
+ "label": "not excluded",
441
+ "evidence": []
442
+ },
443
+ {
444
+ "type": "exclusion",
445
+ "criterion": "Subjects who have a non-vascular origin of the neurological symptoms after brain imaging (CT scan or MRI)",
446
+ "label": "not applicable",
447
+ "evidence": [
448
+ 0
449
+ ]
450
+ },
451
+ {
452
+ "type": "exclusion",
453
+ "criterion": "History of intracranial bleeding, confirmed arterio-venous malformation,aneurysm or uncontrolled coagulopathy",
454
+ "label": "not excluded",
455
+ "evidence": []
456
+ },
457
+ {
458
+ "type": "exclusion",
459
+ "criterion": "Pre-existing neurological disorders or intracranial disease, e.g. multiple sclerosis",
460
+ "label": "not excluded",
461
+ "evidence": []
462
+ },
463
+ {
464
+ "type": "exclusion",
465
+ "criterion": "Subjects with left ventricular aneurysm or akinesis",
466
+ "label": "not excluded",
467
+ "evidence": []
468
+ },
469
+ {
470
+ "type": "exclusion",
471
+ "criterion": "Subjects with atrial fibrillation/atrial flutter (chronic or intermittent)",
472
+ "label": "not excluded",
473
+ "evidence": [
474
+ 3,
475
+ 4
476
+ ]
477
+ },
478
+ {
479
+ "type": "exclusion",
480
+ "criterion": "Subjects with another source of right to left shunt identified at baseline, including an atrial septal defect and/or fenestrated septum",
481
+ "label": "not excluded",
482
+ "evidence": []
483
+ },
484
+ {
485
+ "type": "exclusion",
486
+ "criterion": "Subjects who could not undergo the TEE examination",
487
+ "label": "not excluded",
488
+ "evidence": [
489
+ 2
490
+ ]
491
+ },
492
+ {
493
+ "type": "exclusion",
494
+ "criterion": "Subjects with contraindication to aspirin or Clopidogrel therapy",
495
+ "label": "not excluded",
496
+ "evidence": []
497
+ },
498
+ {
499
+ "type": "exclusion",
500
+ "criterion": "Pregnant or desire to become pregnant within the next year",
501
+ "label": "not excluded",
502
+ "evidence": [
503
+ 0
504
+ ]
505
+ },
506
+ {
507
+ "type": "exclusion",
508
+ "criterion": "Subjects who have a underlying malignancy",
509
+ "label": "not excluded",
510
+ "evidence": []
511
+ }
512
+ ]
513
+ },
514
+ {
515
+ "name": "Hand-written unseen example (not from the dataset)",
516
+ "patient_id": null,
517
+ "trial_id": null,
518
+ "note": "A 64-year-old man with type 2 diabetes diagnosed 8 years ago presents for routine follow-up. His HbA1c last month was 8.9%. He takes metformin 1000 mg twice daily. He had a myocardial infarction 3 years ago and has stable angina. Estimated GFR is 52 mL/min/1.73m2. He does not smoke. He lives with his wife and works as an accountant.",
519
+ "criteria": "Inclusion criteria:\n- Adults aged 40 to 75 years\n- Type 2 diabetes with HbA1c between 7.5% and 10%\n- On a stable dose of metformin for at least 3 months\n\nExclusion criteria:\n- Type 1 diabetes\n- eGFR below 30 mL/min/1.73m2\n- Pregnancy or breastfeeding\n- Current insulin therapy",
520
+ "gold": null
521
+ }
522
+ ]
explain.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Traceable explanations and the explicit trial-level aggregation rule.
2
+
3
+ Explanations are built only from the predicted label and the exact cited sentences, so
4
+ every statement in an explanation points to text that exists in the patient record. The
5
+ model is not asked to write free-text rationales: the dataset's only free-text
6
+ rationales are GPT-4 outputs, which the assignment forbids as inputs or targets.
7
+ """
8
+ from __future__ import annotations
9
+ from .labels import LABEL_MEANING, INVALID
10
+
11
+
12
+ def explain(criterion_type, criterion_text, label, evidence_ids, sentences: dict[int, str]):
13
+ if label == INVALID:
14
+ return "The model output could not be parsed, so no decision is made for this criterion."
15
+ cited = [f'[{i}] "{sentences[i]}"' for i in evidence_ids if i in sentences]
16
+ base = f"Prediction '{label}': {LABEL_MEANING.get(label, label)}."
17
+ if label == "not enough information":
18
+ if cited:
19
+ return base + " Related but insufficient sentences: " + "; ".join(cited) + "."
20
+ return base + " No sentence in the note addresses this criterion; missing information is not treated as proof either way."
21
+ if not cited:
22
+ return base + " Warning: no supporting sentence was cited, so this decision is unsupported and should be checked."
23
+ return base + " Supporting sentences: " + "; ".join(cited) + "."
24
+
25
+
26
+ def aggregate_trial(results):
27
+ """Rule-based preliminary trial verdict from criterion-level predictions.
28
+ This is NOT a ground-truth-labelled outcome; the dataset only labels criteria.
29
+
30
+ Rules (applied in order):
31
+ 1. any exclusion predicted 'excluded' or inclusion predicted 'not included'
32
+ -> 'likely ineligible'
33
+ 2. any 'not enough information' or invalid output -> 'undetermined: more information needed'
34
+ 3. otherwise (all inclusion 'included'/'not applicable', all exclusion
35
+ 'not excluded'/'not applicable') -> 'potentially eligible'
36
+ """
37
+ blockers = [r for r in results if (r["criterion_type"] == "exclusion" and r["label"] == "excluded")
38
+ or (r["criterion_type"] == "inclusion" and r["label"] == "not included")]
39
+ unknown = [r for r in results if r["label"] in ("not enough information", INVALID)]
40
+ if blockers:
41
+ verdict = "likely ineligible"
42
+ elif unknown:
43
+ verdict = "undetermined: more information needed"
44
+ else:
45
+ verdict = "potentially eligible"
46
+ return {"verdict": verdict, "n_criteria": len(results), "n_blocking": len(blockers),
47
+ "n_unknown": len(unknown),
48
+ "rule": "exclusion 'excluded' or inclusion 'not included' blocks; any 'not enough information' "
49
+ "leaves the outcome undetermined; otherwise potentially eligible."}
labels.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Label sets and output schema.
2
+
3
+ The TrialGPT criterion annotations use different label vocabularies for inclusion and
4
+ exclusion criteria. We keep all of them (no binary collapse):
5
+
6
+ inclusion: included | not included | not enough information | not applicable
7
+ exclusion: excluded | not excluded | not enough information | not applicable
8
+ """
9
+ INCLUSION_LABELS = ["included", "not included", "not enough information", "not applicable"]
10
+ EXCLUSION_LABELS = ["excluded", "not excluded", "not enough information", "not applicable"]
11
+ ALL_LABELS = ["included", "not included", "excluded", "not excluded",
12
+ "not enough information", "not applicable"]
13
+ INVALID = "invalid output"
14
+
15
+
16
+ def labels_for(criterion_type: str):
17
+ t = criterion_type.strip().lower()
18
+ if t == "inclusion":
19
+ return INCLUSION_LABELS
20
+ if t == "exclusion":
21
+ return EXCLUSION_LABELS
22
+ raise ValueError(f"criterion_type must be 'inclusion' or 'exclusion', got {criterion_type!r}")
23
+
24
+
25
+ # Short human meaning of each label, used for template explanations in the app/report.
26
+ LABEL_MEANING = {
27
+ "included": "the patient record shows the inclusion criterion is met",
28
+ "not included": "the patient record shows the inclusion criterion is not met",
29
+ "excluded": "the patient record shows the exclusion criterion applies, so the patient would be excluded",
30
+ "not excluded": "the patient record shows the exclusion condition is absent",
31
+ "not enough information": "the record does not contain enough information to decide",
32
+ "not applicable": "the criterion does not apply to this patient",
33
+ }
metrics.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Common evaluation metrics.
2
+
3
+ Classification: accuracy, macro-F1, per-class P/R/F1, confusion matrix; overall and
4
+ separately for inclusion and exclusion criteria. Macro-F1 averages over the classes
5
+ that occur in the gold labels of the evaluated subset (classes absent from the gold
6
+ subset are reported with support 0 but do not enter the macro average; a prediction of
7
+ an absent class still counts as an error through the other classes' precision).
8
+ Invalid outputs count as wrong predictions.
9
+
10
+ Evidence retrieval: sets of sentence IDs per record.
11
+ * micro P/R/F1: TP/FP/FN summed over all records (empty sets contribute nothing).
12
+ * macro P/R/F1 (non-empty gold): averaged over records whose gold set is non-empty;
13
+ an empty prediction there gets P=0, R=0, F1=0.
14
+ * empty-gold handling: records with an empty gold set are reported separately as
15
+ 'empty-gold agreement' = share of them where the model also cited nothing.
16
+ """
17
+ from __future__ import annotations
18
+ import numpy as np
19
+ from sklearn.metrics import confusion_matrix, precision_recall_fscore_support, accuracy_score
20
+ from .labels import ALL_LABELS, INCLUSION_LABELS, EXCLUSION_LABELS, INVALID
21
+
22
+
23
+ def classification_report(gold, pred, label_space=None):
24
+ gold, pred = list(gold), list(pred)
25
+ label_space = label_space or ALL_LABELS
26
+ if not gold:
27
+ return {"n": 0, "accuracy": None, "macro_f1": None, "macro_f1_classes": [], "per_class": {},
28
+ "invalid_outputs": 0, "confusion_matrix": {"labels": label_space, "matrix": []}}
29
+ present = [l for l in label_space if l in gold]
30
+ cm_labels = label_space + ([INVALID] if INVALID in pred else [])
31
+ p, r, f, s = precision_recall_fscore_support(gold, pred, labels=label_space, zero_division=0)
32
+ per_class = {l: {"precision": float(p[i]), "recall": float(r[i]), "f1": float(f[i]), "support": int(s[i])}
33
+ for i, l in enumerate(label_space)}
34
+ macro_f1 = float(np.mean([per_class[l]["f1"] for l in present])) if present else 0.0
35
+ return {
36
+ "n": len(gold),
37
+ "accuracy": float(accuracy_score(gold, pred)) if gold else 0.0,
38
+ "macro_f1": macro_f1,
39
+ "macro_f1_classes": present,
40
+ "per_class": per_class,
41
+ "invalid_outputs": int(sum(x == INVALID for x in pred)),
42
+ "confusion_matrix": {"labels": cm_labels,
43
+ "matrix": confusion_matrix(gold, pred, labels=cm_labels).tolist()},
44
+ }
45
+
46
+
47
+ def classification_suite(rows):
48
+ """rows: list of dicts with criterion_type, gold_label, pred_label."""
49
+ out = {"overall": classification_report([r["gold_label"] for r in rows], [r["pred_label"] for r in rows])}
50
+ for t, space in [("inclusion", INCLUSION_LABELS), ("exclusion", EXCLUSION_LABELS)]:
51
+ sub = [r for r in rows if r["criterion_type"] == t]
52
+ out[t] = classification_report([r["gold_label"] for r in sub], [r["pred_label"] for r in sub], space)
53
+ return out
54
+
55
+
56
+ def _prf(tp, fp, fn):
57
+ p = tp / (tp + fp) if tp + fp else 0.0
58
+ r = tp / (tp + fn) if tp + fn else 0.0
59
+ f = 2 * p * r / (p + r) if p + r else 0.0
60
+ return p, r, f
61
+
62
+
63
+ def evidence_report(rows):
64
+ """rows: dicts with gold_evidence, pred_evidence (lists of ints)."""
65
+ TP = FP = FN = 0
66
+ per = []
67
+ empty_gold = empty_agree = 0
68
+ for r in rows:
69
+ g, p = set(r["gold_evidence"]), set(r["pred_evidence"])
70
+ tp, fp, fn = len(g & p), len(p - g), len(g - p)
71
+ TP, FP, FN = TP + tp, FP + fp, FN + fn
72
+ if g:
73
+ per.append(_prf(tp, fp, fn))
74
+ else:
75
+ empty_gold += 1
76
+ empty_agree += int(not p)
77
+ mp, mr, mf = _prf(TP, FP, FN)
78
+ arr = np.array(per) if per else np.zeros((1, 3))
79
+ return {
80
+ "micro": {"precision": mp, "recall": mr, "f1": mf, "tp": TP, "fp": FP, "fn": FN},
81
+ "macro_nonempty_gold": {"precision": float(arr[:, 0].mean()), "recall": float(arr[:, 1].mean()),
82
+ "f1": float(arr[:, 2].mean()), "n_records": len(per)},
83
+ "empty_gold": {"n_records": empty_gold,
84
+ "model_also_empty": empty_agree,
85
+ "agreement_rate": (empty_agree / empty_gold) if empty_gold else None},
86
+ }
87
+
88
+
89
+ def evaluate_rows(rows):
90
+ res = {"classification": classification_suite(rows), "evidence": {"overall": evidence_report(rows)}}
91
+ for t in ("inclusion", "exclusion"):
92
+ res["evidence"][t] = evidence_report([r for r in rows if r["criterion_type"] == t])
93
+ res["valid_json_rate"] = float(np.mean([r.get("valid_json", True) for r in rows])) if rows else 0.0
94
+ return res
metrics_base_test.json ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "classification": {
3
+ "overall": {
4
+ "n": 206,
5
+ "accuracy": 0.1650485436893204,
6
+ "macro_f1": 0.17029396694058035,
7
+ "macro_f1_classes": [
8
+ "included",
9
+ "not included",
10
+ "not excluded",
11
+ "not enough information",
12
+ "not applicable"
13
+ ],
14
+ "per_class": {
15
+ "included": {
16
+ "precision": 0.4,
17
+ "recall": 0.9629629629629629,
18
+ "f1": 0.5652173913043478,
19
+ "support": 27
20
+ },
21
+ "not included": {
22
+ "precision": 0.0,
23
+ "recall": 0.0,
24
+ "f1": 0.0,
25
+ "support": 7
26
+ },
27
+ "excluded": {
28
+ "precision": 0.0,
29
+ "recall": 0.0,
30
+ "f1": 0.0,
31
+ "support": 0
32
+ },
33
+ "not excluded": {
34
+ "precision": 1.0,
35
+ "recall": 0.01098901098901099,
36
+ "f1": 0.021739130434782608,
37
+ "support": 91
38
+ },
39
+ "not enough information": {
40
+ "precision": 0.38461538461538464,
41
+ "recall": 0.07575757575757576,
42
+ "f1": 0.12658227848101267,
43
+ "support": 66
44
+ },
45
+ "not applicable": {
46
+ "precision": 0.14285714285714285,
47
+ "recall": 0.13333333333333333,
48
+ "f1": 0.13793103448275862,
49
+ "support": 15
50
+ }
51
+ },
52
+ "invalid_outputs": 0,
53
+ "confusion_matrix": {
54
+ "labels": [
55
+ "included",
56
+ "not included",
57
+ "excluded",
58
+ "not excluded",
59
+ "not enough information",
60
+ "not applicable"
61
+ ],
62
+ "matrix": [
63
+ [
64
+ 26,
65
+ 0,
66
+ 0,
67
+ 0,
68
+ 0,
69
+ 1
70
+ ],
71
+ [
72
+ 7,
73
+ 0,
74
+ 0,
75
+ 0,
76
+ 0,
77
+ 0
78
+ ],
79
+ [
80
+ 0,
81
+ 0,
82
+ 0,
83
+ 0,
84
+ 0,
85
+ 0
86
+ ],
87
+ [
88
+ 0,
89
+ 0,
90
+ 77,
91
+ 1,
92
+ 6,
93
+ 7
94
+ ],
95
+ [
96
+ 31,
97
+ 0,
98
+ 26,
99
+ 0,
100
+ 5,
101
+ 4
102
+ ],
103
+ [
104
+ 1,
105
+ 0,
106
+ 10,
107
+ 0,
108
+ 2,
109
+ 2
110
+ ]
111
+ ]
112
+ }
113
+ },
114
+ "inclusion": {
115
+ "n": 75,
116
+ "accuracy": 0.4,
117
+ "macro_f1": 0.23257418909592822,
118
+ "macro_f1_classes": [
119
+ "included",
120
+ "not included",
121
+ "not enough information",
122
+ "not applicable"
123
+ ],
124
+ "per_class": {
125
+ "included": {
126
+ "precision": 0.4,
127
+ "recall": 0.9629629629629629,
128
+ "f1": 0.5652173913043478,
129
+ "support": 27
130
+ },
131
+ "not included": {
132
+ "precision": 0.0,
133
+ "recall": 0.0,
134
+ "f1": 0.0,
135
+ "support": 7
136
+ },
137
+ "not enough information": {
138
+ "precision": 0.75,
139
+ "recall": 0.07894736842105263,
140
+ "f1": 0.14285714285714285,
141
+ "support": 38
142
+ },
143
+ "not applicable": {
144
+ "precision": 0.16666666666666666,
145
+ "recall": 0.3333333333333333,
146
+ "f1": 0.2222222222222222,
147
+ "support": 3
148
+ }
149
+ },
150
+ "invalid_outputs": 0,
151
+ "confusion_matrix": {
152
+ "labels": [
153
+ "included",
154
+ "not included",
155
+ "not enough information",
156
+ "not applicable"
157
+ ],
158
+ "matrix": [
159
+ [
160
+ 26,
161
+ 0,
162
+ 0,
163
+ 1
164
+ ],
165
+ [
166
+ 7,
167
+ 0,
168
+ 0,
169
+ 0
170
+ ],
171
+ [
172
+ 31,
173
+ 0,
174
+ 3,
175
+ 4
176
+ ],
177
+ [
178
+ 1,
179
+ 0,
180
+ 1,
181
+ 1
182
+ ]
183
+ ]
184
+ }
185
+ },
186
+ "exclusion": {
187
+ "n": 131,
188
+ "accuracy": 0.030534351145038167,
189
+ "macro_f1": 0.07661574618096358,
190
+ "macro_f1_classes": [
191
+ "not excluded",
192
+ "not enough information",
193
+ "not applicable"
194
+ ],
195
+ "per_class": {
196
+ "excluded": {
197
+ "precision": 0.0,
198
+ "recall": 0.0,
199
+ "f1": 0.0,
200
+ "support": 0
201
+ },
202
+ "not excluded": {
203
+ "precision": 1.0,
204
+ "recall": 0.01098901098901099,
205
+ "f1": 0.021739130434782608,
206
+ "support": 91
207
+ },
208
+ "not enough information": {
209
+ "precision": 0.2222222222222222,
210
+ "recall": 0.07142857142857142,
211
+ "f1": 0.10810810810810811,
212
+ "support": 28
213
+ },
214
+ "not applicable": {
215
+ "precision": 0.125,
216
+ "recall": 0.08333333333333333,
217
+ "f1": 0.1,
218
+ "support": 12
219
+ }
220
+ },
221
+ "invalid_outputs": 0,
222
+ "confusion_matrix": {
223
+ "labels": [
224
+ "excluded",
225
+ "not excluded",
226
+ "not enough information",
227
+ "not applicable"
228
+ ],
229
+ "matrix": [
230
+ [
231
+ 0,
232
+ 0,
233
+ 0,
234
+ 0
235
+ ],
236
+ [
237
+ 77,
238
+ 1,
239
+ 6,
240
+ 7
241
+ ],
242
+ [
243
+ 26,
244
+ 0,
245
+ 2,
246
+ 0
247
+ ],
248
+ [
249
+ 10,
250
+ 0,
251
+ 1,
252
+ 1
253
+ ]
254
+ ]
255
+ }
256
+ }
257
+ },
258
+ "evidence": {
259
+ "overall": {
260
+ "micro": {
261
+ "precision": 0.08709677419354839,
262
+ "recall": 0.8617021276595744,
263
+ "f1": 0.158203125,
264
+ "tp": 81,
265
+ "fp": 849,
266
+ "fn": 13
267
+ },
268
+ "macro_nonempty_gold": {
269
+ "precision": 0.2661072079104866,
270
+ "recall": 0.7950819672131147,
271
+ "f1": 0.37075938633315686,
272
+ "n_records": 61
273
+ },
274
+ "empty_gold": {
275
+ "n_records": 145,
276
+ "model_also_empty": 12,
277
+ "agreement_rate": 0.08275862068965517
278
+ }
279
+ },
280
+ "inclusion": {
281
+ "micro": {
282
+ "precision": 0.15804597701149425,
283
+ "recall": 0.8870967741935484,
284
+ "f1": 0.26829268292682923,
285
+ "tp": 55,
286
+ "fp": 293,
287
+ "fn": 7
288
+ },
289
+ "macro_nonempty_gold": {
290
+ "precision": 0.24936507936507932,
291
+ "recall": 0.8444444444444444,
292
+ "f1": 0.3635481802148469,
293
+ "n_records": 45
294
+ },
295
+ "empty_gold": {
296
+ "n_records": 30,
297
+ "model_also_empty": 3,
298
+ "agreement_rate": 0.1
299
+ }
300
+ },
301
+ "exclusion": {
302
+ "micro": {
303
+ "precision": 0.044673539518900345,
304
+ "recall": 0.8125,
305
+ "f1": 0.08469055374592835,
306
+ "tp": 26,
307
+ "fp": 556,
308
+ "fn": 6
309
+ },
310
+ "macro_nonempty_gold": {
311
+ "precision": 0.31319444444444444,
312
+ "recall": 0.65625,
313
+ "f1": 0.39104090354090354,
314
+ "n_records": 16
315
+ },
316
+ "empty_gold": {
317
+ "n_records": 115,
318
+ "model_also_empty": 9,
319
+ "agreement_rate": 0.0782608695652174
320
+ }
321
+ }
322
+ },
323
+ "valid_json_rate": 1.0,
324
+ "settings": {
325
+ "decoding": "greedy (argmax), HF forward + explicit DynamicCache loop",
326
+ "max_new_tokens": 48,
327
+ "prompt": "trialscreen.data.build_messages + Qwen chat template",
328
+ "env": {
329
+ "python": "3.13.16",
330
+ "torch": "2.11.0+cu130",
331
+ "transformers": "5.22.2",
332
+ "cuda": true,
333
+ "gpu": "Tesla T4",
334
+ "gpu_mem_gb": 14.6
335
+ },
336
+ "model": "Qwen/Qwen2.5-1.5B-Instruct",
337
+ "adapter": null,
338
+ "minutes": 3.473239330450694
339
+ }
340
+ }
metrics_base_validation.json ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "classification": {
3
+ "overall": {
4
+ "n": 206,
5
+ "accuracy": 0.2087378640776699,
6
+ "macro_f1": 0.17537495399337502,
7
+ "macro_f1_classes": [
8
+ "included",
9
+ "not included",
10
+ "excluded",
11
+ "not excluded",
12
+ "not enough information",
13
+ "not applicable"
14
+ ],
15
+ "per_class": {
16
+ "included": {
17
+ "precision": 0.5737704918032787,
18
+ "recall": 1.0,
19
+ "f1": 0.7291666666666666,
20
+ "support": 35
21
+ },
22
+ "not included": {
23
+ "precision": 0.0,
24
+ "recall": 0.0,
25
+ "f1": 0.0,
26
+ "support": 3
27
+ },
28
+ "excluded": {
29
+ "precision": 0.015384615384615385,
30
+ "recall": 1.0,
31
+ "f1": 0.030303030303030304,
32
+ "support": 2
33
+ },
34
+ "not excluded": {
35
+ "precision": 1.0,
36
+ "recall": 0.0297029702970297,
37
+ "f1": 0.057692307692307696,
38
+ "support": 101
39
+ },
40
+ "not enough information": {
41
+ "precision": 0.25,
42
+ "recall": 0.018867924528301886,
43
+ "f1": 0.03508771929824561,
44
+ "support": 53
45
+ },
46
+ "not applicable": {
47
+ "precision": 0.25,
48
+ "recall": 0.16666666666666666,
49
+ "f1": 0.2,
50
+ "support": 12
51
+ }
52
+ },
53
+ "invalid_outputs": 0,
54
+ "confusion_matrix": {
55
+ "labels": [
56
+ "included",
57
+ "not included",
58
+ "excluded",
59
+ "not excluded",
60
+ "not enough information",
61
+ "not applicable"
62
+ ],
63
+ "matrix": [
64
+ [
65
+ 35,
66
+ 0,
67
+ 0,
68
+ 0,
69
+ 0,
70
+ 0
71
+ ],
72
+ [
73
+ 3,
74
+ 0,
75
+ 0,
76
+ 0,
77
+ 0,
78
+ 0
79
+ ],
80
+ [
81
+ 0,
82
+ 0,
83
+ 2,
84
+ 0,
85
+ 0,
86
+ 0
87
+ ],
88
+ [
89
+ 0,
90
+ 0,
91
+ 92,
92
+ 3,
93
+ 3,
94
+ 3
95
+ ],
96
+ [
97
+ 23,
98
+ 0,
99
+ 26,
100
+ 0,
101
+ 1,
102
+ 3
103
+ ],
104
+ [
105
+ 0,
106
+ 0,
107
+ 10,
108
+ 0,
109
+ 0,
110
+ 2
111
+ ]
112
+ ]
113
+ }
114
+ },
115
+ "inclusion": {
116
+ "n": 66,
117
+ "accuracy": 0.5606060606060606,
118
+ "macro_f1": 0.3001488095238095,
119
+ "macro_f1_classes": [
120
+ "included",
121
+ "not included",
122
+ "not enough information",
123
+ "not applicable"
124
+ ],
125
+ "per_class": {
126
+ "included": {
127
+ "precision": 0.5737704918032787,
128
+ "recall": 1.0,
129
+ "f1": 0.7291666666666666,
130
+ "support": 35
131
+ },
132
+ "not included": {
133
+ "precision": 0.0,
134
+ "recall": 0.0,
135
+ "f1": 0.0,
136
+ "support": 3
137
+ },
138
+ "not enough information": {
139
+ "precision": 1.0,
140
+ "recall": 0.037037037037037035,
141
+ "f1": 0.07142857142857142,
142
+ "support": 27
143
+ },
144
+ "not applicable": {
145
+ "precision": 0.25,
146
+ "recall": 1.0,
147
+ "f1": 0.4,
148
+ "support": 1
149
+ }
150
+ },
151
+ "invalid_outputs": 0,
152
+ "confusion_matrix": {
153
+ "labels": [
154
+ "included",
155
+ "not included",
156
+ "not enough information",
157
+ "not applicable"
158
+ ],
159
+ "matrix": [
160
+ [
161
+ 35,
162
+ 0,
163
+ 0,
164
+ 0
165
+ ],
166
+ [
167
+ 3,
168
+ 0,
169
+ 0,
170
+ 0
171
+ ],
172
+ [
173
+ 23,
174
+ 0,
175
+ 1,
176
+ 3
177
+ ],
178
+ [
179
+ 0,
180
+ 0,
181
+ 0,
182
+ 1
183
+ ]
184
+ ]
185
+ }
186
+ },
187
+ "exclusion": {
188
+ "n": 140,
189
+ "accuracy": 0.04285714285714286,
190
+ "macro_f1": 0.055332167832167836,
191
+ "macro_f1_classes": [
192
+ "excluded",
193
+ "not excluded",
194
+ "not enough information",
195
+ "not applicable"
196
+ ],
197
+ "per_class": {
198
+ "excluded": {
199
+ "precision": 0.015384615384615385,
200
+ "recall": 1.0,
201
+ "f1": 0.030303030303030304,
202
+ "support": 2
203
+ },
204
+ "not excluded": {
205
+ "precision": 1.0,
206
+ "recall": 0.0297029702970297,
207
+ "f1": 0.057692307692307696,
208
+ "support": 101
209
+ },
210
+ "not enough information": {
211
+ "precision": 0.0,
212
+ "recall": 0.0,
213
+ "f1": 0.0,
214
+ "support": 26
215
+ },
216
+ "not applicable": {
217
+ "precision": 0.25,
218
+ "recall": 0.09090909090909091,
219
+ "f1": 0.13333333333333333,
220
+ "support": 11
221
+ }
222
+ },
223
+ "invalid_outputs": 0,
224
+ "confusion_matrix": {
225
+ "labels": [
226
+ "excluded",
227
+ "not excluded",
228
+ "not enough information",
229
+ "not applicable"
230
+ ],
231
+ "matrix": [
232
+ [
233
+ 2,
234
+ 0,
235
+ 0,
236
+ 0
237
+ ],
238
+ [
239
+ 92,
240
+ 3,
241
+ 3,
242
+ 3
243
+ ],
244
+ [
245
+ 26,
246
+ 0,
247
+ 0,
248
+ 0
249
+ ],
250
+ [
251
+ 10,
252
+ 0,
253
+ 0,
254
+ 1
255
+ ]
256
+ ]
257
+ }
258
+ }
259
+ },
260
+ "evidence": {
261
+ "overall": {
262
+ "micro": {
263
+ "precision": 0.08085808580858085,
264
+ "recall": 0.8521739130434782,
265
+ "f1": 0.14770158251695553,
266
+ "tp": 98,
267
+ "fp": 1114,
268
+ "fn": 17
269
+ },
270
+ "macro_nonempty_gold": {
271
+ "precision": 0.21543209876543207,
272
+ "recall": 0.8555555555555555,
273
+ "f1": 0.32336459836459835,
274
+ "n_records": 90
275
+ },
276
+ "empty_gold": {
277
+ "n_records": 116,
278
+ "model_also_empty": 3,
279
+ "agreement_rate": 0.02586206896551724
280
+ }
281
+ },
282
+ "inclusion": {
283
+ "micro": {
284
+ "precision": 0.16348773841961853,
285
+ "recall": 0.8955223880597015,
286
+ "f1": 0.27649769585253453,
287
+ "tp": 60,
288
+ "fp": 307,
289
+ "fn": 7
290
+ },
291
+ "macro_nonempty_gold": {
292
+ "precision": 0.2316666666666667,
293
+ "recall": 0.875,
294
+ "f1": 0.34649783549783547,
295
+ "n_records": 50
296
+ },
297
+ "empty_gold": {
298
+ "n_records": 16,
299
+ "model_also_empty": 1,
300
+ "agreement_rate": 0.0625
301
+ }
302
+ },
303
+ "exclusion": {
304
+ "micro": {
305
+ "precision": 0.04497041420118343,
306
+ "recall": 0.7916666666666666,
307
+ "f1": 0.08510638297872342,
308
+ "tp": 38,
309
+ "fp": 807,
310
+ "fn": 10
311
+ },
312
+ "macro_nonempty_gold": {
313
+ "precision": 0.1951388888888889,
314
+ "recall": 0.83125,
315
+ "f1": 0.29444805194805196,
316
+ "n_records": 40
317
+ },
318
+ "empty_gold": {
319
+ "n_records": 100,
320
+ "model_also_empty": 2,
321
+ "agreement_rate": 0.02
322
+ }
323
+ }
324
+ },
325
+ "valid_json_rate": 1.0,
326
+ "settings": {
327
+ "decoding": "greedy (argmax), HF forward + explicit DynamicCache loop",
328
+ "max_new_tokens": 48,
329
+ "prompt": "trialscreen.data.build_messages + Qwen chat template",
330
+ "env": {
331
+ "python": "3.13.16",
332
+ "torch": "2.11.0+cu130",
333
+ "transformers": "5.22.2",
334
+ "cuda": true,
335
+ "gpu": "Tesla T4",
336
+ "gpu_mem_gb": 14.6
337
+ },
338
+ "model": "Qwen/Qwen2.5-1.5B-Instruct",
339
+ "adapter": null,
340
+ "minutes": 3.9639099796613055
341
+ }
342
+ }
metrics_finetuned_test.json ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "classification": {
3
+ "overall": {
4
+ "n": 206,
5
+ "accuracy": 0.7427184466019418,
6
+ "macro_f1": 0.5337093457967678,
7
+ "macro_f1_classes": [
8
+ "included",
9
+ "not included",
10
+ "not excluded",
11
+ "not enough information",
12
+ "not applicable"
13
+ ],
14
+ "per_class": {
15
+ "included": {
16
+ "precision": 0.92,
17
+ "recall": 0.8518518518518519,
18
+ "f1": 0.8846153846153846,
19
+ "support": 27
20
+ },
21
+ "not included": {
22
+ "precision": 0.0,
23
+ "recall": 0.0,
24
+ "f1": 0.0,
25
+ "support": 7
26
+ },
27
+ "excluded": {
28
+ "precision": 0.0,
29
+ "recall": 0.0,
30
+ "f1": 0.0,
31
+ "support": 0
32
+ },
33
+ "not excluded": {
34
+ "precision": 0.712,
35
+ "recall": 0.978021978021978,
36
+ "f1": 0.8240740740740741,
37
+ "support": 91
38
+ },
39
+ "not enough information": {
40
+ "precision": 0.7307692307692307,
41
+ "recall": 0.5757575757575758,
42
+ "f1": 0.6440677966101694,
43
+ "support": 66
44
+ },
45
+ "not applicable": {
46
+ "precision": 0.75,
47
+ "recall": 0.2,
48
+ "f1": 0.3157894736842105,
49
+ "support": 15
50
+ }
51
+ },
52
+ "invalid_outputs": 0,
53
+ "confusion_matrix": {
54
+ "labels": [
55
+ "included",
56
+ "not included",
57
+ "excluded",
58
+ "not excluded",
59
+ "not enough information",
60
+ "not applicable"
61
+ ],
62
+ "matrix": [
63
+ [
64
+ 23,
65
+ 0,
66
+ 0,
67
+ 0,
68
+ 4,
69
+ 0
70
+ ],
71
+ [
72
+ 1,
73
+ 0,
74
+ 0,
75
+ 0,
76
+ 6,
77
+ 0
78
+ ],
79
+ [
80
+ 0,
81
+ 0,
82
+ 0,
83
+ 0,
84
+ 0,
85
+ 0
86
+ ],
87
+ [
88
+ 0,
89
+ 0,
90
+ 0,
91
+ 89,
92
+ 1,
93
+ 1
94
+ ],
95
+ [
96
+ 1,
97
+ 0,
98
+ 0,
99
+ 27,
100
+ 38,
101
+ 0
102
+ ],
103
+ [
104
+ 0,
105
+ 0,
106
+ 0,
107
+ 9,
108
+ 3,
109
+ 3
110
+ ]
111
+ ]
112
+ }
113
+ },
114
+ "inclusion": {
115
+ "n": 75,
116
+ "accuracy": 0.8,
117
+ "macro_f1": 0.43138111888111885,
118
+ "macro_f1_classes": [
119
+ "included",
120
+ "not included",
121
+ "not enough information",
122
+ "not applicable"
123
+ ],
124
+ "per_class": {
125
+ "included": {
126
+ "precision": 0.92,
127
+ "recall": 0.8518518518518519,
128
+ "f1": 0.8846153846153846,
129
+ "support": 27
130
+ },
131
+ "not included": {
132
+ "precision": 0.0,
133
+ "recall": 0.0,
134
+ "f1": 0.0,
135
+ "support": 7
136
+ },
137
+ "not enough information": {
138
+ "precision": 0.74,
139
+ "recall": 0.9736842105263158,
140
+ "f1": 0.8409090909090909,
141
+ "support": 38
142
+ },
143
+ "not applicable": {
144
+ "precision": 0.0,
145
+ "recall": 0.0,
146
+ "f1": 0.0,
147
+ "support": 3
148
+ }
149
+ },
150
+ "invalid_outputs": 0,
151
+ "confusion_matrix": {
152
+ "labels": [
153
+ "included",
154
+ "not included",
155
+ "not enough information",
156
+ "not applicable"
157
+ ],
158
+ "matrix": [
159
+ [
160
+ 23,
161
+ 0,
162
+ 4,
163
+ 0
164
+ ],
165
+ [
166
+ 1,
167
+ 0,
168
+ 6,
169
+ 0
170
+ ],
171
+ [
172
+ 1,
173
+ 0,
174
+ 37,
175
+ 0
176
+ ],
177
+ [
178
+ 0,
179
+ 0,
180
+ 3,
181
+ 0
182
+ ]
183
+ ]
184
+ }
185
+ },
186
+ "exclusion": {
187
+ "n": 131,
188
+ "accuracy": 0.7099236641221374,
189
+ "macro_f1": 0.4219135802469136,
190
+ "macro_f1_classes": [
191
+ "not excluded",
192
+ "not enough information",
193
+ "not applicable"
194
+ ],
195
+ "per_class": {
196
+ "excluded": {
197
+ "precision": 0.0,
198
+ "recall": 0.0,
199
+ "f1": 0.0,
200
+ "support": 0
201
+ },
202
+ "not excluded": {
203
+ "precision": 0.712,
204
+ "recall": 0.978021978021978,
205
+ "f1": 0.8240740740740741,
206
+ "support": 91
207
+ },
208
+ "not enough information": {
209
+ "precision": 0.5,
210
+ "recall": 0.03571428571428571,
211
+ "f1": 0.06666666666666667,
212
+ "support": 28
213
+ },
214
+ "not applicable": {
215
+ "precision": 0.75,
216
+ "recall": 0.25,
217
+ "f1": 0.375,
218
+ "support": 12
219
+ }
220
+ },
221
+ "invalid_outputs": 0,
222
+ "confusion_matrix": {
223
+ "labels": [
224
+ "excluded",
225
+ "not excluded",
226
+ "not enough information",
227
+ "not applicable"
228
+ ],
229
+ "matrix": [
230
+ [
231
+ 0,
232
+ 0,
233
+ 0,
234
+ 0
235
+ ],
236
+ [
237
+ 0,
238
+ 89,
239
+ 1,
240
+ 1
241
+ ],
242
+ [
243
+ 0,
244
+ 27,
245
+ 1,
246
+ 0
247
+ ],
248
+ [
249
+ 0,
250
+ 9,
251
+ 0,
252
+ 3
253
+ ]
254
+ ]
255
+ }
256
+ }
257
+ },
258
+ "evidence": {
259
+ "overall": {
260
+ "micro": {
261
+ "precision": 0.5684210526315789,
262
+ "recall": 0.574468085106383,
263
+ "f1": 0.5714285714285715,
264
+ "tp": 54,
265
+ "fp": 41,
266
+ "fn": 40
267
+ },
268
+ "macro_nonempty_gold": {
269
+ "precision": 0.5942622950819673,
270
+ "recall": 0.631967213114754,
271
+ "f1": 0.5982825917252148,
272
+ "n_records": 61
273
+ },
274
+ "empty_gold": {
275
+ "n_records": 145,
276
+ "model_also_empty": 130,
277
+ "agreement_rate": 0.896551724137931
278
+ }
279
+ },
280
+ "inclusion": {
281
+ "micro": {
282
+ "precision": 0.5679012345679012,
283
+ "recall": 0.7419354838709677,
284
+ "f1": 0.6433566433566433,
285
+ "tp": 46,
286
+ "fp": 35,
287
+ "fn": 16
288
+ },
289
+ "macro_nonempty_gold": {
290
+ "precision": 0.6870370370370371,
291
+ "recall": 0.7288888888888888,
292
+ "f1": 0.691957671957672,
293
+ "n_records": 45
294
+ },
295
+ "empty_gold": {
296
+ "n_records": 30,
297
+ "model_also_empty": 19,
298
+ "agreement_rate": 0.6333333333333333
299
+ }
300
+ },
301
+ "exclusion": {
302
+ "micro": {
303
+ "precision": 0.5714285714285714,
304
+ "recall": 0.25,
305
+ "f1": 0.34782608695652173,
306
+ "tp": 8,
307
+ "fp": 6,
308
+ "fn": 24
309
+ },
310
+ "macro_nonempty_gold": {
311
+ "precision": 0.3333333333333333,
312
+ "recall": 0.359375,
313
+ "f1": 0.3348214285714286,
314
+ "n_records": 16
315
+ },
316
+ "empty_gold": {
317
+ "n_records": 115,
318
+ "model_also_empty": 111,
319
+ "agreement_rate": 0.9652173913043478
320
+ }
321
+ }
322
+ },
323
+ "valid_json_rate": 1.0,
324
+ "settings": {
325
+ "decoding": "greedy (argmax), HF forward + explicit DynamicCache loop",
326
+ "max_new_tokens": 48,
327
+ "prompt": "trialscreen.data.build_messages + Qwen chat template",
328
+ "env": {
329
+ "python": "3.13.16",
330
+ "torch": "2.11.0+cu130",
331
+ "transformers": "5.22.2",
332
+ "cuda": true,
333
+ "gpu": "Tesla T4",
334
+ "gpu_mem_gb": 14.6
335
+ },
336
+ "model": "Qwen/Qwen2.5-1.5B-Instruct",
337
+ "adapter": "/kaggle/working/trialscreen/checkpoints/qwen2.5-1.5b-trialscreen-lora/best_adapter",
338
+ "minutes": 1.9957645495732625
339
+ }
340
+ }
metrics_finetuned_validation.json ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "classification": {
3
+ "overall": {
4
+ "n": 206,
5
+ "accuracy": 0.7427184466019418,
6
+ "macro_f1": 0.443793395723245,
7
+ "macro_f1_classes": [
8
+ "included",
9
+ "not included",
10
+ "excluded",
11
+ "not excluded",
12
+ "not enough information",
13
+ "not applicable"
14
+ ],
15
+ "per_class": {
16
+ "included": {
17
+ "precision": 0.8333333333333334,
18
+ "recall": 0.7142857142857143,
19
+ "f1": 0.7692307692307693,
20
+ "support": 35
21
+ },
22
+ "not included": {
23
+ "precision": 0.0,
24
+ "recall": 0.0,
25
+ "f1": 0.0,
26
+ "support": 3
27
+ },
28
+ "excluded": {
29
+ "precision": 0.0,
30
+ "recall": 0.0,
31
+ "f1": 0.0,
32
+ "support": 2
33
+ },
34
+ "not excluded": {
35
+ "precision": 0.765625,
36
+ "recall": 0.9702970297029703,
37
+ "f1": 0.8558951965065502,
38
+ "support": 101
39
+ },
40
+ "not enough information": {
41
+ "precision": 0.625,
42
+ "recall": 0.4716981132075472,
43
+ "f1": 0.5376344086021505,
44
+ "support": 53
45
+ },
46
+ "not applicable": {
47
+ "precision": 0.625,
48
+ "recall": 0.4166666666666667,
49
+ "f1": 0.5,
50
+ "support": 12
51
+ }
52
+ },
53
+ "invalid_outputs": 0,
54
+ "confusion_matrix": {
55
+ "labels": [
56
+ "included",
57
+ "not included",
58
+ "excluded",
59
+ "not excluded",
60
+ "not enough information",
61
+ "not applicable"
62
+ ],
63
+ "matrix": [
64
+ [
65
+ 25,
66
+ 0,
67
+ 0,
68
+ 0,
69
+ 10,
70
+ 0
71
+ ],
72
+ [
73
+ 1,
74
+ 0,
75
+ 0,
76
+ 0,
77
+ 2,
78
+ 0
79
+ ],
80
+ [
81
+ 0,
82
+ 0,
83
+ 0,
84
+ 2,
85
+ 0,
86
+ 0
87
+ ],
88
+ [
89
+ 0,
90
+ 0,
91
+ 0,
92
+ 98,
93
+ 2,
94
+ 1
95
+ ],
96
+ [
97
+ 4,
98
+ 0,
99
+ 0,
100
+ 22,
101
+ 25,
102
+ 2
103
+ ],
104
+ [
105
+ 0,
106
+ 0,
107
+ 0,
108
+ 6,
109
+ 1,
110
+ 5
111
+ ]
112
+ ]
113
+ }
114
+ },
115
+ "inclusion": {
116
+ "n": 66,
117
+ "accuracy": 0.7272727272727273,
118
+ "macro_f1": 0.37484737484737485,
119
+ "macro_f1_classes": [
120
+ "included",
121
+ "not included",
122
+ "not enough information",
123
+ "not applicable"
124
+ ],
125
+ "per_class": {
126
+ "included": {
127
+ "precision": 0.8333333333333334,
128
+ "recall": 0.7142857142857143,
129
+ "f1": 0.7692307692307693,
130
+ "support": 35
131
+ },
132
+ "not included": {
133
+ "precision": 0.0,
134
+ "recall": 0.0,
135
+ "f1": 0.0,
136
+ "support": 3
137
+ },
138
+ "not enough information": {
139
+ "precision": 0.6388888888888888,
140
+ "recall": 0.8518518518518519,
141
+ "f1": 0.7301587301587301,
142
+ "support": 27
143
+ },
144
+ "not applicable": {
145
+ "precision": 0.0,
146
+ "recall": 0.0,
147
+ "f1": 0.0,
148
+ "support": 1
149
+ }
150
+ },
151
+ "invalid_outputs": 0,
152
+ "confusion_matrix": {
153
+ "labels": [
154
+ "included",
155
+ "not included",
156
+ "not enough information",
157
+ "not applicable"
158
+ ],
159
+ "matrix": [
160
+ [
161
+ 25,
162
+ 0,
163
+ 10,
164
+ 0
165
+ ],
166
+ [
167
+ 1,
168
+ 0,
169
+ 2,
170
+ 0
171
+ ],
172
+ [
173
+ 4,
174
+ 0,
175
+ 23,
176
+ 0
177
+ ],
178
+ [
179
+ 0,
180
+ 0,
181
+ 1,
182
+ 0
183
+ ]
184
+ ]
185
+ }
186
+ },
187
+ "exclusion": {
188
+ "n": 140,
189
+ "accuracy": 0.75,
190
+ "macro_f1": 0.37888607982839195,
191
+ "macro_f1_classes": [
192
+ "excluded",
193
+ "not excluded",
194
+ "not enough information",
195
+ "not applicable"
196
+ ],
197
+ "per_class": {
198
+ "excluded": {
199
+ "precision": 0.0,
200
+ "recall": 0.0,
201
+ "f1": 0.0,
202
+ "support": 2
203
+ },
204
+ "not excluded": {
205
+ "precision": 0.765625,
206
+ "recall": 0.9702970297029703,
207
+ "f1": 0.8558951965065502,
208
+ "support": 101
209
+ },
210
+ "not enough information": {
211
+ "precision": 0.5,
212
+ "recall": 0.07692307692307693,
213
+ "f1": 0.13333333333333333,
214
+ "support": 26
215
+ },
216
+ "not applicable": {
217
+ "precision": 0.625,
218
+ "recall": 0.45454545454545453,
219
+ "f1": 0.5263157894736842,
220
+ "support": 11
221
+ }
222
+ },
223
+ "invalid_outputs": 0,
224
+ "confusion_matrix": {
225
+ "labels": [
226
+ "excluded",
227
+ "not excluded",
228
+ "not enough information",
229
+ "not applicable"
230
+ ],
231
+ "matrix": [
232
+ [
233
+ 0,
234
+ 2,
235
+ 0,
236
+ 0
237
+ ],
238
+ [
239
+ 0,
240
+ 98,
241
+ 2,
242
+ 1
243
+ ],
244
+ [
245
+ 0,
246
+ 22,
247
+ 2,
248
+ 2
249
+ ],
250
+ [
251
+ 0,
252
+ 6,
253
+ 0,
254
+ 5
255
+ ]
256
+ ]
257
+ }
258
+ }
259
+ },
260
+ "evidence": {
261
+ "overall": {
262
+ "micro": {
263
+ "precision": 0.5655737704918032,
264
+ "recall": 0.6,
265
+ "f1": 0.5822784810126581,
266
+ "tp": 69,
267
+ "fp": 53,
268
+ "fn": 46
269
+ },
270
+ "macro_nonempty_gold": {
271
+ "precision": 0.6040740740740741,
272
+ "recall": 0.6435185185185185,
273
+ "f1": 0.6076719576719577,
274
+ "n_records": 90
275
+ },
276
+ "empty_gold": {
277
+ "n_records": 116,
278
+ "model_also_empty": 102,
279
+ "agreement_rate": 0.8793103448275862
280
+ }
281
+ },
282
+ "inclusion": {
283
+ "micro": {
284
+ "precision": 0.6153846153846154,
285
+ "recall": 0.7164179104477612,
286
+ "f1": 0.6620689655172414,
287
+ "tp": 48,
288
+ "fp": 30,
289
+ "fn": 19
290
+ },
291
+ "macro_nonempty_gold": {
292
+ "precision": 0.7206666666666667,
293
+ "recall": 0.7883333333333333,
294
+ "f1": 0.7304761904761904,
295
+ "n_records": 50
296
+ },
297
+ "empty_gold": {
298
+ "n_records": 16,
299
+ "model_also_empty": 11,
300
+ "agreement_rate": 0.6875
301
+ }
302
+ },
303
+ "exclusion": {
304
+ "micro": {
305
+ "precision": 0.4772727272727273,
306
+ "recall": 0.4375,
307
+ "f1": 0.45652173913043476,
308
+ "tp": 21,
309
+ "fp": 23,
310
+ "fn": 27
311
+ },
312
+ "macro_nonempty_gold": {
313
+ "precision": 0.4583333333333333,
314
+ "recall": 0.4625,
315
+ "f1": 0.4541666666666666,
316
+ "n_records": 40
317
+ },
318
+ "empty_gold": {
319
+ "n_records": 100,
320
+ "model_also_empty": 91,
321
+ "agreement_rate": 0.91
322
+ }
323
+ }
324
+ },
325
+ "valid_json_rate": 1.0,
326
+ "settings": {
327
+ "decoding": "greedy (argmax), HF forward + explicit DynamicCache loop",
328
+ "max_new_tokens": 48,
329
+ "prompt": "trialscreen.data.build_messages + Qwen chat template",
330
+ "env": {
331
+ "python": "3.13.16",
332
+ "torch": "2.11.0+cu130",
333
+ "transformers": "5.22.2",
334
+ "cuda": true,
335
+ "gpu": "Tesla T4",
336
+ "gpu_mem_gb": 14.6
337
+ },
338
+ "model": "Qwen/Qwen2.5-1.5B-Instruct",
339
+ "adapter": "/kaggle/working/trialscreen/checkpoints/qwen2.5-1.5b-trialscreen-lora/best_adapter",
340
+ "minutes": 2.0213489651679994
341
+ }
342
+ }
modeling.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Model loading, prompt tokenisation and criterion-level prediction."""
2
+ from __future__ import annotations
3
+ import time
4
+ import torch
5
+ from .data import build_messages, target_json, split_sentences
6
+ from .parsing import parse_output
7
+ from .decoding import ExplicitQwen2Decoder, HFCacheDecoder, greedy_cached, greedy_nocache
8
+ from .explain import explain
9
+
10
+ TARGET_ID = "Qwen/Qwen2.5-1.5B-Instruct"
11
+ DRAFT_ID = "Qwen/Qwen2.5-0.5B-Instruct"
12
+
13
+
14
+ def pick_device():
15
+ return "cuda" if torch.cuda.is_available() else "cpu"
16
+
17
+
18
+ def pick_dtype(device):
19
+ """bf16 only on GPUs with native support (compute capability >= 8, e.g. A100/L4).
20
+ On a T4 (7.5) torch.cuda.is_bf16_supported() can return True because bf16 is
21
+ *emulated*, which is several times slower than fp16, so we use fp16 there."""
22
+ if device == "cuda":
23
+ major, _ = torch.cuda.get_device_capability()
24
+ return torch.bfloat16 if major >= 8 else torch.float16
25
+ return torch.float32
26
+
27
+
28
+ def load_model(model_id=TARGET_ID, adapter=None, device=None, dtype=None, merge=True):
29
+ """Load tokenizer + causal LM. If `adapter` (local dir or Hub id) is given, apply the
30
+ LoRA adapter and, by default, merge it into the base weights so the explicit decoder
31
+ sees ordinary Linear layers."""
32
+ from transformers import AutoTokenizer, AutoModelForCausalLM
33
+ device = device or pick_device()
34
+ dtype = dtype or pick_dtype(device)
35
+ tok = AutoTokenizer.from_pretrained(model_id)
36
+ model = AutoModelForCausalLM.from_pretrained(model_id, dtype=dtype).to(device).eval()
37
+ if adapter:
38
+ from peft import PeftModel
39
+ model = PeftModel.from_pretrained(model, adapter)
40
+ if merge:
41
+ model = model.merge_and_unload()
42
+ model.eval()
43
+ return tok, model
44
+
45
+
46
+ def eos_ids(tok):
47
+ ids = {tok.eos_token_id}
48
+ for t in ("<|im_end|>", "<|endoftext|>"):
49
+ i = tok.convert_tokens_to_ids(t)
50
+ if isinstance(i, int) and i >= 0:
51
+ ids.add(i)
52
+ return tuple(i for i in ids if i is not None)
53
+
54
+
55
+ def prompt_ids(tok, note_numbered, criterion_type, criterion_text):
56
+ msgs = build_messages(note_numbered, criterion_type, criterion_text)
57
+ text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
58
+ return tok(text, add_special_tokens=False).input_ids
59
+
60
+
61
+ def train_example(tok, rec, max_len=1536):
62
+ """prompt ids + target ids; loss only on target tokens (labels -100 on the prompt).
63
+ Truncation is never silent: an example longer than max_len raises, because cutting
64
+ the note could remove annotated evidence sentences."""
65
+ p = prompt_ids(tok, rec.note, rec.criterion_type, rec.criterion_text)
66
+ t = tok(target_json(rec.label, rec.evidence) + "<|im_end|>", add_special_tokens=False).input_ids
67
+ if len(p) + len(t) > max_len:
68
+ raise ValueError(f"annotation {rec.annotation_id}: {len(p) + len(t)} tokens > max_len {max_len}")
69
+ return {"input_ids": p + t, "labels": [-100] * len(p) + t, "prompt_len": len(p), "target_len": len(t)}
70
+
71
+
72
+ def make_decoder(model, mode="hf_cache", attn_backend="reference"):
73
+ if mode.startswith("explicit"):
74
+ return ExplicitQwen2Decoder(model, attn_backend=attn_backend)
75
+ return HFCacheDecoder(model)
76
+
77
+
78
+ @torch.no_grad()
79
+ def predict_one(tok, model, note, criterion_type, criterion_text, mode="hf_cache",
80
+ attn_backend="reference", max_new_tokens=48, draft_model=None, k=4, decoder=None,
81
+ draft_decoder=None):
82
+ """mode: hf_cache | explicit_cache | explicit_nocache | speculative"""
83
+ sents = split_sentences(note)
84
+ numbered = "\n".join(f"{i}. {s}" for i, s in sents)
85
+ ids = torch.tensor([prompt_ids(tok, numbered, criterion_type, criterion_text)], device=model.device)
86
+ eos = eos_ids(tok)
87
+ t0 = time.perf_counter()
88
+ extra = {}
89
+ if mode == "speculative":
90
+ from .speculative import speculative_greedy
91
+ tgt = decoder or ExplicitQwen2Decoder(model, attn_backend=attn_backend)
92
+ dr = draft_decoder or ExplicitQwen2Decoder(draft_model, attn_backend=attn_backend)
93
+ st = speculative_greedy(tgt, dr, ids, max_new_tokens, k=k, eos_ids=eos)
94
+ extra = st.as_dict()
95
+ else:
96
+ dec = decoder or make_decoder(model, mode, attn_backend)
97
+ fn = greedy_nocache if mode.endswith("nocache") else greedy_cached
98
+ st = fn(dec, ids, max_new_tokens, eos_ids=eos)
99
+ extra = st.as_dict()
100
+ text = tok.decode([t for t in st.tokens if t not in eos], skip_special_tokens=True)
101
+ parsed = parse_output(text, criterion_type, len(sents))
102
+ sent_map = dict(sents)
103
+ return {
104
+ "criterion_type": criterion_type, "criterion_text": criterion_text,
105
+ "label": parsed["label"], "evidence": parsed["evidence"],
106
+ "evidence_text": [sent_map[i] for i in parsed["evidence"]],
107
+ "explanation": explain(criterion_type, criterion_text, parsed["label"], parsed["evidence"], sent_map),
108
+ "raw_output": text, "valid_json": parsed["valid_json"], "parse_notes": parsed["notes"],
109
+ "prompt_tokens": ids.shape[1], "latency_s": time.perf_counter() - t0, "decode": extra,
110
+ }
parsing.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Robust parsing of the model's JSON answer into (label, evidence ids)."""
2
+ from __future__ import annotations
3
+ import json, re
4
+ from .labels import labels_for, INVALID
5
+
6
+ _JSON_RE = re.compile(r"\{.*?\}", re.S)
7
+
8
+
9
+ def parse_output(text: str, criterion_type: str, n_sentences: int) -> dict:
10
+ """Returns dict(label, evidence, valid_json, notes). Never invents a label:
11
+ unparseable output becomes INVALID and is counted as an error in evaluation."""
12
+ allowed = labels_for(criterion_type)
13
+ notes = []
14
+ obj = None
15
+ for m in _JSON_RE.finditer(text):
16
+ try:
17
+ obj = json.loads(m.group(0))
18
+ break
19
+ except json.JSONDecodeError:
20
+ continue
21
+ label, evidence, valid = INVALID, [], obj is not None
22
+ if obj is not None:
23
+ lab = str(obj.get("label", "")).strip().lower()
24
+ if lab in allowed:
25
+ label = lab
26
+ else:
27
+ notes.append(f"label '{lab}' not allowed for {criterion_type}")
28
+ ev = obj.get("evidence", [])
29
+ if isinstance(ev, list):
30
+ for e in ev:
31
+ try:
32
+ e = int(e)
33
+ except (TypeError, ValueError):
34
+ notes.append(f"non-integer evidence id {e!r} dropped")
35
+ continue
36
+ if 0 <= e < n_sentences:
37
+ evidence.append(e)
38
+ else:
39
+ notes.append(f"out-of-range evidence id {e} dropped")
40
+ else:
41
+ # last resort: an exact allowed label string in free text (longest first so
42
+ # 'not included' is not read as 'included'); still flagged as invalid JSON
43
+ for lab in sorted(allowed, key=len, reverse=True):
44
+ if re.search(r"\b" + re.escape(lab) + r"\b", text.lower()):
45
+ label = lab
46
+ notes.append("label recovered from non-JSON text")
47
+ break
48
+ return {"label": label, "evidence": sorted(set(evidence)), "valid_json": valid, "notes": notes}
predictions_base_test.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
predictions_base_validation.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
predictions_finetuned_test.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
predictions_finetuned_validation.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
pytest_gpu_env.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ ................................................... [100%]
2
+ 51 passed in 13.60s
pytest_output.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ ................................................... [100%]
2
+ 51 passed in 5.88s
real_qwen0.5b_explicit_decoder_check.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "Qwen/Qwen2.5-0.5B-Instruct",
3
+ "dtype": "float32",
4
+ "device": "cpu",
5
+ "prompt_tokens": 331,
6
+ "max_abs_logit_diff_vs_hf": {
7
+ "reference": 0.0001697540283203125,
8
+ "tiled": 0.00021457672119140625,
9
+ "torch_sdpa": 0.0
10
+ },
11
+ "greedy_tokens_equal": true,
12
+ "output": "```json\n{\n \"evidence\": [0, 1, 2, 3, 4,",
13
+ "hf_nocache_s": 61.72511977699992,
14
+ "explicit_cache_tiled_s": 7.153236164999953,
15
+ "hf_cache_s": 6.691241931999912
16
+ }
report_export.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Readable, self-contained HTML screening report with provenance."""
2
+ from __future__ import annotations
3
+ import hashlib, html, json, datetime
4
+ from . import __version__
5
+
6
+ DISCLAIMER = ("Educational screening prototype for a university assignment. It is NOT a clinical "
7
+ "enrollment decision tool and must not be used to include or exclude real patients.")
8
+
9
+ _COL = {"included": "#1b7350", "not excluded": "#1b7350", "not included": "#b42318", "excluded": "#b42318",
10
+ "not enough information": "#8a5a00", "not applicable": "#555", "invalid output": "#b42318"}
11
+
12
+
13
+ def provenance(note, criteria, settings):
14
+ blob = json.dumps({"note": note, "criteria": criteria}, sort_keys=True).encode()
15
+ return {"generated_utc": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"),
16
+ "app_version": __version__, "input_sha256": hashlib.sha256(blob).hexdigest(), **settings}
17
+
18
+
19
+ def html_report(trial_name, sentences, results, verdict, prov):
20
+ e = html.escape
21
+ rows = []
22
+ for i, r in enumerate(results, 1):
23
+ ev = "<br>".join(f"<b>[{sid}]</b> {e(t)}" for sid, t in zip(r["evidence"], r["evidence_text"])) or "<i>none cited</i>"
24
+ rows.append(f"<tr><td>{i}</td><td>{e(r['criterion_type'])}</td><td>{e(r['criterion_text'])}</td>"
25
+ f"<td style='color:{_COL.get(r['label'], '#000')};font-weight:700'>{e(r['label'])}</td>"
26
+ f"<td>{ev}</td><td>{e(r['explanation'])}</td></tr>")
27
+ note = "".join(f"<li value='{i}'>{e(s)}</li>" for i, s in sentences)
28
+ missing = [r for r in results if r["label"] == "not enough information"]
29
+ miss = "".join(f"<li>{e(r['criterion_text'])}</li>" for r in missing) or "<li>None</li>"
30
+ return f"""<!doctype html><html lang="en"><meta charset="utf-8"><title>Eligibility screening report</title>
31
+ <style>body{{font-family:system-ui,Arial,sans-serif;max-width:1000px;margin:24px auto;padding:0 16px;color:#1c1a33;line-height:1.5}}
32
+ .warn{{background:#fff4e5;border:2px solid #8a5a00;border-radius:10px;padding:10px 14px}}
33
+ table{{border-collapse:collapse;width:100%;font-size:14px}}td,th{{border:1px solid #ccd;padding:6px;vertical-align:top;text-align:left}}
34
+ th{{background:#eef2fb}}ol li{{margin-bottom:4px}}code{{font-size:12px}}</style>
35
+ <h1>Eligibility screening report</h1><p class="warn"><b>Notice:</b> {e(DISCLAIMER)}</p>
36
+ <h2>Trial</h2><p>{e(trial_name or 'Unnamed trial')}</p>
37
+ <h2>Preliminary outcome (rule-based aggregation)</h2><p><b>{e(verdict['verdict'])}</b> &mdash; {verdict['n_criteria']} criteria,
38
+ {verdict['n_blocking']} blocking, {verdict['n_unknown']} undetermined.<br><small>Rule: {e(verdict['rule'])} This aggregation is not a
39
+ ground-truth label; the dataset only labels individual criteria.</small></p>
40
+ <h2>Missing information</h2><ul>{miss}</ul>
41
+ <h2>Criterion-level results</h2><table><tr><th>#</th><th>Type</th><th>Criterion</th><th>Prediction</th><th>Evidence (sentence ID)</th><th>Explanation</th></tr>
42
+ {''.join(rows)}</table>
43
+ <h2>Patient record (sentence IDs)</h2><ol start="0">{note}</ol>
44
+ <h2>Provenance</h2><pre><code>{e(json.dumps(prov, indent=1))}</code></pre></html>"""
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tested versions (CPU tests in this repo were run with exactly these)
2
+ torch>=2.3
3
+ transformers==5.22.2
4
+ peft==0.21.2
5
+ accelerate==1.15.0
6
+ huggingface_hub>=0.34
7
+ datasets>=3.0
8
+ pandas>=2.2
9
+ numpy>=1.26
10
+ scikit-learn>=1.4
11
+ matplotlib>=3.8
12
+ gradio>=5.0
13
+ pytest>=8.0
space_README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: TrialScreen
3
+ emoji: 🩺
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: "6.31.0"
8
+ app_file: app/app.py
9
+ pinned: false
10
+ license: mit
11
+ ---
12
+ # TrialScreen (educational prototype)
13
+ Criterion-level clinical trial eligibility screening with evidence citations.
14
+ Not a clinical enrollment decision tool.
speculative.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Task 5: greedy speculative decoding (Leviathan et al. 2023; Chen et al. 2023), greedy case.
2
+
3
+ Invariant kept between rounds (both models):
4
+ seq = prompt + generated tokens.
5
+ target cache holds K/V for seq[:-1] (everything except the newest token)
6
+ draft cache holds K/V for a prefix of seq[:-1]; missing tokens are fed before drafting.
7
+
8
+ One round with lookahead k:
9
+ 1. Draft: feed the tokens the draft has not processed yet (ends with seq[-1]) and take
10
+ argmax; then feed each drafted token to get the next, producing d_1..d_k.
11
+ 2. Verify: ONE target forward on [seq[-1], d_1, ..., d_k] (k+1 tokens). Its argmaxes
12
+ p_0..p_k are what plain greedy target decoding would produce after seq, seq+d_1, ...
13
+ 3. Accept the longest prefix with d_i == p_{i-1}; say n tokens. Append d_1..d_n and then
14
+ p_n (the target's correction on the first mismatch, or a free "bonus" token if all
15
+ k drafts were accepted). Every emitted token is a target argmax, so the output equals
16
+ greedy target decoding token for token (up to floating-point ties, see report).
17
+ 4. Roll back: crop the target cache to len(seq_new) - 1 and the draft cache to at most
18
+ that length, discarding K/V written for rejected draft tokens.
19
+ """
20
+ from __future__ import annotations
21
+ import time
22
+ from dataclasses import dataclass, field
23
+ import torch
24
+ from .decoding import sync, reset_peak, peak_mem_mb
25
+
26
+
27
+ @dataclass
28
+ class SpecStats:
29
+ tokens: list = field(default_factory=list)
30
+ rounds: int = 0
31
+ drafted: int = 0
32
+ accepted: int = 0
33
+ accepted_per_round: list = field(default_factory=list)
34
+ target_forwards: int = 0
35
+ draft_forwards: int = 0
36
+ prefill_s: float = 0.0
37
+ total_s: float = 0.0
38
+ peak_mem_mb: float | None = None
39
+
40
+ @property
41
+ def acceptance_rate(self):
42
+ return self.accepted / self.drafted if self.drafted else 0.0
43
+
44
+ @property
45
+ def tokens_per_round(self):
46
+ return len(self.tokens) / self.rounds if self.rounds else 0.0
47
+
48
+ def as_dict(self):
49
+ return {"new_tokens": len(self.tokens), "rounds": self.rounds, "drafted": self.drafted,
50
+ "accepted": self.accepted, "acceptance_rate": self.acceptance_rate,
51
+ "tokens_per_round": self.tokens_per_round, "target_forwards": self.target_forwards,
52
+ "draft_forwards": self.draft_forwards, "prefill_s": self.prefill_s, "total_s": self.total_s,
53
+ "tokens_per_s": len(self.tokens) / self.total_s if self.total_s else None,
54
+ "peak_mem_mb": self.peak_mem_mb}
55
+
56
+
57
+ @torch.no_grad()
58
+ def speculative_greedy(target, draft, prompt_ids: torch.Tensor, max_new_tokens: int, k: int = 4, eos_ids=()):
59
+ device = prompt_ids.device
60
+ target.reset(); draft.reset(); reset_peak(device)
61
+ st = SpecStats()
62
+ sync(device); t0 = time.perf_counter()
63
+ # prefill both models on the prompt; the target's last logit gives the first token
64
+ logits = target.forward(prompt_ids, logits_to_keep=1); st.target_forwards += 1
65
+ draft.forward(prompt_ids[:, :-1], logits_to_keep=1) if prompt_ids.shape[1] > 1 else None
66
+ st.draft_forwards += 1
67
+ seq = prompt_ids[0].tolist()
68
+ first = int(logits[0, -1].argmax())
69
+ seq.append(first); st.tokens.append(first)
70
+ # the target already holds K/V for the whole prompt, i.e. seq[:-1]: invariant holds
71
+ sync(device); st.prefill_s = time.perf_counter() - t0
72
+
73
+ while len(st.tokens) < max_new_tokens and st.tokens[-1] not in eos_ids:
74
+ k_eff = min(k, max_new_tokens - len(st.tokens))
75
+ # ---- 1. draft k tokens
76
+ pending = seq[draft.cache_len:] # tokens draft has not processed (ends with seq[-1])
77
+ dl = draft.forward(torch.tensor([pending], device=device), logits_to_keep=1); st.draft_forwards += 1
78
+ drafts = [int(dl[0, -1].argmax())]
79
+ while len(drafts) < k_eff and drafts[-1] not in eos_ids:
80
+ dl = draft.forward(torch.tensor([[drafts[-1]]], device=device)); st.draft_forwards += 1
81
+ drafts.append(int(dl[0, -1].argmax()))
82
+ # ---- 2. verify with ONE target pass over [seq[-1], d_1..d_k]
83
+ base = len(seq) - 1 # == target.cache_len
84
+ assert target.cache_len == base, (target.cache_len, base)
85
+ tl = target.forward(torch.tensor([[seq[-1]] + drafts], device=device)); st.target_forwards += 1
86
+ preds = tl[0].argmax(-1).tolist() # p_0..p_k
87
+ # ---- 3. accept the longest matching prefix, then add the target's own next token
88
+ n = 0
89
+ while n < len(drafts) and drafts[n] == preds[n]:
90
+ n += 1
91
+ new = drafts[:n] + [preds[n]]
92
+ st.rounds += 1; st.drafted += len(drafts); st.accepted += n; st.accepted_per_round.append(n)
93
+ for tok in new:
94
+ seq.append(tok); st.tokens.append(tok)
95
+ if tok in eos_ids or len(st.tokens) >= max_new_tokens:
96
+ break
97
+ # ---- 4. roll caches back to seq[:-1]
98
+ target.crop(len(seq) - 1)
99
+ draft.crop(min(draft.cache_len, len(seq) - 1))
100
+ sync(device); st.total_s = time.perf_counter() - t0
101
+ st.peak_mem_mb = peak_mem_mb(device)
102
+ st.tokens = st.tokens[:max_new_tokens]
103
+ return st
token_length_stats.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train": {
3
+ "n": 602,
4
+ "total_max": 610,
5
+ "total_mean": 314.8,
6
+ "prompt_max": 584,
7
+ "target_max": 38,
8
+ "target_mean": 14.8,
9
+ "truncated": 0
10
+ },
11
+ "validation": {
12
+ "n": 206,
13
+ "total_max": 444,
14
+ "total_mean": 327.5,
15
+ "prompt_max": 422,
16
+ "target_max": 25,
17
+ "target_mean": 14.3,
18
+ "truncated": 0
19
+ },
20
+ "test": {
21
+ "n": 206,
22
+ "total_max": 504,
23
+ "total_mean": 297.7,
24
+ "prompt_max": 488,
25
+ "target_max": 28,
26
+ "target_mean": 14.3,
27
+ "truncated": 0
28
+ }
29
+ }
train.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LoRA supervised fine-tuning with a plain PyTorch loop (transparent and easy to defend).
2
+
3
+ Objective: next-token cross-entropy on the assistant answer only
4
+ L = - (1/|A|) * sum_{t in A} log p_theta(y_t | y_<t, prompt)
5
+ where A are the target JSON tokens; prompt tokens are masked with label -100.
6
+ Only the low-rank matrices B (d x r) and A (r x k) of each adapted projection are
7
+ trained: W' = W + (alpha / r) * B A (Hu et al., 2022).
8
+ """
9
+ from __future__ import annotations
10
+ import json, math, random, time
11
+ from pathlib import Path
12
+ import torch
13
+ from .modeling import train_example
14
+
15
+
16
+ def collate(batch, pad_id):
17
+ L = max(len(b["input_ids"]) for b in batch)
18
+ ids = torch.full((len(batch), L), pad_id, dtype=torch.long)
19
+ lab = torch.full((len(batch), L), -100, dtype=torch.long)
20
+ att = torch.zeros((len(batch), L), dtype=torch.long)
21
+ for i, b in enumerate(batch): # right padding
22
+ n = len(b["input_ids"])
23
+ ids[i, :n] = torch.tensor(b["input_ids"]); lab[i, :n] = torch.tensor(b["labels"]); att[i, :n] = 1
24
+ return ids, lab, att
25
+
26
+
27
+ @torch.no_grad()
28
+ def eval_loss(model, examples, pad_id, bs, device):
29
+ model.eval(); tot, n = 0.0, 0
30
+ for i in range(0, len(examples), bs):
31
+ ids, lab, att = collate(examples[i:i + bs], pad_id)
32
+ ids, lab, att = ids.to(device), lab.to(device), att.to(device)
33
+ with torch.autocast(device_type="cuda", dtype=torch.float16, enabled=device == "cuda"):
34
+ out = model(input_ids=ids, attention_mask=att, labels=lab)
35
+ ntok = int((lab[:, 1:] != -100).sum())
36
+ tot += float(out.loss) * ntok; n += ntok
37
+ model.train()
38
+ return tot / max(n, 1)
39
+
40
+
41
+ def train_lora(cfg: dict, train_recs, val_recs, out_dir, log=print, val_eval_fn=None):
42
+ from transformers import AutoTokenizer, AutoModelForCausalLM, get_cosine_schedule_with_warmup
43
+ from peft import LoraConfig, get_peft_model
44
+ torch.manual_seed(cfg["seed"]); random.seed(cfg["seed"])
45
+ device = "cuda" if torch.cuda.is_available() else "cpu"
46
+ out_dir = Path(out_dir); out_dir.mkdir(parents=True, exist_ok=True)
47
+ tok = AutoTokenizer.from_pretrained(cfg["model_id"])
48
+ pad_id = tok.pad_token_id if tok.pad_token_id is not None else tok.eos_token_id
49
+ # fp32 master weights + fp16 autocast: T4/P100 have no bf16, and fp16 LoRA params
50
+ # cannot be unscaled by GradScaler. 1.5B params * 4 B = ~6.2 GB, fits a 16 GB T4.
51
+ model = AutoModelForCausalLM.from_pretrained(cfg["model_id"], dtype=torch.float32).to(device)
52
+ if cfg.get("gradient_checkpointing", True):
53
+ model.gradient_checkpointing_enable()
54
+ model.enable_input_require_grads()
55
+ lcfg = LoraConfig(r=cfg["lora_r"], lora_alpha=cfg["lora_alpha"], lora_dropout=cfg["lora_dropout"],
56
+ target_modules=cfg["target_modules"], task_type="CAUSAL_LM", bias="none")
57
+ model = get_peft_model(model, lcfg)
58
+ trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
59
+ total = sum(p.numel() for p in model.parameters())
60
+ log(f"trainable params {trainable:,} / {total:,} ({100 * trainable / total:.3f}%)")
61
+
62
+ tr = [train_example(tok, r, cfg["max_len"]) for r in train_recs]
63
+ va = [train_example(tok, r, cfg["max_len"]) for r in val_recs]
64
+ stats = {"train_max_tokens": max(len(e["input_ids"]) for e in tr),
65
+ "val_max_tokens": max(len(e["input_ids"]) for e in va), "truncated_examples": 0}
66
+ log(f"token stats {stats}")
67
+
68
+ opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad],
69
+ lr=cfg["lr"], weight_decay=cfg["weight_decay"])
70
+ steps_per_epoch = math.ceil(len(tr) / (cfg["batch_size"] * cfg["grad_accum"]))
71
+ total_steps = steps_per_epoch * cfg["epochs"]
72
+ sched = get_cosine_schedule_with_warmup(opt, int(cfg["warmup_ratio"] * total_steps), total_steps)
73
+ scaler = torch.amp.GradScaler("cuda", enabled=device == "cuda")
74
+ history = {"step": [], "train_loss": [], "lr": [], "epoch_end": []}
75
+ best, step = None, 0
76
+ model.train(); t0 = time.time()
77
+ for epoch in range(cfg["epochs"]):
78
+ random.shuffle(tr)
79
+ for b0 in range(0, len(tr), cfg["batch_size"] * cfg["grad_accum"]):
80
+ chunk = tr[b0:b0 + cfg["batch_size"] * cfg["grad_accum"]]
81
+ run = 0.0
82
+ for m0 in range(0, len(chunk), cfg["batch_size"]):
83
+ ids, lab, att = collate(chunk[m0:m0 + cfg["batch_size"]], pad_id)
84
+ ids, lab, att = ids.to(device), lab.to(device), att.to(device)
85
+ with torch.autocast(device_type="cuda", dtype=torch.float16, enabled=device == "cuda"):
86
+ loss = model(input_ids=ids, attention_mask=att, labels=lab).loss
87
+ scaler.scale(loss * len(ids) / len(chunk)).backward()
88
+ run += loss.detach().item() * len(ids) / len(chunk)
89
+ scaler.unscale_(opt)
90
+ torch.nn.utils.clip_grad_norm_([p for p in model.parameters() if p.requires_grad], cfg["max_grad_norm"])
91
+ scaler.step(opt); scaler.update(); opt.zero_grad(set_to_none=True); sched.step()
92
+ step += 1
93
+ history["step"].append(step); history["train_loss"].append(run); history["lr"].append(sched.get_last_lr()[0])
94
+ if step % cfg["log_every"] == 0:
95
+ log(f"epoch {epoch + 1} step {step}/{total_steps} loss {run:.4f} lr {sched.get_last_lr()[0]:.2e} "
96
+ f"elapsed {time.time() - t0:.0f}s")
97
+ vloss = eval_loss(model, va, pad_id, cfg["batch_size"], device)
98
+ rec = {"epoch": epoch + 1, "step": step, "val_loss": vloss}
99
+ if val_eval_fn is not None: # label/evidence metrics on the VALIDATION split only
100
+ rec.update(val_eval_fn(model, tok))
101
+ history["epoch_end"].append(rec)
102
+ log(f"== epoch {epoch + 1} {rec}")
103
+ score = rec.get(cfg["select_metric"], -vloss)
104
+ if best is None or score > best[0]:
105
+ best = (score, epoch + 1)
106
+ model.save_pretrained(out_dir / "best_adapter"); tok.save_pretrained(out_dir / "best_adapter")
107
+ log(f"saved best adapter (epoch {epoch + 1}, {cfg['select_metric']}={score:.4f})")
108
+ model.save_pretrained(out_dir / "last_adapter")
109
+ meta = {"config": cfg, "token_stats": stats, "trainable_params": trainable, "total_params": total,
110
+ "best_epoch": best[1], "best_score": best[0], "train_minutes": (time.time() - t0) / 60,
111
+ "gpu": torch.cuda.get_device_name(0) if device == "cuda" else "cpu",
112
+ "peak_mem_gb": torch.cuda.max_memory_allocated() / 2**30 if device == "cuda" else None}
113
+ json.dump(history, open(out_dir / "history.json", "w"), indent=1)
114
+ json.dump(meta, open(out_dir / "train_meta.json", "w"), indent=1)
115
+ return out_dir / "best_adapter", history, meta
train_history.json ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "step": [
3
+ 1,
4
+ 2,
5
+ 3,
6
+ 4,
7
+ 5,
8
+ 6,
9
+ 7,
10
+ 8,
11
+ 9,
12
+ 10,
13
+ 11,
14
+ 12,
15
+ 13,
16
+ 14,
17
+ 15,
18
+ 16,
19
+ 17,
20
+ 18,
21
+ 19,
22
+ 20,
23
+ 21,
24
+ 22,
25
+ 23,
26
+ 24,
27
+ 25,
28
+ 26,
29
+ 27,
30
+ 28,
31
+ 29,
32
+ 30,
33
+ 31,
34
+ 32,
35
+ 33,
36
+ 34,
37
+ 35,
38
+ 36,
39
+ 37,
40
+ 38,
41
+ 39,
42
+ 40,
43
+ 41,
44
+ 42,
45
+ 43,
46
+ 44,
47
+ 45,
48
+ 46,
49
+ 47,
50
+ 48,
51
+ 49,
52
+ 50,
53
+ 51,
54
+ 52,
55
+ 53,
56
+ 54,
57
+ 55,
58
+ 56,
59
+ 57,
60
+ 58,
61
+ 59,
62
+ 60,
63
+ 61,
64
+ 62,
65
+ 63,
66
+ 64,
67
+ 65,
68
+ 66,
69
+ 67,
70
+ 68,
71
+ 69,
72
+ 70,
73
+ 71,
74
+ 72,
75
+ 73,
76
+ 74,
77
+ 75,
78
+ 76,
79
+ 77,
80
+ 78,
81
+ 79,
82
+ 80,
83
+ 81,
84
+ 82,
85
+ 83,
86
+ 84,
87
+ 85,
88
+ 86,
89
+ 87,
90
+ 88,
91
+ 89,
92
+ 90,
93
+ 91,
94
+ 92,
95
+ 93,
96
+ 94,
97
+ 95,
98
+ 96,
99
+ 97,
100
+ 98,
101
+ 99,
102
+ 100,
103
+ 101,
104
+ 102,
105
+ 103,
106
+ 104,
107
+ 105,
108
+ 106,
109
+ 107,
110
+ 108,
111
+ 109,
112
+ 110,
113
+ 111,
114
+ 112,
115
+ 113,
116
+ 114
117
+ ],
118
+ "train_loss": [
119
+ 0.4009213224053383,
120
+ 0.4356626123189926,
121
+ 0.24739471450448036,
122
+ 0.2628834433853626,
123
+ 0.25149342603981495,
124
+ 0.14134853333234787,
125
+ 0.1799704171717167,
126
+ 0.1406576931476593,
127
+ 0.1876185368746519,
128
+ 0.19509727507829666,
129
+ 0.15732389502227306,
130
+ 0.14001024514436722,
131
+ 0.163081094622612,
132
+ 0.11599132977426052,
133
+ 0.15474559739232063,
134
+ 0.07404879783280194,
135
+ 0.1072159237228334,
136
+ 0.16655178647488356,
137
+ 0.13065406866371632,
138
+ 0.1397935887798667,
139
+ 0.12088210508227348,
140
+ 0.1548105850815773,
141
+ 0.17122196778655052,
142
+ 0.08415172807872295,
143
+ 0.09750973526388407,
144
+ 0.16202368587255478,
145
+ 0.09985598921775818,
146
+ 0.12572021735832095,
147
+ 0.13054070621728897,
148
+ 0.0735541582107544,
149
+ 0.12370543740689754,
150
+ 0.14253276120871305,
151
+ 0.12904429249465466,
152
+ 0.11229122616350651,
153
+ 0.10500960610806942,
154
+ 0.18387718871235847,
155
+ 0.15781394019722939,
156
+ 0.176671888679266,
157
+ 0.13394544273614883,
158
+ 0.10111173614859581,
159
+ 0.10200703609734774,
160
+ 0.09599873889237642,
161
+ 0.09581917244940996,
162
+ 0.1381429573521018,
163
+ 0.09200653061270714,
164
+ 0.0842802170664072,
165
+ 0.16479041799902916,
166
+ 0.03867637598887086,
167
+ 0.07615121779963374,
168
+ 0.04861171846278012,
169
+ 0.12317687086760998,
170
+ 0.08672586921602488,
171
+ 0.07456093840301037,
172
+ 0.09419303014874458,
173
+ 0.07848863303661346,
174
+ 0.11383408308029175,
175
+ 0.1453498713672161,
176
+ 0.06793265696614981,
177
+ 0.08266809303313494,
178
+ 0.06585963675752282,
179
+ 0.08180795656517148,
180
+ 0.14915944822132587,
181
+ 0.07452373672276735,
182
+ 0.10417094640433788,
183
+ 0.11117601254954934,
184
+ 0.05965271219611168,
185
+ 0.10251081362366676,
186
+ 0.0676209693774581,
187
+ 0.10703021753579378,
188
+ 0.07455856213346124,
189
+ 0.06584312301129103,
190
+ 0.020379768451675773,
191
+ 0.0995538979768753,
192
+ 0.060517242178320885,
193
+ 0.06484812055714428,
194
+ 0.09679802618920802,
195
+ 0.06960235675796866,
196
+ 0.07900979230180383,
197
+ 0.08489947812631726,
198
+ 0.057480307295918465,
199
+ 0.07472224393859506,
200
+ 0.04891157383099198,
201
+ 0.08139736391603947,
202
+ 0.06981713697314262,
203
+ 0.05822281423024833,
204
+ 0.052100476110354066,
205
+ 0.08593662176281214,
206
+ 0.04813444905448705,
207
+ 0.06911342311650515,
208
+ 0.029686945490539074,
209
+ 0.031877090223133564,
210
+ 0.0495431637391448,
211
+ 0.08743235561996698,
212
+ 0.030736113665625453,
213
+ 0.06560408370569348,
214
+ 0.07265889458358288,
215
+ 0.061189827509224415,
216
+ 0.06873419834300876,
217
+ 0.04155378649011254,
218
+ 0.06401556264609098,
219
+ 0.042576707899570465,
220
+ 0.05810186034068465,
221
+ 0.02648402936756611,
222
+ 0.034046285785734653,
223
+ 0.03499076818116009,
224
+ 0.021376975812017918,
225
+ 0.05800170870497823,
226
+ 0.05681912833824754,
227
+ 0.06435124296694994,
228
+ 0.1368174310773611,
229
+ 0.11840377002954483,
230
+ 0.07787571474909782,
231
+ 0.03229173272848129,
232
+ 0.05375131405889988
233
+ ],
234
+ "lr": [
235
+ 4e-05,
236
+ 8e-05,
237
+ 0.00012,
238
+ 0.00016,
239
+ 0.0002,
240
+ 0.00019995846763238512,
241
+ 0.00019983390502829166,
242
+ 0.00019962641565531692,
243
+ 0.00019933617186395917,
244
+ 0.00019896341474445525,
245
+ 0.0001985084539265195,
246
+ 0.00019797166732215076,
247
+ 0.00019735350081172067,
248
+ 0.0001966544678736044,
249
+ 0.00019587514915766124,
250
+ 0.00019501619200291908,
251
+ 0.0001940783098998643,
252
+ 0.00019306228189778254,
253
+ 0.00019196895195764362,
254
+ 0.0001907992282510675,
255
+ 0.00018955408240595395,
256
+ 0.00018823454869940242,
257
+ 0.0001868417231985926,
258
+ 0.00018537676285033887,
259
+ 0.00018384088452007578,
260
+ 0.00018223536398107176,
261
+ 0.00018056153485471166,
262
+ 0.00017882078750272742,
263
+ 0.00017701456787229804,
264
+ 0.0001751443762949772,
265
+ 0.00017321176624044687,
266
+ 0.00017121834302613186,
267
+ 0.00016916576248374719,
268
+ 0.00016705572958388576,
269
+ 0.00016488999701978903,
270
+ 0.00016267036375147725,
271
+ 0.00016039867351144778,
272
+ 0.0001580768132731837,
273
+ 0.00015570671168374438,
274
+ 0.00015329033746173975,
275
+ 0.00015082969776201947,
276
+ 0.0001483268365084351,
277
+ 0.00014578383269606005,
278
+ 0.00014320279866427796,
279
+ 0.00014058587834217355,
280
+ 0.00013793524546768356,
281
+ 0.00013525310178198705,
282
+ 0.00013254167520063509,
283
+ 0.00012980321796293836,
284
+ 0.0001270400047611508,
285
+ 0.00012425433085100224,
286
+ 0.00012144851014515055,
287
+ 0.00011862487329113606,
288
+ 0.0001157857657354354,
289
+ 0.00011293354577522263,
290
+ 0.00011007058259945584,
291
+ 0.0001071992543209167,
292
+ 0.0001043219460008374,
293
+ 0.00010144104766775572,
294
+ 9.85589523322443e-05,
295
+ 9.567805399916259e-05,
296
+ 9.28007456790833e-05,
297
+ 8.992941740054418e-05,
298
+ 8.706645422477739e-05,
299
+ 8.42142342645646e-05,
300
+ 8.137512670886397e-05,
301
+ 7.855148985484946e-05,
302
+ 7.57456691489978e-05,
303
+ 7.295999523884921e-05,
304
+ 7.019678203706163e-05,
305
+ 6.745832479936491e-05,
306
+ 6.474689821801295e-05,
307
+ 6.206475453231644e-05,
308
+ 5.941412165782645e-05,
309
+ 5.679720133572206e-05,
310
+ 5.421616730394e-05,
311
+ 5.167316349156495e-05,
312
+ 4.917030223798057e-05,
313
+ 4.6709662538260267e-05,
314
+ 4.4293288316255653e-05,
315
+ 4.192318672681631e-05,
316
+ 3.960132648855226e-05,
317
+ 3.732963624852275e-05,
318
+ 3.5110002980210975e-05,
319
+ 3.294427041611425e-05,
320
+ 3.083423751625282e-05,
321
+ 2.878165697386812e-05,
322
+ 2.678823375955314e-05,
323
+ 2.485562370502279e-05,
324
+ 2.2985432127701946e-05,
325
+ 2.1179212497272584e-05,
326
+ 1.9438465145288374e-05,
327
+ 1.776463601892825e-05,
328
+ 1.6159115479924257e-05,
329
+ 1.462323714966114e-05,
330
+ 1.3158276801407431e-05,
331
+ 1.1765451300597573e-05,
332
+ 1.0445917594046072e-05,
333
+ 9.200771748932513e-06,
334
+ 8.031048042356392e-06,
335
+ 6.937718102217461e-06,
336
+ 5.921690100135713e-06,
337
+ 4.983807997080925e-06,
338
+ 4.124850842338779e-06,
339
+ 3.3455321263955786e-06,
340
+ 2.6464991882793278e-06,
341
+ 2.028332677849254e-06,
342
+ 1.4915460734805097e-06,
343
+ 1.036585255544764e-06,
344
+ 6.638281360408339e-07,
345
+ 3.7358434468308667e-07,
346
+ 1.6609497170834155e-07,
347
+ 4.153236761488266e-08,
348
+ 0.0
349
+ ],
350
+ "epoch_end": [
351
+ {
352
+ "epoch": 1,
353
+ "step": 38,
354
+ "val_loss": 0.15514430725111958,
355
+ "val_accuracy": 0.7378640776699029,
356
+ "val_macro_f1": 0.3611307100606074,
357
+ "val_evidence_micro_f1": 0.3968668407310705,
358
+ "val_valid_json_rate": 1.0
359
+ },
360
+ {
361
+ "epoch": 2,
362
+ "step": 76,
363
+ "val_loss": 0.1418227395039621,
364
+ "val_accuracy": 0.7184466019417476,
365
+ "val_macro_f1": 0.35021929824561404,
366
+ "val_evidence_micro_f1": 0.5172413793103448,
367
+ "val_valid_json_rate": 1.0
368
+ },
369
+ {
370
+ "epoch": 3,
371
+ "step": 114,
372
+ "val_loss": 0.13840951449141506,
373
+ "val_accuracy": 0.7427184466019418,
374
+ "val_macro_f1": 0.443793395723245,
375
+ "val_evidence_micro_f1": 0.5822784810126581,
376
+ "val_valid_json_rate": 1.0
377
+ }
378
+ ]
379
+ }
train_log.txt ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"python": "3.13.16", "torch": "2.11.0+cu130", "transformers": "5.22.2", "cuda": true, "gpu": "Tesla T4", "gpu_mem_gb": 14.6}
2
+ trainable params 18,464,768 / 1,562,179,072 (1.182%)
3
+ token stats {'train_max_tokens': 610, 'val_max_tokens': 444, 'truncated_examples': 0}
4
+ epoch 1 step 5/114 loss 0.2515 lr 2.00e-04 elapsed 27s
5
+ epoch 1 step 10/114 loss 0.1951 lr 1.99e-04 elapsed 53s
6
+ epoch 1 step 15/114 loss 0.1547 lr 1.96e-04 elapsed 80s
7
+ epoch 1 step 20/114 loss 0.1398 lr 1.91e-04 elapsed 108s
8
+ epoch 1 step 25/114 loss 0.0975 lr 1.84e-04 elapsed 136s
9
+ epoch 1 step 30/114 loss 0.0736 lr 1.75e-04 elapsed 162s
10
+ epoch 1 step 35/114 loss 0.1050 lr 1.65e-04 elapsed 190s
11
+ == epoch 1 {'epoch': 1, 'step': 38, 'val_loss': 0.15514430725111958, 'val_accuracy': 0.7378640776699029, 'val_macro_f1': 0.3611307100606074, 'val_evidence_micro_f1': 0.3968668407310705, 'val_valid_json_rate': 1.0}
12
+ saved best adapter (epoch 1, val_macro_f1=0.3611)
13
+ epoch 2 step 40/114 loss 0.1011 lr 1.53e-04 elapsed 499s
14
+ epoch 2 step 45/114 loss 0.0920 lr 1.41e-04 elapsed 528s
15
+ epoch 2 step 50/114 loss 0.0486 lr 1.27e-04 elapsed 555s
16
+ epoch 2 step 55/114 loss 0.0785 lr 1.13e-04 elapsed 582s
17
+ epoch 2 step 60/114 loss 0.0659 lr 9.86e-05 elapsed 609s
18
+ epoch 2 step 65/114 loss 0.1112 lr 8.42e-05 elapsed 637s
19
+ epoch 2 step 70/114 loss 0.0746 lr 7.02e-05 elapsed 665s
20
+ epoch 2 step 75/114 loss 0.0648 lr 5.68e-05 elapsed 691s
21
+ == epoch 2 {'epoch': 2, 'step': 76, 'val_loss': 0.1418227395039621, 'val_accuracy': 0.7184466019417476, 'val_macro_f1': 0.35021929824561404, 'val_evidence_micro_f1': 0.5172413793103448, 'val_valid_json_rate': 1.0}
22
+ epoch 3 step 80/114 loss 0.0575 lr 4.43e-05 elapsed 980s
23
+ epoch 3 step 85/114 loss 0.0582 lr 3.29e-05 elapsed 1007s
24
+ epoch 3 step 90/114 loss 0.0297 lr 2.30e-05 elapsed 1033s
25
+ epoch 3 step 95/114 loss 0.0656 lr 1.46e-05 elapsed 1059s
26
+ epoch 3 step 100/114 loss 0.0640 lr 8.03e-06 elapsed 1088s
27
+ epoch 3 step 105/114 loss 0.0350 lr 3.35e-06 elapsed 1115s
28
+ epoch 3 step 110/114 loss 0.1368 lr 6.64e-07 elapsed 1144s
29
+ == epoch 3 {'epoch': 3, 'step': 114, 'val_loss': 0.13840951449141506, 'val_accuracy': 0.7427184466019418, 'val_macro_f1': 0.443793395723245, 'val_evidence_micro_f1': 0.5822784810126581, 'val_valid_json_rate': 1.0}
30
+ saved best adapter (epoch 3, val_macro_f1=0.4438)
31
+ best adapter: /kaggle/working/trialscreen/checkpoints/qwen2.5-1.5b-trialscreen-lora/best_adapter
train_meta.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "config": {
3
+ "model_id": "Qwen/Qwen2.5-1.5B-Instruct",
4
+ "seed": 42,
5
+ "max_len": 1536,
6
+ "lora_r": 16,
7
+ "lora_alpha": 32,
8
+ "lora_dropout": 0.05,
9
+ "target_modules": [
10
+ "q_proj",
11
+ "k_proj",
12
+ "v_proj",
13
+ "o_proj",
14
+ "gate_proj",
15
+ "up_proj",
16
+ "down_proj"
17
+ ],
18
+ "lr": 0.0002,
19
+ "weight_decay": 0.0,
20
+ "warmup_ratio": 0.05,
21
+ "epochs": 3,
22
+ "batch_size": 4,
23
+ "grad_accum": 4,
24
+ "max_grad_norm": 1.0,
25
+ "gradient_checkpointing": true,
26
+ "log_every": 5,
27
+ "select_metric": "val_macro_f1"
28
+ },
29
+ "token_stats": {
30
+ "train_max_tokens": 610,
31
+ "val_max_tokens": 444,
32
+ "truncated_examples": 0
33
+ },
34
+ "trainable_params": 18464768,
35
+ "total_params": 1562179072,
36
+ "best_epoch": 3,
37
+ "best_score": 0.443793395723245,
38
+ "train_minutes": 23.73788732290268,
39
+ "gpu": "Tesla T4",
40
+ "peak_mem_gb": 6.038183689117432
41
+ }