"""Transformer Zero: browser app (Gradio, runs on a Hugging Face ZeroGPU Space or any GPU box). Env vars (defaults are the deployed setup): TZ_TARGET base model (Qwen/Qwen3-4B-Instruct-2507) TZ_ADAPTER LoRA adapter repo (wajih-rathore/transformer-zero), TZ_ADAPTER_DIR subfolder (qwen3-4b-lora); "" = none TZ_DRAFT speculative draft (Qwen/Qwen3-0.6B) """ import datetime as dt import html import os import tempfile import time import gradio as gr import pandas as pd import torch try: import spaces gpu = spaces.GPU except ImportError: # not on a ZeroGPU Space: run functions as they are def gpu(*a, **k): return a[0] if a and callable(a[0]) else (lambda f: f) from tz.data import LABELS, build_messages, load_dataset, note_sentences, parse_output, prompt_text, split_free_text from tz.decoder import Qwen3Decoder, greedy_generate from tz.explain import explanation_messages, template_explanation from tz.speculative import speculative_generate TARGET = os.environ.get("TZ_TARGET", "Qwen/Qwen3-4B-Instruct-2507") ADAPTER = os.environ.get("TZ_ADAPTER", "wajih-rathore/transformer-zero") ADAPTER_DIR = os.environ.get("TZ_ADAPTER_DIR", "qwen3-4b-lora") DRAFT = os.environ.get("TZ_DRAFT", "Qwen/Qwen3-0.6B") MAX_CRITERIA, MAX_NOTE_TOKENS = 30, 3000 NOTICE = "Educational screening prototype only. Not a clinical enrollment decision." from transformers import AutoModelForCausalLM, AutoTokenizer # noqa: E402 dev = "cuda" if torch.cuda.is_available() else "cpu" dtype = torch.bfloat16 if dev == "cuda" else torch.float32 tok = AutoTokenizer.from_pretrained(TARGET) model = AutoModelForCausalLM.from_pretrained(TARGET, dtype=dtype).to(dev).eval() if ADAPTER: from peft import PeftModel model = PeftModel.from_pretrained(model, ADAPTER, subfolder=ADAPTER_DIR).eval() draft_hf = AutoModelForCausalLM.from_pretrained(DRAFT, dtype=dtype).to(dev).eval() dec, draft = Qwen3Decoder(model), Qwen3Decoder(draft_hf) EOS = {tok.convert_tokens_to_ids("<|im_end|>"), tok.convert_tokens_to_ids("<|endoftext|>")} LORA = bool(ADAPTER) # example patients and trials from the validation split (never the test split) _df = load_dataset() from tz.data import make_split, split_frame # noqa: E402 _val = split_frame(_df, make_split(_df), "val") EXAMPLES = {} for (pid, trial), g in _val.groupby(["patient_id", "trial_id"]): EXAMPLES[f"{pid} / {trial}: {g.trial_title.iloc[0][:60]}"] = ( g.note.iloc[0], "\n".join(g[g.criterion_type == "inclusion"].criterion_text), "\n".join(g[g.criterion_type == "exclusion"].criterion_text)) if len(EXAMPLES) >= 8: break def _ids(text): return tok(text, return_tensors="pt", add_special_tokens=False).input_ids.to(dev) @torch.no_grad() def _hf_batch(prompts, max_new, lora): tok.padding_side = "left" enc = tok(prompts, return_tensors="pt", padding=True, add_special_tokens=False).to(dev) kw = dict(max_new_tokens=max_new, do_sample=False, pad_token_id=tok.pad_token_id, temperature=None, top_p=None, top_k=None) if LORA and not lora: with model.disable_adapter(): out = model.generate(**enc, **kw) else: out = model.generate(**enc, **kw) return tok.batch_decode(out[:, enc.input_ids.shape[1]:], skip_special_tokens=True) def _ours(prompt, max_new, lora, speculative): x = _ids(prompt) if speculative: toks, _ = speculative_generate(dec, draft, x, max_new, k=4, eos_ids=EOS, target_lora=lora and LORA) else: toks, _ = greedy_generate(dec, x, max_new, eos_ids=EOS, lora=lora and LORA) return tok.decode(toks, skip_special_tokens=True) def verdict(rows): """Explicit aggregation rule; the dataset has no patient-level ground truth.""" labels = [(r["Type"], r["Decision"]) for r in rows] if any(l == ("inclusion", "not included") or l == ("exclusion", "excluded") for l in labels): return "Likely NOT eligible", "at least one inclusion criterion is not met or one exclusion criterion applies" if any(d in ("not enough information", "invalid output") for _, d in labels): return "Needs more information", "no criterion rules the patient out, but some cannot be decided from the note" return "Likely eligible", "every criterion is met or not applicable based on the note" @gpu(duration=120) def _screen_gpu(sentences, criteria, engine): prompts = [prompt_text(tok, build_messages(sentences, t, c)) for t, c in criteria] t0 = time.perf_counter() if engine.startswith("Fast"): raw = _hf_batch(prompts, 64, lora=True) else: raw = [_ours(p, 64, True, engine.endswith("speculative")) for p in prompts] rows, need = [], [] for (t, c), r in zip(criteria, raw): label, ev = parse_output(r, t, len(sentences)) rows.append({"Type": t, "Criterion": c, "Decision": label or "invalid output", "Evidence IDs": ev, "Evidence": " | ".join(f"[{i}] {sentences[i]}" for i in ev)}) if label and ev: need.append(len(rows) - 1) exp_prompts = [prompt_text(tok, explanation_messages(rows[i]["Type"], rows[i]["Criterion"], rows[i]["Decision"], [(j, sentences[j]) for j in rows[i]["Evidence IDs"]])) for i in need] if exp_prompts: exps = _hf_batch(exp_prompts, 96, lora=False) if engine.startswith("Fast") else \ [_ours(p, 96, False, engine.endswith("speculative")) for p in exp_prompts] else: exps = [] for i, e in zip(need, exps): rows[i]["Explanation"] = e.strip() for r in rows: r.setdefault("Explanation", template_explanation(r["Decision"]) if r["Decision"] != "invalid output" else "The model's answer could not be read.") return rows, time.perf_counter() - t0 def screen(note, inc, exc, engine): note, inc, exc = (note or "").strip(), (inc or "").strip(), (exc or "").strip() if not note: raise gr.Error("Paste a patient note first.") sentences = split_free_text(note) if len(tok(" ".join(sentences)).input_ids) > MAX_NOTE_TOKENS: raise gr.Error(f"The note is too long (over {MAX_NOTE_TOKENS} tokens). Shorten it and try again.") criteria = [("inclusion", l.strip()) for l in inc.splitlines() if l.strip()] + \ [("exclusion", l.strip()) for l in exc.splitlines() if l.strip()] if not criteria: raise gr.Error("Add at least one inclusion or exclusion criterion (one per line).") if len(criteria) > MAX_CRITERIA: raise gr.Error(f"Too many criteria ({len(criteria)}). The limit is {MAX_CRITERIA} per run.") rows, secs = _screen_gpu(sentences, criteria, engine) head, why = verdict(rows) numbered = "\n".join(f"{i}. {s}" for i, s in enumerate(sentences)) table = pd.DataFrame([{k: (", ".join(map(str, v)) if k == "Evidence IDs" else v) for k, v in r.items()} for r in rows]) summary = f"## {head}\nRule: {why}. ({len(rows)} criteria in {secs:.1f} s, engine: {engine})\n\n> {NOTICE}" return summary, table, numbered, _report(note, numbered, rows, head, why, engine, secs) def _report(note, numbered, rows, head, why, engine, secs): cells = "".join("
{NOTICE}
Rule: {html.escape(why)}.
| Type | Criterion | Decision | Evidence IDs | Evidence | Explanation |
|---|
{html.escape(numbered)}