"""Render REPORT.md from results/metrics.json. python src/make_report.py The narrative sentences are conditioned on the measured deltas, so the write-up cannot claim a win that the numbers do not show. """ import json import os import sys if hasattr(sys.stdout, "reconfigure"): # Windows consoles default to cp1252 sys.stdout.reconfigure(encoding="utf-8", errors="replace") sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) ROWS = [ ("mean_prompt_tokens", "Prompt tokens (mean)", "lower"), ("schema_valid_rate", "Schema-valid JSON %", "higher"), ("json_parse_rate", "Parsable JSON %", "higher"), ("trailing_text_rate", "Text after the JSON block %", "lower"), ("intent_acc", "Intent accuracy %", "higher"), ("priority_acc", "Priority accuracy %", "higher"), ("next_action_acc", "Next-action accuracy %", "higher"), ("escalation_f1", "Escalation F1", "higher"), ("escalation_precision", "Escalation precision", "higher"), ("escalation_recall", "Escalation recall", "higher"), ("policy_exact_set_match", "Policy set exact match %", "higher"), ("policy_f1", "Policy-citation F1", "higher"), ("hallucinated_policy_id_rate", "Rows citing a non-existent policy %", "lower"), ("mean_prose_chars", "Prose length (chars)", "-"), ("prose_reproduced_from_train_rate", "Prose copied verbatim from training %", "-"), ("mean_generated_tokens", "Generated tokens (mean)", "-"), ("seconds_per_example", "Seconds / example", "lower"), ] ARM_LABEL = { "prompted": "base + full prompt", "prompted_fewshot": "base + full prompt + 2-shot", "short_prompt": "base + one-line prompt", "lora": "**LoRA + one-line prompt**", } def fmt(v): return "-" if v is None else (f"{v:g}" if isinstance(v, (int, float)) else str(v)) def delta(m, base, tuned, key, better): a, b = base.get(key), tuned.get(key) if a is None or b is None: return None d = b - a if better == "lower": verdict = "better" if d < 0 else ("worse" if d > 0 else "unchanged") elif better == "higher": verdict = "better" if d > 0 else ("worse" if d < 0 else "unchanged") else: verdict = "n/a" return d, verdict def sentence(name, d, unit="points", better="higher"): if d is None: return None if abs(d) < 0.05: return f"{name} is unchanged." direction = "up" if d > 0 else "down" good = (d > 0) if better == "higher" else (d < 0) tail = "" if good else " (a regression)" return f"{name} is {direction} {abs(d):.1f} {unit}{tail}." def main(): path = "results/metrics.json" if not os.path.exists(path): sys.exit("results/metrics.json not found — run src/evaluate.py first.") m = json.load(open(path, encoding="utf-8")) arms = [a for a in ARM_LABEL if a in m] if "lora" not in m or "prompted" not in m: sys.exit("need at least the 'prompted' and 'lora' arms in metrics.json") base, tuned = m["prompted"], m["lora"] short = m.get("short_prompt") header = "| Metric | " + " | ".join(ARM_LABEL[a] for a in arms) + " | Δ (LoRA − prompted) |" sep = "|---|" + "---|" * (len(arms) + 1) lines = [header, sep] for key, label, better in ROWS: cells = [fmt(m[a].get(key)) for a in arms] d = delta(m, base, tuned, key, better) dcell = "-" if d is None else f"{d[0]:+.1f}" lines.append(f"| {label} | " + " | ".join(cells) + f" | {dcell} |") table = "\n".join(lines) tok_cut = 100 * (1 - tuned["mean_prompt_tokens"] / base["mean_prompt_tokens"]) findings = [ f"The fine-tuned model runs on **{tuned['mean_prompt_tokens']:.0f} prompt tokens against " f"{base['mean_prompt_tokens']:.0f}** for the prompted baseline — a {tok_cut:.0f}% cut in prompt " f"tokens on every single request.", ] for key, label, better in [ ("schema_valid_rate", "Schema-valid JSON", "higher"), ("intent_acc", "Intent accuracy", "higher"), ("escalation_f1", "Escalation F1", "higher"), ("policy_f1", "Policy-citation F1", "higher"), ("hallucinated_policy_id_rate", "The rate of replies citing a policy ID that does not exist", "lower"), ("trailing_text_rate", "Stray text after the JSON block", "lower"), ]: d = delta(m, base, tuned, key, better) s = sentence(label, d[0] if d else None, better=better) if s: findings.append(s) if short: findings.append( f"Stripping the long prompt without fine-tuning (`short_prompt`) drops schema-valid JSON to " f"{short['schema_valid_rate']:g}% and policy-citation F1 to {short['policy_f1']:g}% — which is the " f"measure of how much work the long prompt was actually doing, and therefore how much the adapter " f"had to absorb." ) repro = tuned.get("prose_reproduced_from_train_rate") if repro is not None: findings.append( f"**The prose is substantially memorised.** {repro:g}% of the fine-tune's replies reproduce a " f"training answer word for word (after normalising order IDs and numbers), against " f"{base.get('prose_reproduced_from_train_rate', 0):g}% for the prompted baseline. The adapter has " f"learned the response bank, not just the policy and the format. On templated training data that is " f"the expected outcome, and it is the single biggest reason not to read these accuracy numbers as " f"evidence about real support text." ) train_summary = {} for cand in ("outputs/lora-support/train_summary.json", "outputs/smoke/train_summary.json"): if os.path.exists(cand): train_summary = json.load(open(cand, encoding="utf-8")) break stats = json.load(open("data/stats.json", encoding="utf-8")) if os.path.exists("data/stats.json") else {} doc = f"""# What changed: prompted vs LoRA fine-tuned *Auto-generated from `results/metrics.json` by `src/make_report.py`. Every number below is measured on the {tuned['n']}-conversation held-out test set with greedy decoding and rule-based scoring — no LLM judge.* ## Setup | | | |---|---| | Base model | `{tuned.get('base_model', '?')}` | | Adapter | LoRA r={train_summary.get('lora', {}).get('r', '?')}, alpha={train_summary.get('lora', {}).get('alpha', '?')}, all attention + MLP projections | | Training data | {stats.get('train', {}).get('n', '?')} synthetic conversations → {train_summary.get('train_examples', '?')} assistant-turn examples | | Epochs / lr | {train_summary.get('epochs', '?')} / {train_summary.get('lr', '?')} | | Final train / eval loss | {train_summary.get('final_train_loss', '?')} / {train_summary.get('final_eval_loss', '?')} | | Test set | {tuned['n']} conversations, held-out customer phrasings, {stats.get('test', {}).get('escalating', '?')} requiring escalation | | Decoding | greedy, max {tuned.get('mean_generated_tokens', '?')} tokens generated on average | | Hardware | {tuned.get('device', '?')} | ## Results {table} ## What actually changed """ + "\n".join(f"* {f}" for f in findings) + f""" ## Reading these numbers honestly * The fine-tune was trained on this policy handbook and this output contract. It has not learned customer support; it has learned *this company's* support. Swap the policies and the adapter is wrong in exactly the confident way that makes fine-tuned models dangerous — the prompted baseline would simply follow the new prompt. * Prose quality is not scored at all, only length, structure and verbatim reuse. Given that roughly half the fine-tune's answers are recycled training sentences, "the fine-tune writes better replies" is a claim this experiment does not support and does not attempt to. * The customer phrasings in the test set are unseen, but they come from the same generator as the training set. This measures generalisation across wording, not across distribution. * Single seed, single base model. Gaps of a point or two are noise; the ones worth talking about are the large ones{' — chiefly the ' + f'{tok_cut:.0f}% prompt-token reduction' if tok_cut > 20 else ''}. ## Where this would go next * Push the same recipe onto a genuinely noisy dataset (real ticket text, human-labelled escalation) and see how much of the gap survives. * Test robustness: does the adapter still behave when the customer message is adversarial, or in a language the training set never contained? * Measure the serving economics properly — prompt-token savings compound with KV-cache pressure and are the strongest practical argument for this trade. """ with open("REPORT.md", "w", encoding="utf-8") as f: f.write(doc) print("wrote REPORT.md") print(table) if __name__ == "__main__": main()