Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse filesFiles changed (13)
- .gitattributes+4
- README.md+115-452
- agents/llm_fraudster.py+287-287
- assets/Fraudster Reward.pngAdded
- assets/HF Spaces.pngAdded
- assets/Investigator Reward.pngAdded
- assets/Loss-reward-KL curve.pngAdded
- blog.mdAdded+102
- training/TRAINING_GUIDE.md+366-366
- training/baseline_eval.ipynb+512-512
- training/compare_runs.ipynb+370-370
- training/official_hf_training.ipynb+950-950
- training/train_investigator.ipynb
33 unmodified lines34353633 unmodified lines*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textassets/ad[[:space:]]fraud[[:space:]]asset.png filter=lfs diff=lfs merge=lfs -text33 unmodified lines3435363738394033 unmodified lines*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textassets/ad[[:space:]]fraud[[:space:]]asset.png filter=lfs diff=lfs merge=lfs -textassets/Fraudster[[:space:]]Reward.png filter=lfs diff=lfs merge=lfs -textassets/HF[[:space:]]Spaces.png filter=lfs diff=lfs merge=lfs -textassets/Investigator[[:space:]]Reward.png filter=lfs diff=lfs merge=lfs -textassets/Loss-reward-KL[[:space:]]curve.png filter=lfs diff=lfs merge=lfs -text
9 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275289 unmodified lines- openenv- ad-fraud- reinforcement-learningbase_path: /web---# CounterFeint — Ad Fraud Investigation EnvironmentAn OpenEnv environment that simulates ad fraud review - a real-world task where AI agents investigate queues of advertisements, uncover fraud signals, and render verdicts under budget constraints.Ad fraud costs the digital advertising industry over **$100 billion annually**. Platforms like Meta process billions of ads daily and ban advertisers only at high confidence thresholds. Unlike simple classification, real ad review is a **sequential decision-making** problem: a reviewer starts with limited surface-level signals, actively chooses what to investigate within a constrained budget, and must decide when enough evidence exists to commit to a verdict. This environment captures that workflow and provides a training ground for agents to learn it.## Quick Start### Install```bashpip install -e .```### Run the server```bashuvicorn server.app:app --host 0.0.0.0 --port 8000```### Use the client```pythonfrom counterfeint import AdFraudEnv, AdReviewActionwith AdFraudEnv(base_url="http://localhost:8000").sync() as env:result = env.reset(seed=42, task_id="task_1")print(result.observation.queue_summary)# Investigate an adresult = env.step(AdReviewAction(action_type="investigate",ad_id="ad_001",investigation_target="landing_page",))print(result.observation.feedback)# Render a verdictresult = env.step(AdReviewAction(action_type="verdict",ad_id="ad_001",verdict="reject",confidence=0.9,))print(f"Reward: {result.reward}, Done: {result.done}")```### Run with Docker```bashdocker build -t counterfeint .docker run -p 8000:8000 counterfeint```## Environment Design### Episode flowEach episode is a review session. The agent receives a queue of ads and must process them within a limited action budget:```reset(task_id, seed)|v+----------------------------------+<----------------------+| Observe queue + first ad info | |+------------------+---------------+ || |v |+-------------+ +------------------+ || investigate |---->| Reveal one signal |----------++-------------+ | (costs 1 budget) || +------------------+v+-------------+ +------------------+| verdict |---->| approve / reject |----------++-------------+ | / escalate | || +------------------+ |v |+--------------+ +------------------+ || link_accounts|---->| Flag fraud ring |----------++--------------+ | (Task 3 only) || +------------------+vBudget exhausted or all ads reviewed -> episode ends```### TasksThree tasks with increasing difficulty test different capabilities:| Task | Name | Ads | Budget | Composition | Challenge ||---|---|---:|---:|---|---|| 1 | Basic Ad Triage | 5 | 25 | 2 legit, 3 obvious fraud | Learn the investigate -> verdict loop || 2 | Sophisticated Fraud | 12 | 30 | 5 legit, 5 sophisticated scams, 2 gray-area | Triage under budget pressure (~2.5 actions/ad) || 3 | Fraud Network Detection | 20 | 35 | 6 legit, 10 fraud (3 hidden rings), 4 gray-area | Cross-ad reasoning to detect coordinated networks (~1.75 actions/ad) |Task 3 introduces **fraud rings** - clusters of 3-5 ads controlled by the same actor, using varied topologies (cliques, chains, hub-and-spoke). Individual ring members look borderline; the fraud signal is only visible by cross-referencing investigation data across ads (shared payment IDs, matching template hashes, overlapping targeting fingerprints).### Action SpaceActions are JSON objects. Three types:**`investigate`** - spend one budget point to reveal a signal about an ad.```json{"action_type": "investigate","ad_id": "ad_001","investigation_target": "landing_page"}```Each ad has six investigation dimensions:| Target | What it reveals ||---|---|| `advertiser_history` | Account age, spend history, violation record, verification status || `landing_page` | Domain age, SSL, registrar, redirect chains, scam template similarity || `payment_method` | Payment type, chargeback history, cross-account velocity || `targeting_overlap` | Targeting fingerprint, audience overlap percentages || `campaign_structure` | Objective, bid strategy, budget/age ratio, placement distribution || `policy_classifier` | Llama Guard 3 / Purple Llama mock: safe / unsafe verdict, triggered LG categories (S1–S13), TS-Fraud markers (urgency, fake authority, get-rich-quick, etc.) |**`verdict`** - render a final decision on an ad.```json{"action_type": "verdict","ad_id": "ad_001","verdict": "reject","confidence": 0.9}````verdict` options: `approve`, `reject`, `escalate`. `confidence`: 0.0-1.0.**`link_accounts`** - flag two ads as part of the same fraud network (Task 3).```json{"action_type": "link_accounts","ad_id": "ad_003","linked_ad_id": "ad_007","link_reason": "shared payment ID pmt_ring_48231 and matching template hash"}```### Observation SpaceObservations are text-heavy by design so LLM agents can reason naturally:| Field | Type | Description ||---|---|---|| `queue_summary` | `str` | Task name, total/reviewed/pending counts, budget remaining || `current_ad_info` | `str` | Ad copy, category, targeting, risk signals for the focused ad || `investigation_findings` | `str` | Accumulated findings from all investigations so far || `verdict_history_summary` | `str` | Verdicts rendered so far || `feedback` | `str` | Natural language feedback on the last action || `available_ads` | `list[str]` | Ad IDs still pending review || `queue_status` | `dict` | Structured status for programmatic access || `done` | `bool` | Whether the episode is complete || `reward` | `float` | Step reward |## Reward Design| Action | Reward | Rationale ||---|---:|---|| Investigation | -0.02 | Simulates time/latency cost || Correct rejection (fraud -> reject) | +0.30 to +0.40 | Scaled by fraud severity || Correct approval (legit -> approve) | +0.10 | Revenue preserved || Correct escalation | +0.15 | Appropriate caution || False positive (legit -> reject) | -0.35 | Lost advertiser revenue || False negative (fraud -> approve) | -0.50 | Worst outcome - fraud goes live || Escalate (when wrong) | -0.05 | Human reviewer cost || Correct network link | +0.40 | High-value coordinated fraud detection || Incorrect network link | -0.25 | False accusation cost |Unreviewed ads are auto-approved at episode end - missed fraud incurs the full -0.50 false-negative penalty.## Grading & ScoringEach task has a dedicated grader that produces a normalized **0.0-1.0 score**. Raw reward is normalized between theoretical worst-case (every decision wrong + full budget wasted) and best-case (every decision correct + efficient budget use).| Component | Task 1 | Task 2 | Task 3 ||---|:---:|:---:|:---:|| Verdict accuracy | Yes | Yes | Yes || Budget efficiency bonus | Yes | Yes | Yes || Calibration bonus | - | Yes | Yes || Network detection (edge coverage) | - | - | Yes || Investigation coverage bonus | - | - | Yes |**Calibration bonus** rewards agents whose stated confidence correlates with actual accuracy - high confidence on correct verdicts and low confidence on uncertain ones.**Network detection** uses edge coverage: what fraction of ground-truth fraud ring connections did the agent discover via `link_accounts`?**Coverage bonus** rewards breadth over depth - agents that review more ads (rather than deep-diving a single one) score higher on Task 3.## Baseline ScoresGenerated with `seed=42` using `Qwen/Qwen2.5-1.5B-Instruct`. Reproducible via `python inference.py`.| Task | Score | Steps | Verdicts ||---|---:|---:|---:|| Task 1 (Easy) | 0.953 | 10 | 5/5 || Task 2 (Medium) | 0.882 | 23 | 12/12 || Task 3 (Hard) | 0.415 | 35 | 20/20 |The sharp drop on Task 3 reflects the difficulty of cross-ad reasoning under tight budget - the baseline agent investigates and renders verdicts well but struggles to detect coordinated fraud rings.## Three-Agent FraudArena (R2)CounterFeint also ships a three-agent multi-policy mode where anadversarial **Fraudster** proposes ads, an **Investigator** reviews themunder a budget, and an **Auditor** grades the Investigator's reasoningpost-hoc. This adds Themes #1 (multi-agent interaction) and #4(self-improvement) to the original single-agent task.```python -m counterfeint.inference # scripted vs scripted vs scriptedpython -m counterfeint.inference --llm-fraudster # adversarial LLM Fraudster (frozen)python -m counterfeint.inference --llm-fraudster --llm-investigator # full LLM bench```The Fraudster has its own escalating curriculum (`max_proposals`,`allowed_fraud_categories`) that scales with task difficulty, and`--llm-fraudster` swaps the deterministic `ReactiveFraudster` for anOpenAI-compatible LLM (works with Ollama at`http://localhost:11434/v1`). LLM failures (timeout, bad JSON,validation error) silently fall back to the scripted policy and arecounted in the `[END] ... fallbacks=fraudster:N,investigator:N`STDOUT line.### Self-play curriculum (sequential, two-generation)CounterFeint trains *one agent at a time* against frozen opponents —the canonical multi-agent RL paradigm used by AlphaGo, OpenAI Five,and AlphaStar. Co-training two LLMs in parallel is non-stationary anddiverges; sequential self-play is stable.**Asymmetric multi-agent setup (shipped).** Train the much smallerInvestigator on `Qwen/Qwen2.5-1.5B-Instruct` against the**larger frozen** `llama3.1:8b` Fraudster served by Ollama — a**~5×** parameter asymmetry. Every rollout uses the LLM Fraudsterby default (`LLM_FRAUDSTER_RATIO=1.0`), so the training distributionis genuinely adversarial and matches the held-out eval distribution —the headline claim is "*the smaller model wins via task-specificGRPO against a stronger frozen adversary*".The two policies also come from **different model families** (QwenInvestigator vs Llama Fraudster), so the GRPO signal isn't aparameter-sharing artefact and the framework is demonstrablymodel-agnostic.| Role | Model | Backend | Trainable? ||--------------|------------------------------------|--------------------|------------|| Investigator | `Qwen/Qwen2.5-1.5B-Instruct` | HuggingFace + QLoRA| **Yes** || Fraudster | `llama3.1:8b` | Ollama (frozen) | No || Auditor | Rule-based scorecards (`HeuristicAuditor`) — **deterministic by design**, see note below | In-process Python | No |**Why the Auditor is deterministic.** The Auditor's flag stream is the*reward source* for both other roles (Track A drives the Investigator'srationale-quality penalty; Track B drives the Fraudster's plausibility-weighted survival credit). A deterministic Auditor makes the rewardfunction inspectable, reproducible across training runs, and free of LLMnoise / cost / latency. It also mirrors how real ad-policy review teamsoperate — rule-based scorecards layered on top of model verdicts. The[`graders/auditor_pipeline.run_full_audit`](graders/auditor_pipeline.py)orchestrator already returns a typed bundle that an LLM-backed auditorcould populate in one shot, so a future `LLMAuditor` is a clean drop-in;that swap is **explicitly out of scope for this hackathon submission**.Single submission notebook (per the hackathon's "*ideally as a Colabnotebook so judges can re-run it*" guidance): every line of thetraining stack — `HFInvestigator`, the rollout collector, the GRPOconfig, and the TRL `GRPOTrainer` driver — is **inlined into[`training/train_investigator.ipynb`](training/train_investigator.ipynb)**.Production-time policies (`counterfeint.agents.LLMFraudster`,`counterfeint.scripted.*`) and the eval harness (`counterfeint.eval_suite`)remain as repo modules because they are also imported by inference /serving paths.Need to fall back to a deterministic Fraudster (e.g. no GPU headroomfor both 1.5B-train + 8B-serve)? Set `LLM_FRAUDSTER_RATIO = 0.0` in §1of the notebook — every rollout will then use `ReactiveFraudster`instead of Ollama.**Why Qwen 2.5 1.5B as the trainable base?**- **Apache 2.0** — Judges can re-run the notebook from a clean machine with no HF accountrequired.- **Fits a 12 GB consumer GPU** alongside the 8B Ollama Fraudster onthe same device when QLoRA brings the trainable footprint to~1.2 GB. (Also fits Colab T4 with room to spare.)- **Strong JSON / tool-use behaviour** — Qwen2.5-Instruct waspost-trained explicitly for structured outputs, which translates toa noticeably lower `fallback_count` on the action schema than asame-size general-purpose base.- **5× smaller than the Fraudster** — sharpens the headline claim("*small specialised Investigator beats large generalist Fraudstervia GRPO*") into something a judge can read off the model cardalone.Override via the `BASE_MODEL` constant in §1 of the notebook if youwant to scale up (e.g. `Qwen/Qwen2.5-3B-Instruct` or`meta-llama/Llama-3.2-3B-Instruct`; both are drop-in replacements).#### Three runtime budgetsThe training notebook exposes a single `MODE` knob so judges (or yourown laptop) can pick how long to wait:| `MODE` | Episodes | Eval seeds | ~Wall time (24 GB GPU) | What it proves ||---------|---------:|-------------:|----------------------------------------------|----------------|| `smoke` | 6 | 3 (1/task) | ~10 min (`dry_run=True`, GRPO step skipped) | Pipeline runs end-to-end; artefacts written. || `demo` | 30 | 30 (10/task) | ~45–75 min | Visible before/after delta; headline plot meaningful. || `full` | 150 | 30 (10/task) | ~4–6 h | Convergence-quality curve. |Episode counts are smaller than for a scripted-fraudster setup becauseevery rollout now pays the 8B-Fraudster latency. GRPO with averifiable reward function (the existing grader) needs **far less datathan supervised fine-tuning or RLHF on human preferences** — typicallya few hundred to a few thousand (prompt, completion, reward) samples.Each `demo` episode produces ~5–10 Investigator turns, so the30-episode `demo` budget yields ~150–300 GRPO samples, which is abovethe noise floor for a 1.5B base with QLoRA when reward variance is high.### Training vs inference: two different stacksCounterFeint deliberately separates the **training** stack from the**inference** stack. They look similar from the outside (both serve a`Qwen2.5-1.5B-Instruct` policy) but live behind different code paths:| Concern | Training (the LLM whose weights move) | Inference / frozen opponent ||-------------------------------------------|---------------------------------------|---------------------------------------|| Backend | HuggingFace `transformers` + `peft` + `trl` | Ollama (OpenAI-compatible HTTP) || Where it runs | GPU process inside the training notebook | Separate background daemon (`ollama serve`) || Code entry point | `HFInvestigator` (inlined in §5 of [`train_investigator.ipynb`](training/train_investigator.ipynb)) | `counterfeint.agents.LLMInvestigator` / `LLMFraudster` || 4-bit / LoRA? | Yes — QLoRA via `bitsandbytes` + LoRA adapter | No — Ollama serves the GGUF weights as-is || Used during | GRPO rollouts in `train_investigator.ipynb` | Held-out eval, baseline runs, frozen LLM Fraudster || Install | `pip install -r requirements-train.txt` | `ollama pull llama3.1:8b` (Fraudster) |The two stacks deliberately share the **same prompt assembly + JSONparsing** (`counterfeint.agents.prompts` + the `_to_messages` /`_extract_action` helpers in `LLMPolicyBase`), so the trained adaptercan be exported to GGUF and dropped behind Ollama with zero behaviourdrift.## Before vs After TrainingThe held-out eval lane lives in[`counterfeint/eval_suite.py`](eval_suite.py). It runs theInvestigator over 30 fixed `(task_id, seed)` tuples (10 per task,**disjoint from training seeds**) against the stable`ReactiveFraudster` adversary, and writes three artefacts to`eval_outputs/`:```eval_outputs/├── eval_results.json # per-episode metrics for both tags├── eval_summary.md # markdown delta table (before / after / delta)└── eval_plot.png # 2×2 bar chart, headline visual```Reproduce with:```bash# Pre-training baseline (scripted Investigator)python -m counterfeint.eval_suite --before-tag scripted --after-tag scripted_rerun# After training (programmatic, used at the end of the Colab notebook):python -c "from counterfeint.eval_suite import run_before_after; \from counterfeint.scripted import ScriptedInvestigator; \from pathlib import Path; \run_before_after(before_tag='scripted', after_tag='trained_v1', \before_investigator_factory=ScriptedInvestigator, \after_investigator_factory=lambda: load_trained_investigator('checkpoints/v1'), \out_dir=Path('eval_outputs'))"```*Bar chart compares grader score, Track A reasoning score, mean fraudleaks (false approvals on ground-truth fraud), and budget consumptionacross all three tasks. The PNG above is a **placeholder** generatedfrom synthetic metrics so the README rendering stays self-contained;the real artefact is regenerated end-to-end by every`run_before_after` call (final cell of[`training/train_investigator.ipynb`](training/train_investigator.ipynb))and is committed to `eval_outputs/` pre-submission. The fullper-episode breakdown lives in[`eval_outputs/eval_summary.md`](eval_outputs/eval_summary.md).*Per-episode metrics tracked: `grader_score`, `track_a_score`,`track_b_score`, `n_fraud_leaks`, `budget_used_pct`,`fallback_count`, `rewards_by_role`. The `fallback_count` makessilent LLM degradations visible; an eval run with > 30 % fallbackrate is treated as inconclusive.### Evaluated against Meta-CIB-modeled adsBeyond the procedurally generated tasks, every `run_before_after()`output also embeds a summary of a small held-out dataset([`counterfeint/data/real_world_test_set.json`](data/real_world_test_set.json))of **15 synthetic ads** authored to match the patterns described inMeta's published quarterly **Adversarial Threat Reports** — coveringthe Ghana DigitSol clique, the Benin Digited chain, and theChina-Russia hub-spoke operations now wired into our networkgenerator ([`counterfeint/data/network_generator.py`](data/network_generator.py)).| Case study source | # ads | Quarter || --------------------------------------- | ----: | :------ || Ghana DigitSol-style | 5 | Q3 2020 || Benin Digited-style | 5 | Q1 2021 || China-Russia-style hub | 3 | Q3 2022 || Distractor (not part of any CIB ring) | 2 | n/a |Every ad in the holdout JSON carries:* `case_study_source` — the Meta CIB report it descends from* `provenance_quarter` — the report quarter (e.g. "Q3 2020")* `ring_membership` — the synthetic ring it belongs to* `shared_signals` — payment / registrar / creative fingerprintsshared across the ring (the ground truth the Investigator shouldsurface)The dataset is loaded only via[`counterfeint/data/real_world_loader.py`](data/real_world_loader.py),which gates every read on an explicit `confirm_eval_only=True`argument. Training rollouts never call the loader, so this set**cannot leak into training by accident** — the`load_real_world_holdout()` API itself enforces the holdout boundary.The 2 distractor *legit* ads (Brooklyn coffee roastery,Calm app trial) are intentionally included so the realism sweepalso measures the trained Investigator's **false-positive rate** onbenign-looking content, not just its hit rate on fraud.## Project Structure```counterfeint/+-- __init__.py # Package exports+-- client.py # WebSocket client (extends EnvClient)+-- models.py # Action, Observation, State types+-- inference.py # R1 single-agent + R2 three-agent driver+-- eval_suite.py # Held-out eval lane: run_before_after()+-- openenv.yaml # OpenEnv manifest+-- pyproject.toml # Dependencies and package config+-- requirements-dev.txt # Dev-only deps (pytest, matplotlib for eval_plot.png)+-- Dockerfile # Multi-stage Docker build+-- baseline_scores.json # Cached baseline results+-- agents/ # LLM-backed policy classes (R2)| +-- base.py # LLMPolicyBase: retry + timeout + scripted fallback| +-- prompts.py # FRAUDSTER_SYSTEM_PROMPT, INVESTIGATOR_SYSTEM_PROMPT| +-- llm_fraudster.py # LLMFraudster (fallback: ReactiveFraudster)| +-- llm_investigator.py # LLMInvestigator (fallback: ScriptedInvestigator)+-- scripted/ # Deterministic baseline policies (R2)| +-- fraudster.py # Scripted, Reactive, and Gibberish (control) Fraudsters| +-- investigator.py # ScriptedInvestigator (cites Meta policy IDs)| +-- auditor.py # HeuristicAuditor (rule-based, fixed reward channel)+-- data/| +-- ad_generator.py # Episode generation, task configs (with Fraudster knobs)| +-- advertiser_profiles.py # Synthetic advertiser history| +-- fraud_patterns.py # Fraud + legit ad templates (easy/medium/hard)| +-- landing_pages.py # Simulated landing page investigation data| +-- network_generator.py # Named CIB ring topologies (Ghana / Benin / China-Russia)| +-- meta_policy_taxonomy.py # Meta policy citation IDs / sections / URLs| +-- real_world_test_set.json # 15-ad CIB-modeled holdout (Ghana / Benin / China-Russia)| +-- real_world_loader.py # Eval-only loader (confirm_eval_only=True gate)| +-- audit_heuristics.py # Regex helpers (incl. Meta citation IDs)+-- graders/| +-- base_grader.py # Shared normalization and reward logic| +-- task1_grader.py # Verdict accuracy only| +-- task2_grader.py # + calibration bonus| +-- task3_grader.py # + network detection + coverage bonus| +-- auditor_track_a.py # Investigator reasoning audit (rationales, citations)| +-- auditor_track_b.py # Fraudster ad-plausibility audit| +-- multi_agent_rewards.py # Combined reward computation+-- server/| +-- app.py # FastAPI app with /tasks, /baseline, /grader endpoints| +-- environment.py # Core environment (reset/step/state)| +-- referee.py # 3-agent state machine, applies TaskConfig curriculum| +-- investigate_ui.py # HTML dashboard routes (/investigate, /web redirect)| +-- static/| +-- investigate_hq.html # Interactive investigation dashboard+-- training/| +-- train_investigator.ipynb # Single-file submission: GRPO trainer with all helpers inlined| # (HFInvestigator + rollout collector + GRPO config + driver)+-- tests/+-- test_data_generation.py # Determinism, cross-ref, decoy, CIB topology+-- test_environment.py # Step logic, state tracking, anti-exploit+-- test_graders.py # Score ranges, calibration, network scoring+-- test_three_agent_episode.py # Three-agent state machine + curriculum+-- test_llm_agents.py # LLMPolicyBase fallback + retry semantics+-- test_eval_suite.py # Eval-lane parser + writer round-trips+-- test_meta_policy_taxonomy.py # Citation coverage + evidence-token recognition```## API Endpoints| Endpoint | Method | Description ||---|---|---|| `/health` | GET | Health check || `/schema` | GET | Action/Observation JSON schemas || `/ws` | WS | WebSocket for `step()` / `reset()` / `state()` || `/tasks` | GET | Task list with configs and action schema || `/baseline` | GET | Baseline scores (cached or live) || `/grader` | GET | Last episode's grader result || `/investigate` | GET | HTML investigation dashboard (also `/` redirects here) |## License9 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901919 unmodified lines- openenv- ad-fraud- reinforcement-learning- multi-agent- grpo- trust-and-safetybase_path: /web---# CounterFeint - Ad Fraud Investigation Environment> A three-agent adversarial RL environment where a 0.6B Investigator learns to catch ad fraud that a frozen 8B Fraudster tries to sneak past it - trained end-to-end with GRPO on a single T4 GPU.**[Live Environment (HF Space)](https://huggingface.co/spaces/QuantumTransformer/CounterFeint)** ·**[Blog Post](blog.md)** ·**[Training Notebook](training/official_hf_training.ipynb)** ·**[GitHub](https://github.com/Abhijithreddydasari/CounterFeint)**---## Why Ad Fraud?Ad fraud costs the digital advertising industry over **$100 billion annually**.Platforms like Meta process billions of ads daily and reject advertisers only at high confidence - because a false positive kills a legitimate business's revenue, while a false negative puts a scam in front of millions of real people.The critical insight: catching sophisticated ad fraud isn't a classification problem. It's **investigation**. A reviewer starts with surface-level signals, actively chooses what to dig into under time and budget constraints, and decides when the evidence is sufficient to commit to a verdict. That sequential decision-making workflow - triage, investigate, decide - is exactly what CounterFeint simulates.I built this environment because this kind of investigative reasoning under uncertainty is precisely where RL-trained LLMs can add real value, and it maps directly to how trust & safety teams at platforms like Meta actually operate.## The FraudArena - Three-Agent SetupCounterFeint is an [OpenEnv](https://github.com/open-env/open-env)-compatible environment built around a three-agent adversarial game:| Role | What it does | Model ||---|---|---|| **Fraudster** | Proposes ads designed to evade detection - from obvious scams to sophisticated, borderline-plausible creatives | `llama3.1:8b` (frozen) or scripted baseline || **Investigator** | Reviews a queue of ads, investigates suspicious signals within a budget, renders verdicts | `Qwen3-0.6B` + QLoRA (**trained via GRPO**) || **Auditor** | Grades the Investigator's reasoning quality and the Fraudster's plausibility | Rule-based scorecards (deterministic) |The Investigator is the agent I train - a **0.6B parameter model** learning to outperform a frozen **8B adversary** (~13x parameter gap). The goal: train the small model with GRPO until it catches what the big one tries to hide.### Episode FlowEach episode is a multi-round match between the three agents:```reset(task_id, seed)|v+-- Round 1..N (up to max_rounds) --------------------------+| || FRAUDSTER TURN || -> propose_ad / modify_pending_ad / end_turn || (capped at max_proposals across the match) || || INVESTIGATOR TURN || -> investigate (spend 1 budget to reveal a signal) || -> verdict (approve / reject / escalate) || -> link_accounts (flag fraud ring connections) || (capped at action_budget across the match) || |+------------------------------------------------------------+|vAUDIT PHASE-> Auditor grades Investigator reasoning (Track A)+ Fraudster plausibility (Track B)-> Episode ends, rewards computed```### Three Escalating Tasks| Task | Base Ads | Budget | Fraudster Curriculum | Challenge ||---|---:|---:|---|---|| **Basic Triage** | 5 | 25 | 3 proposals, 4 rounds, easy categories only | Learn the investigate -> verdict loop || **Sophisticated Fraud** | 12 | 30 | 6 proposals, 4 rounds, mid-tier categories | Triage under budget pressure (~2.5 actions/ad) || **Fraud Network Detection** | 20 | 35 | 7 proposals, 5 rounds, full category palette + rings | Cross-ad reasoning to detect coordinated networks (~1.75 actions/ad) |Task 3 introduces **fraud rings** - clusters of 3-5 ads controlled by the same actor using varied graph topologies (cliques, chains, hub-and-spoke), modeled after real CIB operations from Meta's Adversarial Threat Reports. The Fraudster's curriculum also escalates: more proposals, more rounds, and access to network-level fraud categories that produce coordinated ring patterns.## What Makes It Realistic**Budget constraints force triage.** Every investigation costs budget. Miss a fraud ad? It auto-approves at episode end with the full false-negative penalty (-0.50). Over-investigate one ad? You run out before reviewing the rest. This is the same tradeoff real reviewers face daily.**Meta Purple Llama integration.** One of the six investigation tools is a `policy_classifier` simulating **Llama Guard 3** / Purple Llama safety screening - returning safe/unsafe verdicts, triggered categories (S1-S13), and trust & safety fraud markers (urgency language, fake authority, get-rich-quick signals).**Meta policy taxonomy.** Every ad carries a citation grounded in Meta's published transparency policies (e.g., `FSDP-IF-03` for Fraud, Scams and Deceptive Practices). The Auditor checks whether the Investigator cites the correct policy section in its rationale.**CIB-modeled fraud rings.** Task 3 networks are modeled on real Coordinated Inauthentic Behaviour operations from Meta's quarterly threat reports - Ghana DigitSol-style cliques (Q3 2020), Benin Digited-style chains (Q1 2021), and China-Russia-style hub-spoke networks (Q3 2022).**Asymmetric rewards.** False negatives (fraud goes live) are penalized 5x more than false positives. Correct network link detection pays +0.40 because coordinated fraud is the highest-value catch. A calibration bonus rewards agents whose stated confidence correlates with actual accuracy.| Investigator Reward Flow | Fraudster Reward Flow ||:---:|:---:||  |  |## TrainingI train the Investigator using **GRPO** (Group Relative Policy Optimization) with **QLoRA** on `Qwen/Qwen3-0.6B` via HuggingFace TRL. The entire trainable footprint is ~600MB, fitting comfortably on a free Colab T4.**Pipeline:**1. **Collect rollouts** - run multi-agent episodes in-process (no HTTP server) with a scripted Fraudster and Auditor2. **Score with a proxy reward** - a deterministic, verifiable reward function that scores each completion on schema validity, observation coherence, action correctness, and evidence citation quality3. **GRPO update** - TRL's `GRPOTrainer` uses reward variance across completions to compute advantagesThe proxy reward uses **continuous components** - partial credit for almost-valid JSON, graduated bonuses for evidence density, conciseness rewards - so GRPO always has a meaningful signal.**Training notebook:** [`training/official_hf_training.ipynb`](training/official_hf_training.ipynb)### Results| Model | Task 1 | Task 2 | Task 3 | Mean ||---|---:|---:|---:|---:|| Qwen3-0.6B baseline (4-bit, no fine-tuning) | 0.543 | 0.576 | 0.180 | 0.433 |<!-- | Qwen3-0.6B + GRPO LoRA | TODO | TODO | TODO | TODO | --><!-- TODO: Add after-training results row and plots --><!--  --><!--  -->Task 3's baseline score of 0.18 reflects the difficulty - the untrained model can barely handle basic investigation, let alone cross-ad fraud ring detection.## Quick Start```bashpip install -e .uvicorn server.app:app --host 0.0.0.0 --port 8000``````pythonfrom counterfeint import AdFraudEnv, AdReviewActionwith AdFraudEnv(base_url="http://localhost:8000").sync() as env:result = env.reset(seed=42, task_id="task_1")result = env.step(AdReviewAction(action_type="investigate",ad_id="ad_001",investigation_target="landing_page",))result = env.step(AdReviewAction(action_type="verdict",ad_id="ad_001",verdict="reject",confidence=0.9,))```**Train:** Open [`training/official_hf_training.ipynb`](training/official_hf_training.ipynb) on a T4 GPU. Set `MODE = "demo"` for ~30 min, or `MODE = "proper"` for ~3 hours.## Project Structure```counterfeint/├── server/ # FastAPI app, core environment, referee state machine├── agents/ # LLM policy classes (HFInvestigator, LLMFraudster, prompts)├── scripted/ # Deterministic baselines (ScriptedInvestigator, ReactiveFraudster, HeuristicAuditor)├── data/ # Ad generation, fraud patterns, CIB network topologies, Meta policy taxonomy├── graders/ # Task graders, auditor tracks (reasoning quality + plausibility)├── training/ # GRPO training notebook, proxy reward, rollout collector├── tests/ # Test suite├── openenv.yaml # OpenEnv manifest└── Dockerfile # Docker build for HF Spaces```## Links| Resource | URL ||---|---|| Live Environment | [HF Space](https://huggingface.co/spaces/QuantumTransformer/CounterFeint) || Training Notebook | [`training/official_hf_training.ipynb`](training/official_hf_training.ipynb) || Blog Post | [`blog.md`](blog.md) || GitHub | [CounterFeint](https://github.com/Abhijithreddydasari/CounterFeint) |## License
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287"""LLM-backed Fraudster policy.Wraps :class:`.base.LLMPolicyBase` with the Fraudster system prompt andobservation-to-user-prompt assembly logic. Falls back to:class:`counterfeint.scripted.ReactiveFraudster` on any failure."""from __future__ import annotationsfrom typing import Any, Dict, List, Optionalfrom ..models import FraudsterActionfrom ..scripted._base import PolicyBasefrom ..scripted.fraudster import ReactiveFraudsterfrom .base import LLMPolicyBasefrom .prompts import FRAUDSTER_SYSTEM_PROMPT, FRAUDSTER_USER_TEMPLATEdef _compact_queue(queue: List[Dict[str, Any]], max_items: int = 8) -> str:"""Condense the current_queue field to a single-line preview."""if not queue:return "[empty]"own = [e for e in queue if e.get("is_my_proposal")]others = [e for e in queue if not e.get("is_my_proposal")]ordered = own + othersparts: List[str] = []for entry in ordered[:max_items]:ad_id = entry.get("ad_id", "?")cat = entry.get("category", "?")status = entry.get("status", "pending")slot = entry.get("slot_index")mine = (f" (mine, slot={slot})"if entry.get("is_my_proposal") and slot is not Noneelse (" (mine)" if entry.get("is_my_proposal") else ""))parts.append(f"{ad_id}/{cat}/{status}{mine}")trailer = "" if len(queue) <= max_items else f" +{len(queue) - max_items} more"return "; ".join(parts) + trailerdef _compact_prior_verdicts(verdicts: List[Dict[str, Any]], max_items: int = 5) -> str:if not verdicts:return "(none yet)"recent = verdicts[-max_items:]out: List[str] = []for v in recent:ad_id = v.get("ad_id", "?")decision = v.get("verdict", "?")conf = v.get("confidence")mine = " [mine]" if v.get("was_my_proposal") else ""conf_str = f"{conf:.2f}" if isinstance(conf, (int, float)) else "?"out.append(f"{ad_id}={decision}@{conf_str}{mine}")return " | ".join(out)# Columns rendered per proposal. Matches the Investigator's decided-ads# column set so both sides reason over the same signal vocabulary._PROPOSAL_SIGNAL_COLUMNS: List[str] = ["slot_index","investigator_verdict","category","country","account_age_days","domain","registrar","payment_id","payment_type","targeting_fingerprint",]def _render_my_proposal_signals(signals: Dict[str, Dict[str, Any]],*,max_ads: int = 8,) -> str:"""Render the Fraudster's per-proposal signal table as compact text."""if not signals:return "(no proposals submitted yet)"ad_ids = list(signals.keys())if len(ad_ids) > max_ads:kept = ad_ids[-max_ads:]trailer = f" (+{len(ad_ids) - max_ads} older proposals not shown)"else:kept = ad_idstrailer = ""lines: List[str] = []for ad_id in kept:entry = signals.get(ad_id, {}) or {}cells: List[str] = []for col in _PROPOSAL_SIGNAL_COLUMNS:if col in entry and entry[col] not in (None, ""):cells.append(f"{col}={entry[col]}")if cells:lines.append(f" {ad_id}: " + " | ".join(cells))return ("\n".join(lines) + trailer).rstrip()# Per-task-tier guidance appended to the user prompt. Easy tasks get a# louder fraud posture (so the Investigator can succeed at all in the# pre-training baseline); hard tasks get a stealthier posture (so the# trained Investigator's lift is meaningful). We deliberately surface# this in the USER prompt instead of mutating ``system_prompt`` so the# policy still sees a stable system role across all tasks (the system# prompt is the schema contract; per-task hints live in the user# message where the rest of the per-turn observation lives)._TASK_TIER_HINTS: Dict[str, str] = {"task_1": ("Tier hint (task_1, easy): use blatant fraud cues — obvious ""scam ad copy, unrelated targeting, cheap TLDs. The Investigator ""needs a clean baseline to learn against."),"task_2": ("Tier hint (task_2, medium): mix one or two subtle ads with the ""obvious ones; vary registrars / payment types across your slate."),"task_3": ("Tier hint (task_3, hard): aim for stealth. Construct fraud ""rings via shared payment_id / domain / targeting_fingerprint ""across 2-3 of your proposals so the only path to detection is ""cross-ad ring inference, not single-ad surface red flags."),"task_3_unseen": ("Tier hint (task_3_unseen, hard generalisation): same posture ""as task_3 but you are being evaluated on a held-out seed — do ""NOT collapse to a single template; vary your slate."),}def _task_tier_hint(task_id: str) -> str:return _TASK_TIER_HINTS.get(task_id or "", "")# Field whitelist per action_type. Keys not in the whitelist for the# action's type are dropped before Pydantic validation so a small# Llama-class model that mixes (e.g. ``slot_index`` on a ``propose_ad``,# or ``ad_copy`` on a ``modify_pending_ad``) still produces a valid# action instead of falling back. ``rationale`` and ``action_type`` are# always allowed._FRAUDSTER_FIELDS_BY_TYPE: Dict[str, set[str]] = {"propose_ad": {"action_type", "ad_copy", "category","landing_page_blurb", "targeting_summary", "rationale",},"modify_pending_ad": {"action_type", "slot_index","new_ad_copy", "new_landing_page_blurb", "rationale",},"end_turn": {"action_type", "rationale"},"commit_final": {"action_type", "rationale"},}class LLMFraudster(LLMPolicyBase):"""LLM Fraudster with a :class:`ReactiveFraudster` deterministic fallback."""system_prompt = FRAUDSTER_SYSTEM_PROMPTaction_model = FraudsterAction_log_name = "fraudster"def __init__(self,*,fallback_policy: Optional[PolicyBase] = None,fallback_seed: int = 0,**kwargs: Any,) -> None:if fallback_policy is None:fallback_policy = ReactiveFraudster(seed=fallback_seed)super().__init__(fallback_policy=fallback_policy, **kwargs)# ------------------------------------------------------------------def _build_user_prompt(self, observation: Dict[str, Any]) -> str:queue = observation.get("current_queue", []) or []verdicts = observation.get("prior_verdicts", []) or []tier_hint = _task_tier_hint(observation.get("task_id", ""))return FRAUDSTER_USER_TEMPLATE.format(round_number=observation.get("round_number", 0),rounds_remaining=observation.get("rounds_remaining", 0),proposals_used=observation.get("proposals_used", 0),proposals_remaining=observation.get("proposals_remaining", 0),actions_left_this_turn=observation.get("actions_left_this_turn", 0),allowed_categories=", ".join(observation.get("allowed_categories", []) or ["(none)"]),queue_len=len(queue),current_queue_preview=_compact_queue(queue),prior_verdicts_preview=_compact_prior_verdicts(verdicts),my_proposal_signals_preview=_render_my_proposal_signals(observation.get("my_proposal_signals") or {}),tier_hint=tier_hint or "(no tier hint for this task)",feedback=(observation.get("feedback") or "").strip() or "(none)",)# ------------------------------------------------------------------# Schema-coercion shim. Llama 3.1 in particular tends to:# 1. emit ``"slot_index": -1`` on ``propose_ad`` (it interprets# the slot field as "no slot yet"), which violates the# ``ge=0`` constraint and trips the Pydantic validator → the# whole step then falls back to the deterministic# ReactiveFraudster, polluting fallback metrics.# 2. include modify-only fields (``slot_index``, ``new_ad_copy``)# on a ``propose_ad`` action and vice-versa. These are# Optional in the schema so they pass validation, but they# poison the audit log because ``_serialize_fraudster_action``# copies them through verbatim.## We normalise both classes of issue here so the fallback only# fires on hard JSON / unknown-action errors.# ------------------------------------------------------------------def _coerce_payload(self, data: Dict[str, Any]) -> Dict[str, Any]:action_type = data.get("action_type")if action_type not in _FRAUDSTER_FIELDS_BY_TYPE:return dataallowed = _FRAUDSTER_FIELDS_BY_TYPE[action_type]out: Dict[str, Any] = {k: v for k, v in data.items() if k in allowed}# Llama 3.1 frequently emits ``targeting_summary`` (and other# free-text fields) as a structured dict like# {"age_range": [13, 65], "genders": ["male", "female"], ...}# or a list, rather than the schema-required string. Flatten# these into a deterministic string representation here so we# don't burn through the fallback budget on every other turn.for text_field in ("ad_copy","landing_page_blurb","targeting_summary","new_ad_copy","new_landing_page_blurb","new_targeting_summary",):if text_field in out and not isinstance(out[text_field], str):out[text_field] = _stringify_text_field(out[text_field])if action_type == "modify_pending_ad":slot = out.get("slot_index")if isinstance(slot, str):try:out["slot_index"] = int(slot)except (TypeError, ValueError):out.pop("slot_index", None)slot = out.get("slot_index")if isinstance(slot, int) and slot < 0:# -1 is meaningless for a modify; surface as missing# so the env returns its "modify_pending_ad requires# slot_index" error rather than silently rewriting# slot 0.out.pop("slot_index", None)return outdef _stringify_text_field(value: Any) -> str:"""Flatten a dict/list LLM emission into a comma-joined string.For dict inputs, joins ``key=value`` pairs (sub-lists comma-joined,sub-dicts JSON-encoded as a fallback). For list inputs, joins theitems by ``", "``. Anything else is rendered through ``str()``.The result is intended to preserve the LLM's intent as readabletext without crashing the schema validator."""if isinstance(value, dict):parts: List[str] = []for k, v in value.items():if isinstance(v, list):rendered = ",".join(str(item) for item in v)elif isinstance(v, dict):rendered = ";".join(f"{ki}={vi}" for ki, vi in v.items())else:rendered = str(v)parts.append(f"{k}={rendered}")return "; ".join(parts)if isinstance(value, list):return ", ".join(str(item) for item in value)return str(value)__all__ = ["LLMFraudster"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287"""LLM-backed Fraudster policy.Wraps :class:`.base.LLMPolicyBase` with the Fraudster system prompt andobservation-to-user-prompt assembly logic. Falls back to:class:`counterfeint.scripted.ReactiveFraudster` on any failure."""from __future__ import annotationsfrom typing import Any, Dict, List, Optionalfrom ..models import FraudsterActionfrom ..scripted._base import PolicyBasefrom ..scripted.fraudster import ReactiveFraudsterfrom .base import LLMPolicyBasefrom .prompts import FRAUDSTER_SYSTEM_PROMPT, FRAUDSTER_USER_TEMPLATEdef _compact_queue(queue: List[Dict[str, Any]], max_items: int = 8) -> str:"""Condense the current_queue field to a single-line preview."""if not queue:return "[empty]"own = [e for e in queue if e.get("is_my_proposal")]others = [e for e in queue if not e.get("is_my_proposal")]ordered = own + othersparts: List[str] = []for entry in ordered[:max_items]:ad_id = entry.get("ad_id", "?")cat = entry.get("category", "?")status = entry.get("status", "pending")slot = entry.get("slot_index")mine = (f" (mine, slot={slot})"if entry.get("is_my_proposal") and slot is not Noneelse (" (mine)" if entry.get("is_my_proposal") else ""))parts.append(f"{ad_id}/{cat}/{status}{mine}")trailer = "" if len(queue) <= max_items else f" +{len(queue) - max_items} more"return "; ".join(parts) + trailerdef _compact_prior_verdicts(verdicts: List[Dict[str, Any]], max_items: int = 5) -> str:if not verdicts:return "(none yet)"recent = verdicts[-max_items:]out: List[str] = []for v in recent:ad_id = v.get("ad_id", "?")decision = v.get("verdict", "?")conf = v.get("confidence")mine = " [mine]" if v.get("was_my_proposal") else ""conf_str = f"{conf:.2f}" if isinstance(conf, (int, float)) else "?"out.append(f"{ad_id}={decision}@{conf_str}{mine}")return " | ".join(out)# Columns rendered per proposal. Matches the Investigator's decided-ads# column set so both sides reason over the same signal vocabulary._PROPOSAL_SIGNAL_COLUMNS: List[str] = ["slot_index","investigator_verdict","category","country","account_age_days","domain","registrar","payment_id","payment_type","targeting_fingerprint",]def _render_my_proposal_signals(signals: Dict[str, Dict[str, Any]],*,max_ads: int = 8,) -> str:"""Render the Fraudster's per-proposal signal table as compact text."""if not signals:return "(no proposals submitted yet)"ad_ids = list(signals.keys())if len(ad_ids) > max_ads:kept = ad_ids[-max_ads:]trailer = f" (+{len(ad_ids) - max_ads} older proposals not shown)"else:kept = ad_idstrailer = ""lines: List[str] = []for ad_id in kept:entry = signals.get(ad_id, {}) or {}cells: List[str] = []for col in _PROPOSAL_SIGNAL_COLUMNS:if col in entry and entry[col] not in (None, ""):cells.append(f"{col}={entry[col]}")if cells:lines.append(f" {ad_id}: " + " | ".join(cells))return ("\n".join(lines) + trailer).rstrip()# Per-task-tier guidance appended to the user prompt. Easy tasks get a# louder fraud posture (so the Investigator can succeed at all in the# pre-training baseline); hard tasks get a stealthier posture (so the# trained Investigator's lift is meaningful). We deliberately surface# this in the USER prompt instead of mutating ``system_prompt`` so the# policy still sees a stable system role across all tasks (the system# prompt is the schema contract; per-task hints live in the user# message where the rest of the per-turn observation lives)._TASK_TIER_HINTS: Dict[str, str] = {"task_1": ("Tier hint (task_1, easy): use blatant fraud cues — obvious ""scam ad copy, unrelated targeting, cheap TLDs. The Investigator ""needs a clean baseline to learn against."),"task_2": ("Tier hint (task_2, medium): mix one or two subtle ads with the ""obvious ones; vary registrars / payment types across your slate."),"task_3": ("Tier hint (task_3, hard): aim for stealth. Construct fraud ""rings via shared payment_id / domain / targeting_fingerprint ""across 2-3 of your proposals so the only path to detection is ""cross-ad ring inference, not single-ad surface red flags."),"task_3_unseen": ("Tier hint (task_3_unseen, hard generalisation): same posture ""as task_3 but you are being evaluated on a held-out seed — do ""NOT collapse to a single template; vary your slate."),}def _task_tier_hint(task_id: str) -> str:return _TASK_TIER_HINTS.get(task_id or "", "")# Field whitelist per action_type. Keys not in the whitelist for the# action's type are dropped before Pydantic validation so a small# Llama-class model that mixes (e.g. ``slot_index`` on a ``propose_ad``,# or ``ad_copy`` on a ``modify_pending_ad``) still produces a valid# action instead of falling back. ``rationale`` and ``action_type`` are# always allowed._FRAUDSTER_FIELDS_BY_TYPE: Dict[str, set[str]] = {"propose_ad": {"action_type", "ad_copy", "category","landing_page_blurb", "targeting_summary", "rationale",},"modify_pending_ad": {"action_type", "slot_index","new_ad_copy", "new_landing_page_blurb", "rationale",},"end_turn": {"action_type", "rationale"},"commit_final": {"action_type", "rationale"},}class LLMFraudster(LLMPolicyBase):"""LLM Fraudster with a :class:`ReactiveFraudster` deterministic fallback."""system_prompt = FRAUDSTER_SYSTEM_PROMPTaction_model = FraudsterAction_log_name = "fraudster"def __init__(self,*,fallback_policy: Optional[PolicyBase] = None,fallback_seed: int = 0,**kwargs: Any,) -> None:if fallback_policy is None:fallback_policy = ReactiveFraudster(seed=fallback_seed)super().__init__(fallback_policy=fallback_policy, **kwargs)# ------------------------------------------------------------------def _build_user_prompt(self, observation: Dict[str, Any]) -> str:queue = observation.get("current_queue", []) or []verdicts = observation.get("prior_verdicts", []) or []tier_hint = _task_tier_hint(observation.get("task_id", ""))return FRAUDSTER_USER_TEMPLATE.format(round_number=observation.get("round_number", 0),rounds_remaining=observation.get("rounds_remaining", 0),proposals_used=observation.get("proposals_used", 0),proposals_remaining=observation.get("proposals_remaining", 0),actions_left_this_turn=observation.get("actions_left_this_turn", 0),allowed_categories=", ".join(observation.get("allowed_categories", []) or ["(none)"]),queue_len=len(queue),current_queue_preview=_compact_queue(queue),prior_verdicts_preview=_compact_prior_verdicts(verdicts),my_proposal_signals_preview=_render_my_proposal_signals(observation.get("my_proposal_signals") or {}),tier_hint=tier_hint or "(no tier hint for this task)",feedback=(observation.get("feedback") or "").strip() or "(none)",)# ------------------------------------------------------------------# Schema-coercion shim. Llama 3.1 in particular tends to:# 1. emit ``"slot_index": -1`` on ``propose_ad`` (it interprets# the slot field as "no slot yet"), which violates the# ``ge=0`` constraint and trips the Pydantic validator → the# whole step then falls back to the deterministic# ReactiveFraudster, polluting fallback metrics.# 2. include modify-only fields (``slot_index``, ``new_ad_copy``)# on a ``propose_ad`` action and vice-versa. These are# Optional in the schema so they pass validation, but they# poison the audit log because ``_serialize_fraudster_action``# copies them through verbatim.## We normalise both classes of issue here so the fallback only# fires on hard JSON / unknown-action errors.# ------------------------------------------------------------------def _coerce_payload(self, data: Dict[str, Any]) -> Dict[str, Any]:action_type = data.get("action_type")if action_type not in _FRAUDSTER_FIELDS_BY_TYPE:return dataallowed = _FRAUDSTER_FIELDS_BY_TYPE[action_type]out: Dict[str, Any] = {k: v for k, v in data.items() if k in allowed}# Llama 3.1 frequently emits ``targeting_summary`` (and other# free-text fields) as a structured dict like# {"age_range": [13, 65], "genders": ["male", "female"], ...}# or a list, rather than the schema-required string. Flatten# these into a deterministic string representation here so we# don't burn through the fallback budget on every other turn.for text_field in ("ad_copy","landing_page_blurb","targeting_summary","new_ad_copy","new_landing_page_blurb","new_targeting_summary",):if text_field in out and not isinstance(out[text_field], str):out[text_field] = _stringify_text_field(out[text_field])if action_type == "modify_pending_ad":slot = out.get("slot_index")if isinstance(slot, str):try:out["slot_index"] = int(slot)except (TypeError, ValueError):out.pop("slot_index", None)slot = out.get("slot_index")if isinstance(slot, int) and slot < 0:# -1 is meaningless for a modify; surface as missing# so the env returns its "modify_pending_ad requires# slot_index" error rather than silently rewriting# slot 0.out.pop("slot_index", None)return outdef _stringify_text_field(value: Any) -> str:"""Flatten a dict/list LLM emission into a comma-joined string.For dict inputs, joins ``key=value`` pairs (sub-lists comma-joined,sub-dicts JSON-encoded as a fallback). For list inputs, joins theitems by ``", "``. Anything else is rendered through ``str()``.The result is intended to preserve the LLM's intent as readabletext without crashing the schema validator."""if isinstance(value, dict):parts: List[str] = []for k, v in value.items():if isinstance(v, list):rendered = ",".join(str(item) for item in v)elif isinstance(v, dict):rendered = ";".join(f"{ki}={vi}" for ki, vi in v.items())else:rendered = str(v)parts.append(f"{k}={rendered}")return "; ".join(parts)if isinstance(value, list):return ", ".join(str(item) for item in value)return str(value)__all__ = ["LLMFraudster"]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102# CounterFeint: Teaching a 0.6B LLM to Investigate Ad Fraud
Ad fraud is a $100B/year problem, and catching the sophisticated stuff isn't classification - it's investigation. I built an RL environment to teach a small LLM how to do it.
---
## Why This Problem?
Platforms like Meta review billions of ads daily. The easy scams get caught by rule-based filters. The hard part is **sophisticated fraud** - ads that look legitimate on the surface but reveal their nature only when you dig into payment histories, inspect landing page registrars, or notice that five seemingly unrelated accounts share the same payment processor. This isn't classification. It's **sequential investigation under uncertainty**, where every investigation has a cost and every missed fraud ad goes live.
That workflow - triage, investigate, decide under budget pressure - is exactly where RL-trained LLMs could add real value. Not replacing human reviewers, but handling the first pass so humans focus on the hardest cases. I participated in the Meta Scalar OpenEnv Hackathon solo and chose this problem because it maps directly to how trust & safety teams operate, and sits at the intersection of multi-agent interaction, long-horizon planning, and real-world applicability.
## How CounterFeint Works
CounterFeint is an [OpenEnv](https://github.com/open-env/open-env)-compatible environment built around a **FraudArena** - a three-agent adversarial game:
- A **Fraudster** proposes ads designed to slip past review
- An **Investigator** reviews a queue of ads under a limited budget, investigates suspicious signals, and renders verdicts (approve / reject / escalate)
- An **Auditor** grades the Investigator's reasoning using deterministic scorecards
The Investigator is the agent I train. It's a **Qwen3-0.6B** model with QLoRA - going up against a frozen **Llama 3.1 8B** Fraudster. That's a ~13x parameter gap. The goal is to train the small model with GRPO until it catches what the big one tries to hide.

### Making It Realistic
Most RL environments for LLMs are clean abstractions - math problems, grid worlds, coding tasks. I wanted something messier, closer to how the real world works. A few design decisions that drove realism:
**Budget constraints force real triage.** Each investigation costs one budget point. On Task 3, there are 20 ads but only 35 budget points (~1.75 actions/ad) - you physically cannot investigate everything. Miss a fraud ad? It auto-approves at episode end with a -0.50 penalty. Same resource-allocation problem real reviewers face.
**Meta's safety stack, simulated.** One of six investigation tools is a `policy_classifier` simulating Llama Guard 3 / Purple Llama - returning safe/unsafe verdicts, triggered safety categories (S1-S13), and fraud markers (urgency language, fake authority, get-rich-quick). Every ad carries a citation from Meta's published policy taxonomy (e.g., `FSDP-IF-03`). The Auditor checks whether the Investigator cites the correct policy in its rationale - pushing toward evidence-based reasoning.
**CIB-modeled fraud rings.** Task 3 fraud networks are modeled on real Coordinated Inauthentic Behaviour operations from Meta's quarterly Adversarial Threat Reports - Ghana DigitSol-style cliques, Benin Digited-style chains, China-Russia hub-spoke networks. Individual ring members look borderline; the signal only emerges through cross-ad reasoning.
**Asymmetric rewards.** False negatives are penalized 5x more than false positives. Correct network link detection pays +0.40. A calibration bonus rewards agents whose stated confidence actually tracks their accuracy.
| Investigator Reward Flow | Fraudster Reward Flow |
|:---:|:---:|
|  |  |
## Training: GRPO on a T4
I used **GRPO** (Group Relative Policy Optimization) via HuggingFace TRL - the same algorithm family used in DeepSeek-R1's training. The key property: GRPO doesn't need human preference labels, just a **verifiable reward function** and sufficient reward variance across completions.
### The proxy reward
This was the biggest technical challenge. TRL's `GRPOTrainer` generates fresh completions internally and passes them to your reward function. My first runs showed a flat reward curve. Zero learning. The lookup was returning a constant penalty for everything.
The fix: a **per-completion proxy reward** that scores any (prompt, completion) pair without touching the environment server:
1. **Schema validity** - does the completion parse as valid JSON matching the action schema? (Partial credit for almost-valid JSON)
2. **Coherence** - does the referenced `ad_id` appear in the prompt's observation?
3. **Action correctness** - does the action class match what a successful episode recorded?
4. **Evidence quality** - does the rationale cite concrete signals (payment IDs, policy codes)?
5. **Conciseness** - shorter valid completions score higher
These components are **continuous**, not binary - giving GRPO meaningful variance even when most completions are mediocre. This design is consistent with how verifiable-reward GRPO recipes work in projects like Open-R1.
### QLoRA keeps it accessible
The entire setup fits on a free Colab T4: Qwen3-0.6B in 4-bit quantization (~400MB), LoRA adapter (rank 16, ~12MB trainable), plus the in-process environment and scripted opponents. No separate inference server needed during training.
## Challenges
A few things that cost real time:
**System prompt specificity.** Early prompts were too vague and the model invented action types, hallucinated ad IDs, or produced nonexistent investigation targets. Small models need precise instructions - explicit enum lists, concrete examples for every action type, and an explicit "output one JSON object per step, nothing else" directive. The difference between a working and broken prompt was surprisingly narrow.
**Context window overflow.** On Task 3 with 20 ads, accumulated investigation findings can exceed the context limit. I implemented truncation strategies that keep recent and relevant findings while trimming older history - but getting this right without losing critical cross-ad signals for fraud ring detection required careful tuning.
**HF vs local prompt handling.** The chat template for system/user prompts differs between local `model.generate()` and the HuggingFace Inference API. Ensuring `HFInvestigator` (training) and `LLMInvestigator` (inference) produce identical prompt assembly was essential for the trained adapter to transfer cleanly.
## Results
**Baseline (Qwen3-0.6B, 4-bit, no fine-tuning):**
| Task | Score |
| ---------------------------- | --------- |
| Task 1 (Basic Triage) | 0.543 |
| Task 2 (Sophisticated Fraud) | 0.576 |
| Task 3 (Fraud Networks) | 0.180 |
| **Mean** | **0.433** |
## Try It
**[Live environment on HuggingFace Spaces](https://huggingface.co/spaces/QuantumTransformer/CounterFeint)**
**[Training notebook](training/official_hf_training.ipynb)** - self-contained, runs on a Colab T4. Set `MODE = "demo"` for ~30 min, `MODE = "proper"` for ~3 hours.
**[GitHub](https://github.com/Abhijithreddydasari/CounterFeint)**
*Built by [Abhijith Reddy](https://github.com/Abhijithreddydasari) (solo) for the Meta Scalar OpenEnv PyTorch HuggingFace Hackathon, 2026.*123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367# CounterFeint - Training on Hugging FaceStep-by-step playbook for taking the Investigator from the current ~0.6 mean`grader_score` baseline to a trained checkpoint with reward + loss curves and aHF Hub release. All compute is sized for the **$30 HF Pro / Spaces credit**.---## TL;DR (the whole pipeline in 4 commands)1. **Baseline eval** -> `baseline_eval.ipynb` on a T4 Space (~30 min, $0.20)2. **Train** -> `official_hf_training.ipynb` on a T4 Space, `MODE = "proper"` (~3 hr, $1.20)3. **Compare** -> `compare_runs.ipynb` locally (free, no GPU)4. **Push** -> set `PUSH_TO_HUB = True` in the training notebook to ship the LoRAadapter + `eval_summary.json` to the HubThat's one full bake-off run. You can afford ~20 of them inside the $30 budget.---## 0. What lives where```counterfeint/training/├── baseline_eval.ipynb # NEW pre-training, multi-model bake-off├── official_hf_training.ipynb # main GRPO training + post-training eval├── compare_runs.ipynb # NEW aggregates baseline + trained runs into plots├── proxy_reward.py # deterministic reward function used during GRPO├── rollout.py # in-process episode collector (no HTTP server)├── smoke_official_hf.py # quick local pipeline check (skip if you trust the notebooks)└── TRAINING_GUIDE.md # this file```After a baseline + training run, the directory tree looks like:```baseline_outputs/├── qwen3-0.6b/baseline_results.json # per-episode rows for that model├── qwen2.5-1.5b/baseline_results.json├── qwen3-1.7b/baseline_results.json├── baseline_summary.json└── baseline_comparison.png # bar chart for the READMEoutputs/└── counterfeint-investigator-qwen3-06b-grpo/ # one directory per training run├── lora_adapter/ # LoRA weights + tokenizer│ ├── adapter_config.json│ └── adapter_model.safetensors├── eval_summary.json # before / after grader_score├── log_history.json # raw TRL log (loss, reward, kl)├── training_config.json # exact config that produced this run├── training_curves.png # combined loss / reward / KL plot└── eval_plot.png # per-episode before / after barscomparison_outputs/├── before_after_grader.png # headline plot├── training_curves.png # multi-run overlay└── comparison_table.csv```---## 1. Pick your compute laneYou have **two** sensible options for running these notebooks. Both work.### Lane A - HF Spaces with JupyterLab (uses HF credits directly)Best when: you specifically want to spend the $30 HF credit, want artifactsto live next to your Space, or want a persistent dev environment.1. Go to [https://huggingface.co/new-space](https://huggingface.co/new-space).2. Pick the **"JupyterLab"** Docker template (or "Notebooks").3. Hardware: **T4 small** (`$0.40 / hr`). For multi-model ablations you canbump to **A10G small** (`$1.05 / hr`) to halve wall time.4. Add a persistent disk (50 GB is plenty).5. Once the Space is running, open the JupyterLab UI and either:- `git clone` your repo into `/data/`, or- upload the `counterfeint/` directory through the file browser.6. Open `counterfeint/training/baseline_eval.ipynb` and run cell-by-cell.**Cost reality:** T4 at $0.40/hr means a 30 min baseline + 3 hr proper trainingrun is ~**$1.40**. You can do ~20 such cycles inside $30.### Lane B - Google Colab (free T4) + push artifacts to HF HubBest when: you want the cheapest path and don't care that the compute isGoogle's; the $30 stays available for HF Inference Endpoints later (e.g. theLlama 3.1 8B Fraudster for the demo video).1. Open Colab ([https://colab.research.google.com/](https://colab.research.google.com/)).2. `Runtime -> Change runtime type -> T4 GPU`.3. Upload `baseline_eval.ipynb` (or open from GitHub via `File -> Open notebook`).4. The first cell autodetects Colab and clones the repo for you.5. Run cells. Push the `outputs/` and `baseline_outputs/` folders to your HFdataset repo at the end.**Strong recommendation:** start in Colab to debug, then move to HF Spaces onlyonce you trust the pipeline end-to-end. This stretches the $30 further.---## 2. Run the BEFORE eval (baseline_eval.ipynb)### What it doesLoads each base model in `MODELS = [...]`, runs **9 episodes** per model(`task_1, task_2, task_3` x 3 held-out seeds), and writes:- `baseline_outputs/<tag>/baseline_results.json`- `baseline_outputs/baseline_summary.json`- `baseline_outputs/baseline_comparison.png`### How to run1. Open `baseline_eval.ipynb` on your chosen GPU.2. **Section 1** - run install cells. Restart the kernel if Colab asks.3. **Section 1** - run `notebook_login()` and paste your HF token (READ scopeis enough for base models). Skip if your token is already cached.4. **Section 2** - edit `MODELS` if you want to drop a model. Default list:```pythonMODELS = [("Qwen/Qwen3-0.6B", "qwen3-0.6b"),("Qwen/Qwen2.5-1.5B-Instruct", "qwen2.5-1.5b"),("Qwen/Qwen3-1.7B", "qwen3-1.7b"),]```5. Run all cells. Total wall time on T4: **~30 min** (3 models x ~10 min).6. Inspect `baseline_outputs/baseline_comparison.png`. This is your "BEFORE"figure for the writeup.### What the numbers should look likeFrom recent local runs (Qwen2.5-1.5B-Instruct with the in-process driver):| Task | Mean grader_score || ------- | ----------------- || task_1 | 0.84 || task_2 | 0.64 || task_3 | 0.32 || overall | 0.60 |If your numbers differ by more than 0.1 on `task_1`, double-check thein-process driver is healthy (no `[policy crash]` or `[env reject]` messagesin Section 4 output).### (optional) Push baselines to the HubIn Section 6, set:```pythonBASELINE_HUB_REPO_ID = "your-username/counterfeint-baselines"```then re-run that cell. Creates a public dataset repo with the JSON + PNGartifacts.---## 3. Run the training (official_hf_training.ipynb)### What it doesGRPO trains Qwen3-0.6B + LoRA on rollouts collected from your environment,using `proxy_reward_fn` for fast deterministic per-completion scoring. Thenruns the same eval suite the baseline notebook used and saves abefore/after summary.### How to run1. Open `official_hf_training.ipynb` on the same GPU.2. **Section 2** - pick a `MODE`:| MODE | seeds | epochs | rollouts | wall time (T4) | use for || -------- | ----- | ------ | -------- | -------------- | ----------------------------- || `smoke` | 2 | 1 | ~12 | ~10 min | "does the pipeline build" || `demo` | 6 | 1 | ~36 | ~40 min | demo deck / video screen-grab || `proper` | 12 | 2 | ~72 | ~3 hr | the run that ships || `full` | 24 | 3 | ~144 | ~6-8 hr | "final main result" (A10G) |Start with `proper`. If wall time matters, drop to `demo`.3. Set `BASE_MODEL`. Defaults to `Qwen/Qwen3-0.6B`. To re-run with a differentbase model later, change this and the `TRAINED_TAG`.4. Set `TRAINED_TAG` to something descriptive: e.g. `qwen3-0.6b-r16-proper`. Eachrun gets its own `outputs/<TRAINED_TAG>/` directory so they don't overwrite.5. Set `PUSH_TO_HUB`:```pythonPUSH_TO_HUB = TrueHUB_REPO_ID = "your-username/counterfeint-investigator"```6. Set `RUN_BEFORE_EVAL = True` for the FIRST run of any base model (so youget the matching "BEFORE" numbers for that run). For subsequent ablationson the SAME base model you can flip it to `False` to save ~10 min.7. Run all cells. Watch the Section 5 (training) cell — TRL prints`loss`, `reward`, `kl` every `logging_steps`. Reward should creep upmonotonically; if it's flat for the first 30 steps, see "Troubleshooting"below.### OutputsAfter the notebook finishes, `outputs/<TRAINED_TAG>/` contains everything youneed for the writeup:- `eval_summary.json` - mean before/after grader_score (the headline number)- `log_history.json` - raw TRL log- `training_curves.png` - combined loss / reward / KL plot- `eval_plot.png` - per-episode before/after bars- `adapter_model.safetensors` - the trained LoRA adapter- `training_config.json` - the exact config that produced this runIf `PUSH_TO_HUB = True`, all of these are mirrored to the HF Hub repo.---## 4. (optional) Run multiple training jobs for an ablationRepeat Section 3 with different settings to populate `compare_runs.ipynb`:```python# run #1BASE_MODEL = "Qwen/Qwen3-0.6B"TRAINED_TAG = "qwen3-0.6b-r16-proper"# run #2 (bigger LoRA)BASE_MODEL = "Qwen/Qwen3-0.6B"TRAINED_TAG = "qwen3-0.6b-r32-proper"LORA_R, LORA_ALPHA = 32, 64# run #3 (bigger base)BASE_MODEL = "Qwen/Qwen2.5-1.5B-Instruct"TRAINED_TAG = "qwen2.5-1.5b-r16-proper"```Each run writes a separate `outputs/<TRAINED_TAG>/` directory, so you can collect3-4 different ablations. Total budget: 3 runs x $1.20 = ~$3.60 on T4.---## 5. Aggregate everything (compare_runs.ipynb)Runs **locally** (no GPU). Just `jupyter notebook compare_runs.ipynb` oropen it in Cursor. It auto-discovers:- every `baseline_outputs/<tag>/baseline_results.json`- every `outputs/<run_tag>/eval_summary.json`- every `outputs/<run_tag>/log_history.json`and produces:- `comparison_outputs/before_after_grader.png` - the headline figure for yourREADME and slide deck- `comparison_outputs/training_curves.png` - reward / loss / KL overlaidacross all runs- `comparison_outputs/comparison_table.csv` - the table for the README---## 6. What to put in the README and submissionThe hackathon submission asks for:1. **A working training script** (Colab notebook) -> `official_hf_training.ipynb`2. **Loss + reward plots from a real run** -> `outputs/<TRAINED_TAG>/training_curves.png`and `comparison_outputs/training_curves.png`3. **Push your environment to a HF Space** -> already covered by the Spaceyou set up in Step 14. **README that motivates the problem and shows results** ->`comparison_outputs/before_after_grader.png` is your hero figureSuggested README skeleton:```markdown## Results| Model | Baseline | Trained | Delta ||--------------------|---------:|--------:|------:|| Qwen3-0.6B + LoRA | 0.60 | 0.78 | +0.18 || Qwen2.5-1.5B+LoRA | 0.66 | 0.83 | +0.17 |```---## 7. Fraudster LLM choice (your question)You're right that the Fraudster is **inference-only** — we never gradientupdate the Fraudster, only the Investigator. So you have flexibility here:| Option | Where it runs | Pros | Cons || --------------------------------- | ---------------------- | ------------------------------- | ---------------------------------------- || `ScriptedFraudster` (current) | in-process, free | deterministic, fast, free | not a "real" LLM adversary || `Llama-3.1-8B-Instruct` via HF IE | HF Inference Endpoints | strong, well-known model | ~$0.10/1M input + $0.10/1M output tokens || `Qwen2.5-7B-Instruct` via HF IE | HF Inference Endpoints | matches the Investigator family | similar cost to Llama 8B || `Llama-3.1-8B` via local Ollama | your laptop | free, private | slow on consumer GPU (~30s / proposal) |### My recommendation for **training rollouts**: keep `ScriptedFraudsterl`Reasons:1. **Determinism** - GRPO needs reproducible reward signal. An LLM Fraudsterwould inject sampling noise into the trajectory, which fights the proxyreward.2. **Speed** - rollouts are the bottleneck. Scripted is ~50x faster than8B inference.3. **Cost** - your $30 budget gets 6x more training time without LLM Fraudsterin the rollout loop.### My recommendation for the **demo / final eval**: Llama 3.1 8B Instruct via HF IEFor the demo video / final presentation eval, swap in a real LLM Fraudster soyour Investigator looks credible against a strong adversary. Steps:1. In `replay_match.py`, set `--fraudster-backend openai` and point it at aHF Inference Endpoint serving `meta-llama/Meta-Llama-3.1-8B-Instruct`.2. Run **3 demo episodes** (one per task) on `task_1 task_2 task_3` with aseed not in your eval set.3. Capture the `replay_*.md` transcripts for the slide deck.4. Total cost for ~3 episodes: well under $1.For pure HF-native, use `Qwen/Qwen2.5-7B-Instruct` instead — same family asthe Investigator and slightly cheaper to host.---## 8. Troubleshooting### "Reward is flat for the first 50 steps"Usually means the Investigator's completions are not parsing as valid JSON, so`proxy_reward_fn` returns the same penalty every step. Check:1. Section 4 of the training notebook prints the JSON-parse rate of collectedrollouts. If it's < 60%, the prompt template is wrong for this base model.2. For Qwen3 models, make sure `enable_thinking=False` is set on`HFInvestigator`. Otherwise the model emits `<thinking>...</thinking>`before the JSON and parsing fails.### "OOM during training"T4 has 16 GB. With 4-bit + LoRA you should fit Qwen3-0.6B with`batch_size=4` and `max_prompt_length=1024`. If you OOM:1. Drop `per_device_train_batch_size` to 2.2. Drop `max_prompt_length` to 768.3. Switch base model to `Qwen3-0.6B` (not 1.7B).### "GRPOConfig got an unexpected keyword argument 'max_prompt_length'"You're on an older TRL. The notebook handles this dynamically (uses`inspect.signature` to detect TRL's API), but if you're poking at the configmanually, set `tokenizer.model_max_length = 1024` instead.### "UnicodeDecodeError on Windows"Windows-only. Set `PYTHONUTF8=1` in the environment before running. Not anissue on Spaces / Colab (both are Linux).### "Hub push fails with 401"Re-run `notebook_login()` in Section 1 with a token that has **WRITE** scope(the baseline-only path can use READ).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367# CounterFeint - Training on Hugging FaceStep-by-step playbook for taking the Investigator from the current ~0.6 mean`grader_score` baseline to a trained checkpoint with reward + loss curves and aHF Hub release. All compute is sized for the **$30 HF Pro / Spaces credit**.---## TL;DR (the whole pipeline in 4 commands)1. **Baseline eval** -> `baseline_eval.ipynb` on a T4 Space (~30 min, $0.20)2. **Train** -> `official_hf_training.ipynb` on a T4 Space, `MODE = "proper"` (~3 hr, $1.20)3. **Compare** -> `compare_runs.ipynb` locally (free, no GPU)4. **Push** -> set `PUSH_TO_HUB = True` in the training notebook to ship the LoRAadapter + `eval_summary.json` to the HubThat's one full bake-off run. You can afford ~20 of them inside the $30 budget.---## 0. What lives where```counterfeint/training/├── baseline_eval.ipynb # NEW pre-training, multi-model bake-off├── official_hf_training.ipynb # main GRPO training + post-training eval├── compare_runs.ipynb # NEW aggregates baseline + trained runs into plots├── proxy_reward.py # deterministic reward function used during GRPO├── rollout.py # in-process episode collector (no HTTP server)├── smoke_official_hf.py # quick local pipeline check (skip if you trust the notebooks)└── TRAINING_GUIDE.md # this file```After a baseline + training run, the directory tree looks like:```baseline_outputs/├── qwen3-0.6b/baseline_results.json # per-episode rows for that model├── qwen2.5-1.5b/baseline_results.json├── qwen3-1.7b/baseline_results.json├── baseline_summary.json└── baseline_comparison.png # bar chart for the READMEoutputs/└── counterfeint-investigator-qwen3-06b-grpo/ # one directory per training run├── lora_adapter/ # LoRA weights + tokenizer│ ├── adapter_config.json│ └── adapter_model.safetensors├── eval_summary.json # before / after grader_score├── log_history.json # raw TRL log (loss, reward, kl)├── training_config.json # exact config that produced this run├── training_curves.png # combined loss / reward / KL plot└── eval_plot.png # per-episode before / after barscomparison_outputs/├── before_after_grader.png # headline plot├── training_curves.png # multi-run overlay└── comparison_table.csv```---## 1. Pick your compute laneYou have **two** sensible options for running these notebooks. Both work.### Lane A - HF Spaces with JupyterLab (uses HF credits directly)Best when: you specifically want to spend the $30 HF credit, want artifactsto live next to your Space, or want a persistent dev environment.1. Go to [https://huggingface.co/new-space](https://huggingface.co/new-space).2. Pick the **"JupyterLab"** Docker template (or "Notebooks").3. Hardware: **T4 small** (`$0.40 / hr`). For multi-model ablations you canbump to **A10G small** (`$1.05 / hr`) to halve wall time.4. Add a persistent disk (50 GB is plenty).5. Once the Space is running, open the JupyterLab UI and either:- `git clone` your repo into `/data/`, or- upload the `counterfeint/` directory through the file browser.6. Open `counterfeint/training/baseline_eval.ipynb` and run cell-by-cell.**Cost reality:** T4 at $0.40/hr means a 30 min baseline + 3 hr proper trainingrun is ~**$1.40**. You can do ~20 such cycles inside $30.### Lane B - Google Colab (free T4) + push artifacts to HF HubBest when: you want the cheapest path and don't care that the compute isGoogle's; the $30 stays available for HF Inference Endpoints later (e.g. theLlama 3.1 8B Fraudster for the demo video).1. Open Colab ([https://colab.research.google.com/](https://colab.research.google.com/)).2. `Runtime -> Change runtime type -> T4 GPU`.3. Upload `baseline_eval.ipynb` (or open from GitHub via `File -> Open notebook`).4. The first cell autodetects Colab and clones the repo for you.5. Run cells. Push the `outputs/` and `baseline_outputs/` folders to your HFdataset repo at the end.**Strong recommendation:** start in Colab to debug, then move to HF Spaces onlyonce you trust the pipeline end-to-end. This stretches the $30 further.---## 2. Run the BEFORE eval (baseline_eval.ipynb)### What it doesLoads each base model in `MODELS = [...]`, runs **9 episodes** per model(`task_1, task_2, task_3` x 3 held-out seeds), and writes:- `baseline_outputs/<tag>/baseline_results.json`- `baseline_outputs/baseline_summary.json`- `baseline_outputs/baseline_comparison.png`### How to run1. Open `baseline_eval.ipynb` on your chosen GPU.2. **Section 1** - run install cells. Restart the kernel if Colab asks.3. **Section 1** - run `notebook_login()` and paste your HF token (READ scopeis enough for base models). Skip if your token is already cached.4. **Section 2** - edit `MODELS` if you want to drop a model. Default list:```pythonMODELS = [("Qwen/Qwen3-0.6B", "qwen3-0.6b"),("Qwen/Qwen2.5-1.5B-Instruct", "qwen2.5-1.5b"),("Qwen/Qwen3-1.7B", "qwen3-1.7b"),]```5. Run all cells. Total wall time on T4: **~30 min** (3 models x ~10 min).6. Inspect `baseline_outputs/baseline_comparison.png`. This is your "BEFORE"figure for the writeup.### What the numbers should look likeFrom recent local runs (Qwen2.5-1.5B-Instruct with the in-process driver):| Task | Mean grader_score || ------- | ----------------- || task_1 | 0.84 || task_2 | 0.64 || task_3 | 0.32 || overall | 0.60 |If your numbers differ by more than 0.1 on `task_1`, double-check thein-process driver is healthy (no `[policy crash]` or `[env reject]` messagesin Section 4 output).### (optional) Push baselines to the HubIn Section 6, set:```pythonBASELINE_HUB_REPO_ID = "your-username/counterfeint-baselines"```then re-run that cell. Creates a public dataset repo with the JSON + PNGartifacts.---## 3. Run the training (official_hf_training.ipynb)### What it doesGRPO trains Qwen3-0.6B + LoRA on rollouts collected from your environment,using `proxy_reward_fn` for fast deterministic per-completion scoring. Thenruns the same eval suite the baseline notebook used and saves abefore/after summary.### How to run1. Open `official_hf_training.ipynb` on the same GPU.2. **Section 2** - pick a `MODE`:| MODE | seeds | epochs | rollouts | wall time (T4) | use for || -------- | ----- | ------ | -------- | -------------- | ----------------------------- || `smoke` | 2 | 1 | ~12 | ~10 min | "does the pipeline build" || `demo` | 6 | 1 | ~36 | ~40 min | demo deck / video screen-grab || `proper` | 12 | 2 | ~72 | ~3 hr | the run that ships || `full` | 24 | 3 | ~144 | ~6-8 hr | "final main result" (A10G) |Start with `proper`. If wall time matters, drop to `demo`.3. Set `BASE_MODEL`. Defaults to `Qwen/Qwen3-0.6B`. To re-run with a differentbase model later, change this and the `TRAINED_TAG`.4. Set `TRAINED_TAG` to something descriptive: e.g. `qwen3-0.6b-r16-proper`. Eachrun gets its own `outputs/<TRAINED_TAG>/` directory so they don't overwrite.5. Set `PUSH_TO_HUB`:```pythonPUSH_TO_HUB = TrueHUB_REPO_ID = "your-username/counterfeint-investigator"```6. Set `RUN_BEFORE_EVAL = True` for the FIRST run of any base model (so youget the matching "BEFORE" numbers for that run). For subsequent ablationson the SAME base model you can flip it to `False` to save ~10 min.7. Run all cells. Watch the Section 5 (training) cell — TRL prints`loss`, `reward`, `kl` every `logging_steps`. Reward should creep upmonotonically; if it's flat for the first 30 steps, see "Troubleshooting"below.### OutputsAfter the notebook finishes, `outputs/<TRAINED_TAG>/` contains everything youneed for the writeup:- `eval_summary.json` - mean before/after grader_score (the headline number)- `log_history.json` - raw TRL log- `training_curves.png` - combined loss / reward / KL plot- `eval_plot.png` - per-episode before/after bars- `adapter_model.safetensors` - the trained LoRA adapter- `training_config.json` - the exact config that produced this runIf `PUSH_TO_HUB = True`, all of these are mirrored to the HF Hub repo.---## 4. (optional) Run multiple training jobs for an ablationRepeat Section 3 with different settings to populate `compare_runs.ipynb`:```python# run #1BASE_MODEL = "Qwen/Qwen3-0.6B"TRAINED_TAG = "qwen3-0.6b-r16-proper"# run #2 (bigger LoRA)BASE_MODEL = "Qwen/Qwen3-0.6B"TRAINED_TAG = "qwen3-0.6b-r32-proper"LORA_R, LORA_ALPHA = 32, 64# run #3 (bigger base)BASE_MODEL = "Qwen/Qwen2.5-1.5B-Instruct"TRAINED_TAG = "qwen2.5-1.5b-r16-proper"```Each run writes a separate `outputs/<TRAINED_TAG>/` directory, so you can collect3-4 different ablations. Total budget: 3 runs x $1.20 = ~$3.60 on T4.---## 5. Aggregate everything (compare_runs.ipynb)Runs **locally** (no GPU). Just `jupyter notebook compare_runs.ipynb` oropen it in Cursor. It auto-discovers:- every `baseline_outputs/<tag>/baseline_results.json`- every `outputs/<run_tag>/eval_summary.json`- every `outputs/<run_tag>/log_history.json`and produces:- `comparison_outputs/before_after_grader.png` - the headline figure for yourREADME and slide deck- `comparison_outputs/training_curves.png` - reward / loss / KL overlaidacross all runs- `comparison_outputs/comparison_table.csv` - the table for the README---## 6. What to put in the README and submissionThe hackathon submission asks for:1. **A working training script** (Colab notebook) -> `official_hf_training.ipynb`2. **Loss + reward plots from a real run** -> `outputs/<TRAINED_TAG>/training_curves.png`and `comparison_outputs/training_curves.png`3. **Push your environment to a HF Space** -> already covered by the Spaceyou set up in Step 14. **README that motivates the problem and shows results** ->`comparison_outputs/before_after_grader.png` is your hero figureSuggested README skeleton:```markdown## Results| Model | Baseline | Trained | Delta ||--------------------|---------:|--------:|------:|| Qwen3-0.6B + LoRA | 0.60 | 0.78 | +0.18 || Qwen2.5-1.5B+LoRA | 0.66 | 0.83 | +0.17 |```---## 7. Fraudster LLM choice (your question)You're right that the Fraudster is **inference-only** — we never gradientupdate the Fraudster, only the Investigator. So you have flexibility here:| Option | Where it runs | Pros | Cons || --------------------------------- | ---------------------- | ------------------------------- | ---------------------------------------- || `ScriptedFraudster` (current) | in-process, free | deterministic, fast, free | not a "real" LLM adversary || `Llama-3.1-8B-Instruct` via HF IE | HF Inference Endpoints | strong, well-known model | ~$0.10/1M input + $0.10/1M output tokens || `Qwen2.5-7B-Instruct` via HF IE | HF Inference Endpoints | matches the Investigator family | similar cost to Llama 8B || `Llama-3.1-8B` via local Ollama | your laptop | free, private | slow on consumer GPU (~30s / proposal) |### My recommendation for **training rollouts**: keep `ScriptedFraudsterl`Reasons:1. **Determinism** - GRPO needs reproducible reward signal. An LLM Fraudsterwould inject sampling noise into the trajectory, which fights the proxyreward.2. **Speed** - rollouts are the bottleneck. Scripted is ~50x faster than8B inference.3. **Cost** - your $30 budget gets 6x more training time without LLM Fraudsterin the rollout loop.### My recommendation for the **demo / final eval**: Llama 3.1 8B Instruct via HF IEFor the demo video / final presentation eval, swap in a real LLM Fraudster soyour Investigator looks credible against a strong adversary. Steps:1. In `replay_match.py`, set `--fraudster-backend openai` and point it at aHF Inference Endpoint serving `meta-llama/Meta-Llama-3.1-8B-Instruct`.2. Run **3 demo episodes** (one per task) on `task_1 task_2 task_3` with aseed not in your eval set.3. Capture the `replay_*.md` transcripts for the slide deck.4. Total cost for ~3 episodes: well under $1.For pure HF-native, use `Qwen/Qwen2.5-7B-Instruct` instead — same family asthe Investigator and slightly cheaper to host.---## 8. Troubleshooting### "Reward is flat for the first 50 steps"Usually means the Investigator's completions are not parsing as valid JSON, so`proxy_reward_fn` returns the same penalty every step. Check:1. Section 4 of the training notebook prints the JSON-parse rate of collectedrollouts. If it's < 60%, the prompt template is wrong for this base model.2. For Qwen3 models, make sure `enable_thinking=False` is set on`HFInvestigator`. Otherwise the model emits `<thinking>...</thinking>`before the JSON and parsing fails.### "OOM during training"T4 has 16 GB. With 4-bit + LoRA you should fit Qwen3-0.6B with`batch_size=4` and `max_prompt_length=1024`. If you OOM:1. Drop `per_device_train_batch_size` to 2.2. Drop `max_prompt_length` to 768.3. Switch base model to `Qwen3-0.6B` (not 1.7B).### "GRPOConfig got an unexpected keyword argument 'max_prompt_length'"You're on an older TRL. The notebook handles this dynamically (uses`inspect.signature` to detect TRL's API), but if you're poking at the configmanually, set `tokenizer.model_max_length = 1024` instead.### "UnicodeDecodeError on Windows"Windows-only. Set `PYTHONUTF8=1` in the environment before running. Not anissue on Spaces / Colab (both are Linux).### "Hub push fails with 401"Re-run `notebook_login()` in Section 1 with a token that has **WRITE** scope(the baseline-only path can use READ).
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512{"cells": [{"cell_type": "markdown","id": "896b8c3f","metadata": {},"source": ["# CounterFeint - Baseline Evaluation (BEFORE training)\n","\n","This notebook produces the **BEFORE** numbers your submission compares against.\n","\n","## What it does\n","\n","1. Loads one or more base models (no LoRA, no fine-tuning) as the Investigator\n","2. Runs each model on a fixed set of held-out seeds (`task_1`, `task_2`, `task_3`)\n","3. Reports `grader_score`, `verdicts`, `fallback_rate` per task per seed\n","4. Saves results to `baseline_outputs/<model_tag>/baseline_results.json`\n","5. Renders a single comparison plot across models\n","\n","## Why a separate notebook\n","\n","Running this **before** training gives you:\n","\n","- A cheap (~30 min) reproducibility check on HF Spaces hardware\n","- A multi-model bake-off so you pick the best base before training\n","- A reusable JSON file the training notebook can load for its `BEFORE` panel without re-running the base model\n","\n","## Models compared\n","\n","| Model | Params | Why |\n","|---|---|---|\n","| `Qwen/Qwen3-0.6B` | 0.6B | Smallest Qwen3, default training target |\n","| `Qwen/Qwen2.5-1.5B-Instruct` | 1.5B | Production Investigator (current baseline) |\n","| `Qwen/Qwen3-1.7B` | 1.7B | Bigger Qwen3, fits on T4 with 4-bit |\n","\n","You can edit the `MODELS` list in Section 2 to add/remove.\n","\n","## Hardware\n","\n","Runs on a single T4 (~16 GB VRAM). Each model takes ~10 min for 9 episodes (3 tasks × 3 seeds)."]},{"cell_type": "markdown","id": "7fb0c26a","metadata": {},"source": ["## Section 1 - Setup\n","\n","Same install logic as `official_hf_training.ipynb`. If Colab asks you to restart after install, do so and resume from Section 2."]},{"cell_type": "code","execution_count": null,"id": "dc628696","metadata": {},"outputs": [],"source": ["import os\n","import sys\n","import subprocess\n","from pathlib import Path\n","\n","IN_COLAB = \"google.colab\" in sys.modules\n","print(f\"In Colab: {IN_COLAB}\")\n","\n","if IN_COLAB:\n"," repo_dir = Path(\"/content/OpenEnv-Hackathon\")\n"," if not repo_dir.exists():\n"," subprocess.run(\n"," [\"git\", \"clone\", \"https://github.com/Abhijithreddydasari/OpenEnv-Hackathon.git\", str(repo_dir)],\n"," check=True,\n"," )\n"," REPO_ROOT = repo_dir\n","else:\n"," # On HF Spaces the kernel may start in /data or /home/user\n"," _candidates = [\n"," Path('/data/counterfeint'),\n"," Path('/home/user/app/counterfeint'),\n"," Path('/home/user/app'),\n"," ]\n"," here = Path.cwd().resolve()\n"," REPO_ROOT = next(\n"," (p for p in [here, *here.parents, *_candidates] if (p / 'counterfeint' / 'server').exists() or (p / 'server').exists()),\n"," here,\n"," )\n"," # If we found a path like /data/counterfeint where server/ is directly inside,\n"," # we need to go one level up for the repo root\n"," if (REPO_ROOT / 'server').exists() and not (REPO_ROOT / 'counterfeint').exists():\n"," REPO_ROOT = REPO_ROOT.parent\n","\n","print(f\"REPO_ROOT = {REPO_ROOT}\")\n","os.chdir(REPO_ROOT)\n","if str(REPO_ROOT) not in sys.path:\n"," sys.path.insert(0, str(REPO_ROOT))"]},{"cell_type": "code","execution_count": null,"id": "493dc487","metadata": {},"outputs": [],"source": ["def pip_install(args):\n"," subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", *args], check=True)\n","\n","print(\"Installing CounterFeint (editable) ...\")\n","pip_install([\"-e\", \".\"])\n","\n","print(\"Installing eval dependencies ...\")\n","pip_install([\n"," \"torch\", \"transformers>=4.46.0\", \"accelerate>=1.1.0\",\n"," \"bitsandbytes>=0.44.0\", \"datasets>=3.0.0\",\n"," \"matplotlib>=3.8.0\", \"huggingface_hub>=0.26.0\",\n"," \"nest_asyncio>=1.6.0\",\n","])\n","print(\"Done.\")"]},{"cell_type": "code","execution_count": null,"id": "7d5fa3de","metadata": {},"outputs": [],"source": ["try:\n"," from huggingface_hub import notebook_login\n"," notebook_login()\n","except Exception as exc:\n"," print(f\"[hf-login] skipped: {exc}\")"]},{"cell_type": "code","execution_count": null,"id": "86d9a05e","metadata": {},"outputs": [],"source": ["import torch\n","import nest_asyncio\n","nest_asyncio.apply()\n","\n","print(f\"PyTorch: {torch.__version__}\")\n","print(f\"CUDA : {torch.cuda.is_available()}\")\n","if torch.cuda.is_available():\n"," print(f\"GPU : {torch.cuda.get_device_name(0)}\")\n"," print(f\"VRAM : {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB\")"]},{"cell_type": "markdown","id": "648c9020","metadata": {},"source": ["## Section 2 - Models to evaluate\n","\n","Edit `MODELS` to control which base models you run. Each entry is `(repo_id, short_tag)`. The short tag is used in filenames and the comparison plot.\n","\n","For a quick first run, comment out the bigger models. For the final submission, run all three so you have a multi-model bake-off in your README."]},{"cell_type": "code","execution_count": null,"id": "b9a87a43","metadata": {},"outputs": [],"source": ["import json\n","\n","MODELS = [\n"," (\"Qwen/Qwen3-0.6B\", \"qwen3-0.6b\"),\n"," (\"Qwen/Qwen2.5-1.5B-Instruct\", \"qwen2.5-1.5b\"),\n"," (\"Qwen/Qwen3-1.7B\", \"qwen3-1.7b\"),\n"," # Comment models out to skip them. Each adds ~10 min on T4.\n","]\n","\n","TASKS = [\"task_1\", \"task_2\", \"task_3\"]\n","EVAL_SEEDS = [101, 103, 107] # held-out seeds\n","MAX_STEPS_PER_EPISODE = 80\n","\n","LOAD_IN_4BIT = True\n","MAX_NEW_TOKENS = 128\n","TEMPERATURE = 0.3\n","\n","OUT_ROOT = Path(\"baseline_outputs\")\n","OUT_ROOT.mkdir(parents=True, exist_ok=True)\n","\n","print(f\"Will evaluate {len(MODELS)} model(s) on \"\n"," f\"{len(TASKS)} tasks x {len(EVAL_SEEDS)} seeds = \"\n"," f\"{len(MODELS) * len(TASKS) * len(EVAL_SEEDS)} episodes\")\n","for repo, tag in MODELS:\n"," print(f\" - {tag:<14} ({repo})\")"]},{"cell_type": "markdown","id": "bca6692a","metadata": {},"source": ["## Section 3 - In-process eval driver\n","\n","Runs one full multi-agent episode in-process (no HTTP server). Same env code as the production HTTP path.\n","\n","The Fraudster + Auditor are scripted (deterministic) so the only thing that varies between models is the Investigator's policy."]},{"cell_type": "code","execution_count": null,"id": "4e73367c","metadata": {},"outputs": [],"source": ["from counterfeint.scripted import HeuristicAuditor, ReactiveFraudster\n","from counterfeint.server.referee import RefereeEnvironment\n","\n","\n","def run_episode(investigator, *, task_id, seed, max_steps=80):\n"," env = RefereeEnvironment()\n"," env.reset_match(task_id=task_id, seed=seed)\n","\n"," fraudster = ReactiveFraudster(seed=42)\n"," auditor = HeuristicAuditor()\n"," handlers = {\n"," \"fraudster_turn\": (fraudster, env.build_fraudster_observation, env.step_as_fraudster),\n"," \"investigator_turn\":(investigator, env.build_investigator_observation, env.step_as_investigator),\n"," \"audit_phase\": (auditor, env.build_auditor_observation, env.step_as_auditor),\n"," }\n","\n"," step_idx = 0\n"," n_verdicts = 0\n"," n_inv_steps = 0\n"," fb_at_start = getattr(investigator, \"fallback_count\", 0)\n"," calls_at_start = getattr(investigator, \"call_count\", 0)\n","\n"," while env.phase in handlers:\n"," current_phase = env.phase\n"," policy, build_obs, step_fn = handlers[current_phase]\n"," if current_phase != \"audit_phase\" and step_idx >= max_steps:\n"," break\n"," obs = build_obs().model_dump()\n"," for slot in (\"last_prompt\", \"last_completion\", \"last_error\"):\n"," if hasattr(policy, slot):\n"," setattr(policy, slot, None)\n"," try:\n"," action = policy.act(obs)\n"," except Exception as exc:\n"," print(f\" [policy crash] {current_phase}: {type(exc).__name__}: {exc}\")\n"," break\n"," try:\n"," step_fn(action)\n"," except Exception as exc:\n"," print(f\" [env reject] {current_phase}: {type(exc).__name__}: {exc}\")\n"," break\n"," if current_phase != \"audit_phase\":\n"," step_idx += 1\n"," if current_phase == \"investigator_turn\":\n"," n_inv_steps += 1\n"," if getattr(action, \"action_type\", None) in (\"verdict\", \"link_accounts\"):\n"," n_verdicts += 1\n","\n"," state = env.state\n"," fb_used = getattr(investigator, \"fallback_count\", 0) - fb_at_start\n"," calls_used = getattr(investigator, \"call_count\", 0) - calls_at_start\n","\n"," return {\n"," \"task_id\": task_id,\n"," \"seed\": seed,\n"," \"grader_score\": getattr(state, \"grader_score\", None),\n"," \"end_reason\": getattr(state, \"end_reason\", None),\n"," \"stopped_phase\": env.phase,\n"," \"n_inv_steps\": n_inv_steps,\n"," \"n_verdicts\": n_verdicts,\n"," \"investigator_calls\": int(calls_used),\n"," \"investigator_fallback\": int(fb_used),\n"," }"]},{"cell_type": "markdown","id": "6b65bbfe","metadata": {},"source": ["## Section 4 - Run baseline eval across all models\n","\n","Loads each model in turn (4-bit), runs all eval episodes, then unloads it before loading the next. Memory should stay under 8 GB on T4 even for the 1.7B model."]},{"cell_type": "code","execution_count": null,"id": "3115c1a7","metadata": {},"outputs": [],"source": ["import gc\n","import time\n","from counterfeint.agents import HFInvestigator\n","\n","all_results = {} # tag -> list of episode dicts\n","\n","for repo, tag in MODELS:\n"," print(f\"\\n{'='*70}\")\n"," print(f\"Loading {tag} ({repo}) ...\")\n"," print(f\"{'='*70}\")\n"," t0 = time.perf_counter()\n"," investigator = HFInvestigator.from_pretrained(\n"," repo,\n"," load_in_4bit=LOAD_IN_4BIT,\n"," max_new_tokens=MAX_NEW_TOKENS,\n"," temperature=TEMPERATURE,\n"," do_sample=True,\n"," enable_thinking=False,\n"," )\n"," print(f\"Loaded in {time.perf_counter() - t0:.1f}s\")\n","\n"," rows = []\n"," eval_t0 = time.perf_counter()\n"," for task_id in TASKS:\n"," for seed in EVAL_SEEDS:\n"," r = run_episode(\n"," investigator,\n"," task_id=task_id, seed=seed,\n"," max_steps=MAX_STEPS_PER_EPISODE,\n"," )\n"," rows.append(r)\n"," print(\n"," f\" {task_id} seed={seed:>3}: \"\n"," f\"grader={(r['grader_score'] or 0.0):+.3f} \"\n"," f\"verdicts={r['n_verdicts']:>2} \"\n"," f\"fallback={r['investigator_fallback']}/{r['investigator_calls']} \"\n"," f\"end={r['end_reason']}\"\n"," )\n"," eval_elapsed = time.perf_counter() - eval_t0\n"," print(f\"\\nEval took {eval_elapsed/60:.1f} min ({eval_elapsed/len(rows):.1f}s/episode)\")\n","\n"," out_dir = OUT_ROOT / tag\n"," out_dir.mkdir(parents=True, exist_ok=True)\n"," with open(out_dir / \"baseline_results.json\", \"w\") as f:\n"," json.dump({\n"," \"model_repo\": repo,\n"," \"model_tag\": tag,\n"," \"config\": {\n"," \"load_in_4bit\": LOAD_IN_4BIT,\n"," \"max_new_tokens\": MAX_NEW_TOKENS,\n"," \"temperature\": TEMPERATURE,\n"," \"max_steps_per_episode\": MAX_STEPS_PER_EPISODE,\n"," \"eval_seeds\": EVAL_SEEDS,\n"," \"tasks\": TASKS,\n"," },\n"," \"rows\": rows,\n"," \"elapsed_seconds\": round(eval_elapsed, 1),\n"," }, f, indent=2)\n"," print(f\"Wrote {out_dir/'baseline_results.json'}\")\n","\n"," all_results[tag] = rows\n","\n"," del investigator\n"," gc.collect()\n"," if torch.cuda.is_available():\n"," torch.cuda.empty_cache()\n","\n","print(\"\\n\" + \"=\" * 70)\n","print(\"ALL MODELS DONE\")\n","print(\"=\" * 70)"]},{"cell_type": "markdown","id": "e149ad5a","metadata": {},"source": ["## Section 5 - Summary table + comparison plot\n","\n","A clean per-model summary, plus the figure your README and slide deck will reference."]},{"cell_type": "code","execution_count": null,"id": "4cf2ea68","metadata": {},"outputs": [],"source": ["def _gs(r): return r[\"grader_score\"] or 0.0\n","\n","summary_rows = []\n","for tag, rows in all_results.items():\n"," by_task = {t: [] for t in TASKS}\n"," for r in rows:\n"," by_task[r[\"task_id\"]].append(_gs(r))\n"," overall = sum(_gs(r) for r in rows) / max(1, len(rows))\n"," fb = sum(r[\"investigator_fallback\"] for r in rows)\n"," calls = sum(r[\"investigator_calls\"] for r in rows)\n"," summary_rows.append({\n"," \"model\": tag,\n"," \"task_1_mean\": sum(by_task[\"task_1\"]) / max(1, len(by_task[\"task_1\"])),\n"," \"task_2_mean\": sum(by_task[\"task_2\"]) / max(1, len(by_task[\"task_2\"])),\n"," \"task_3_mean\": sum(by_task[\"task_3\"]) / max(1, len(by_task[\"task_3\"])),\n"," \"overall_mean\": overall,\n"," \"fallback_rate\": fb / max(1, calls),\n"," })\n","\n","print(f\"\\n{'model':<14} {'task_1':>8} {'task_2':>8} {'task_3':>8} {'mean':>8} {'fb-rate':>8}\")\n","print(\"-\" * 60)\n","for s in summary_rows:\n"," print(\n"," f\"{s['model']:<14} \"\n"," f\"{s['task_1_mean']:>8.3f} \"\n"," f\"{s['task_2_mean']:>8.3f} \"\n"," f\"{s['task_3_mean']:>8.3f} \"\n"," f\"{s['overall_mean']:>8.3f} \"\n"," f\"{s['fallback_rate']:>8.2%}\"\n"," )\n","\n","with open(OUT_ROOT / \"baseline_summary.json\", \"w\") as f:\n"," json.dump(summary_rows, f, indent=2)\n","print(f\"\\nWrote {OUT_ROOT/'baseline_summary.json'}\")"]},{"cell_type": "code","execution_count": null,"id": "995e389c","metadata": {},"outputs": [],"source": ["import matplotlib.pyplot as plt\n","import numpy as np\n","\n","if summary_rows:\n"," tags = [s[\"model\"] for s in summary_rows]\n"," width = 0.18\n"," x = np.arange(len(tags))\n","\n"," fig, ax = plt.subplots(figsize=(10, 5.5))\n"," ax.bar(x - 1.5 * width, [s[\"task_1_mean\"] for s in summary_rows], width, label=\"task_1\", color=\"#4C72B0\")\n"," ax.bar(x - 0.5 * width, [s[\"task_2_mean\"] for s in summary_rows], width, label=\"task_2\", color=\"#55A868\")\n"," ax.bar(x + 0.5 * width, [s[\"task_3_mean\"] for s in summary_rows], width, label=\"task_3\", color=\"#C44E52\")\n"," ax.bar(x + 1.5 * width, [s[\"overall_mean\"] for s in summary_rows], width, label=\"overall\", color=\"#8172B2\")\n","\n"," ax.set_xticks(x)\n"," ax.set_xticklabels(tags, rotation=15, ha=\"right\")\n"," ax.set_ylabel(\"Mean grader_score\")\n"," ax.set_title(\"Baseline grader_score across models (no training)\")\n"," ax.set_ylim(0, 1.0)\n"," ax.axhline(0.45, ls=\"--\", color=\"gray\", lw=1, label=\"trainable bar\")\n"," ax.legend(ncol=5, fontsize=9, loc=\"upper right\")\n"," ax.grid(axis=\"y\", alpha=0.3)\n"," fig.tight_layout()\n"," plot_path = OUT_ROOT / \"baseline_comparison.png\"\n"," fig.savefig(plot_path, dpi=140, bbox_inches=\"tight\")\n"," plt.show()\n"," print(f\"\\nWrote {plot_path}\")\n","else:\n"," print(\"No results to plot.\")"]},{"cell_type": "markdown","id": "802d3ec2","metadata": {},"source": ["## Section 6 - (optional) Push artifacts to HF Hub\n","\n","Pushes the baseline JSON + plot to a HF dataset repo so judges can browse them. Set `BASELINE_HUB_REPO_ID` and re-run."]},{"cell_type": "code","execution_count": null,"id": "dcefbda3","metadata": {},"outputs": [],"source": ["BASELINE_HUB_REPO_ID = \"\" # e.g. \"your-username/counterfeint-baselines\"\n","\n","if BASELINE_HUB_REPO_ID:\n"," from huggingface_hub import HfApi, create_repo\n"," api = HfApi()\n"," create_repo(BASELINE_HUB_REPO_ID, repo_type=\"dataset\", exist_ok=True, private=False)\n"," api.upload_folder(\n"," folder_path=str(OUT_ROOT),\n"," repo_id=BASELINE_HUB_REPO_ID,\n"," repo_type=\"dataset\",\n"," commit_message=\"Upload CounterFeint baseline eval artifacts\",\n"," )\n"," print(f\"Pushed to https://huggingface.co/datasets/{BASELINE_HUB_REPO_ID}\")\n","else:\n"," print(\"Set BASELINE_HUB_REPO_ID to push results.\")"]}],"metadata": {"kernelspec": {"display_name": "Python 3","language": "python","name": "python3"},"language_info": {"name": "python","version": "3.11"}},"nbformat": 4,"nbformat_minor": 5}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512{"cells": [{"cell_type": "markdown","id": "896b8c3f","metadata": {},"source": ["# CounterFeint - Baseline Evaluation (BEFORE training)\n","\n","This notebook produces the **BEFORE** numbers your submission compares against.\n","\n","## What it does\n","\n","1. Loads one or more base models (no LoRA, no fine-tuning) as the Investigator\n","2. Runs each model on a fixed set of held-out seeds (`task_1`, `task_2`, `task_3`)\n","3. Reports `grader_score`, `verdicts`, `fallback_rate` per task per seed\n","4. Saves results to `baseline_outputs/<model_tag>/baseline_results.json`\n","5. Renders a single comparison plot across models\n","\n","## Why a separate notebook\n","\n","Running this **before** training gives you:\n","\n","- A cheap (~30 min) reproducibility check on HF Spaces hardware\n","- A multi-model bake-off so you pick the best base before training\n","- A reusable JSON file the training notebook can load for its `BEFORE` panel without re-running the base model\n","\n","## Models compared\n","\n","| Model | Params | Why |\n","|---|---|---|\n","| `Qwen/Qwen3-0.6B` | 0.6B | Smallest Qwen3, default training target |\n","| `Qwen/Qwen2.5-1.5B-Instruct` | 1.5B | Production Investigator (current baseline) |\n","| `Qwen/Qwen3-1.7B` | 1.7B | Bigger Qwen3, fits on T4 with 4-bit |\n","\n","You can edit the `MODELS` list in Section 2 to add/remove.\n","\n","## Hardware\n","\n","Runs on a single T4 (~16 GB VRAM). Each model takes ~10 min for 9 episodes (3 tasks × 3 seeds)."]},{"cell_type": "markdown","id": "7fb0c26a","metadata": {},"source": ["## Section 1 - Setup\n","\n","Same install logic as `official_hf_training.ipynb`. If Colab asks you to restart after install, do so and resume from Section 2."]},{"cell_type": "code","execution_count": null,"id": "dc628696","metadata": {},"outputs": [],"source": ["import os\n","import sys\n","import subprocess\n","from pathlib import Path\n","\n","IN_COLAB = \"google.colab\" in sys.modules\n","print(f\"In Colab: {IN_COLAB}\")\n","\n","if IN_COLAB:\n"," repo_dir = Path(\"/content/OpenEnv-Hackathon\")\n"," if not repo_dir.exists():\n"," subprocess.run(\n"," [\"git\", \"clone\", \"https://github.com/Abhijithreddydasari/OpenEnv-Hackathon.git\", str(repo_dir)],\n"," check=True,\n"," )\n"," REPO_ROOT = repo_dir\n","else:\n"," # On HF Spaces the kernel may start in /data or /home/user\n"," _candidates = [\n"," Path('/data/counterfeint'),\n"," Path('/home/user/app/counterfeint'),\n"," Path('/home/user/app'),\n"," ]\n"," here = Path.cwd().resolve()\n"," REPO_ROOT = next(\n"," (p for p in [here, *here.parents, *_candidates] if (p / 'counterfeint' / 'server').exists() or (p / 'server').exists()),\n"," here,\n"," )\n"," # If we found a path like /data/counterfeint where server/ is directly inside,\n"," # we need to go one level up for the repo root\n"," if (REPO_ROOT / 'server').exists() and not (REPO_ROOT / 'counterfeint').exists():\n"," REPO_ROOT = REPO_ROOT.parent\n","\n","print(f\"REPO_ROOT = {REPO_ROOT}\")\n","os.chdir(REPO_ROOT)\n","if str(REPO_ROOT) not in sys.path:\n"," sys.path.insert(0, str(REPO_ROOT))"]},{"cell_type": "code","execution_count": null,"id": "493dc487","metadata": {},"outputs": [],"source": ["def pip_install(args):\n"," subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", *args], check=True)\n","\n","print(\"Installing CounterFeint (editable) ...\")\n","pip_install([\"-e\", \".\"])\n","\n","print(\"Installing eval dependencies ...\")\n","pip_install([\n"," \"torch\", \"transformers>=4.46.0\", \"accelerate>=1.1.0\",\n"," \"bitsandbytes>=0.44.0\", \"datasets>=3.0.0\",\n"," \"matplotlib>=3.8.0\", \"huggingface_hub>=0.26.0\",\n"," \"nest_asyncio>=1.6.0\",\n","])\n","print(\"Done.\")"]},{"cell_type": "code","execution_count": null,"id": "7d5fa3de","metadata": {},"outputs": [],"source": ["try:\n"," from huggingface_hub import notebook_login\n"," notebook_login()\n","except Exception as exc:\n"," print(f\"[hf-login] skipped: {exc}\")"]},{"cell_type": "code","execution_count": null,"id": "86d9a05e","metadata": {},"outputs": [],"source": ["import torch\n","import nest_asyncio\n","nest_asyncio.apply()\n","\n","print(f\"PyTorch: {torch.__version__}\")\n","print(f\"CUDA : {torch.cuda.is_available()}\")\n","if torch.cuda.is_available():\n"," print(f\"GPU : {torch.cuda.get_device_name(0)}\")\n"," print(f\"VRAM : {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB\")"]},{"cell_type": "markdown","id": "648c9020","metadata": {},"source": ["## Section 2 - Models to evaluate\n","\n","Edit `MODELS` to control which base models you run. Each entry is `(repo_id, short_tag)`. The short tag is used in filenames and the comparison plot.\n","\n","For a quick first run, comment out the bigger models. For the final submission, run all three so you have a multi-model bake-off in your README."]},{"cell_type": "code","execution_count": null,"id": "b9a87a43","metadata": {},"outputs": [],"source": ["import json\n","\n","MODELS = [\n"," (\"Qwen/Qwen3-0.6B\", \"qwen3-0.6b\"),\n"," (\"Qwen/Qwen2.5-1.5B-Instruct\", \"qwen2.5-1.5b\"),\n"," (\"Qwen/Qwen3-1.7B\", \"qwen3-1.7b\"),\n"," # Comment models out to skip them. Each adds ~10 min on T4.\n","]\n","\n","TASKS = [\"task_1\", \"task_2\", \"task_3\"]\n","EVAL_SEEDS = [101, 103, 107] # held-out seeds\n","MAX_STEPS_PER_EPISODE = 80\n","\n","LOAD_IN_4BIT = True\n","MAX_NEW_TOKENS = 128\n","TEMPERATURE = 0.3\n","\n","OUT_ROOT = Path(\"baseline_outputs\")\n","OUT_ROOT.mkdir(parents=True, exist_ok=True)\n","\n","print(f\"Will evaluate {len(MODELS)} model(s) on \"\n"," f\"{len(TASKS)} tasks x {len(EVAL_SEEDS)} seeds = \"\n"," f\"{len(MODELS) * len(TASKS) * len(EVAL_SEEDS)} episodes\")\n","for repo, tag in MODELS:\n"," print(f\" - {tag:<14} ({repo})\")"]},{"cell_type": "markdown","id": "bca6692a","metadata": {},"source": ["## Section 3 - In-process eval driver\n","\n","Runs one full multi-agent episode in-process (no HTTP server). Same env code as the production HTTP path.\n","\n","The Fraudster + Auditor are scripted (deterministic) so the only thing that varies between models is the Investigator's policy."]},{"cell_type": "code","execution_count": null,"id": "4e73367c","metadata": {},"outputs": [],"source": ["from counterfeint.scripted import HeuristicAuditor, ReactiveFraudster\n","from counterfeint.server.referee import RefereeEnvironment\n","\n","\n","def run_episode(investigator, *, task_id, seed, max_steps=80):\n"," env = RefereeEnvironment()\n"," env.reset_match(task_id=task_id, seed=seed)\n","\n"," fraudster = ReactiveFraudster(seed=42)\n"," auditor = HeuristicAuditor()\n"," handlers = {\n"," \"fraudster_turn\": (fraudster, env.build_fraudster_observation, env.step_as_fraudster),\n"," \"investigator_turn\":(investigator, env.build_investigator_observation, env.step_as_investigator),\n"," \"audit_phase\": (auditor, env.build_auditor_observation, env.step_as_auditor),\n"," }\n","\n"," step_idx = 0\n"," n_verdicts = 0\n"," n_inv_steps = 0\n"," fb_at_start = getattr(investigator, \"fallback_count\", 0)\n"," calls_at_start = getattr(investigator, \"call_count\", 0)\n","\n"," while env.phase in handlers:\n"," current_phase = env.phase\n"," policy, build_obs, step_fn = handlers[current_phase]\n"," if current_phase != \"audit_phase\" and step_idx >= max_steps:\n"," break\n"," obs = build_obs().model_dump()\n"," for slot in (\"last_prompt\", \"last_completion\", \"last_error\"):\n"," if hasattr(policy, slot):\n"," setattr(policy, slot, None)\n"," try:\n"," action = policy.act(obs)\n"," except Exception as exc:\n"," print(f\" [policy crash] {current_phase}: {type(exc).__name__}: {exc}\")\n"," break\n"," try:\n"," step_fn(action)\n"," except Exception as exc:\n"," print(f\" [env reject] {current_phase}: {type(exc).__name__}: {exc}\")\n"," break\n"," if current_phase != \"audit_phase\":\n"," step_idx += 1\n"," if current_phase == \"investigator_turn\":\n"," n_inv_steps += 1\n"," if getattr(action, \"action_type\", None) in (\"verdict\", \"link_accounts\"):\n"," n_verdicts += 1\n","\n"," state = env.state\n"," fb_used = getattr(investigator, \"fallback_count\", 0) - fb_at_start\n"," calls_used = getattr(investigator, \"call_count\", 0) - calls_at_start\n","\n"," return {\n"," \"task_id\": task_id,\n"," \"seed\": seed,\n"," \"grader_score\": getattr(state, \"grader_score\", None),\n"," \"end_reason\": getattr(state, \"end_reason\", None),\n"," \"stopped_phase\": env.phase,\n"," \"n_inv_steps\": n_inv_steps,\n"," \"n_verdicts\": n_verdicts,\n"," \"investigator_calls\": int(calls_used),\n"," \"investigator_fallback\": int(fb_used),\n"," }"]},{"cell_type": "markdown","id": "6b65bbfe","metadata": {},"source": ["## Section 4 - Run baseline eval across all models\n","\n","Loads each model in turn (4-bit), runs all eval episodes, then unloads it before loading the next. Memory should stay under 8 GB on T4 even for the 1.7B model."]},{"cell_type": "code","execution_count": null,"id": "3115c1a7","metadata": {},"outputs": [],"source": ["import gc\n","import time\n","from counterfeint.agents import HFInvestigator\n","\n","all_results = {} # tag -> list of episode dicts\n","\n","for repo, tag in MODELS:\n"," print(f\"\\n{'='*70}\")\n"," print(f\"Loading {tag} ({repo}) ...\")\n"," print(f\"{'='*70}\")\n"," t0 = time.perf_counter()\n"," investigator = HFInvestigator.from_pretrained(\n"," repo,\n"," load_in_4bit=LOAD_IN_4BIT,\n"," max_new_tokens=MAX_NEW_TOKENS,\n"," temperature=TEMPERATURE,\n"," do_sample=True,\n"," enable_thinking=False,\n"," )\n"," print(f\"Loaded in {time.perf_counter() - t0:.1f}s\")\n","\n"," rows = []\n"," eval_t0 = time.perf_counter()\n"," for task_id in TASKS:\n"," for seed in EVAL_SEEDS:\n"," r = run_episode(\n"," investigator,\n"," task_id=task_id, seed=seed,\n"," max_steps=MAX_STEPS_PER_EPISODE,\n"," )\n"," rows.append(r)\n"," print(\n"," f\" {task_id} seed={seed:>3}: \"\n"," f\"grader={(r['grader_score'] or 0.0):+.3f} \"\n"," f\"verdicts={r['n_verdicts']:>2} \"\n"," f\"fallback={r['investigator_fallback']}/{r['investigator_calls']} \"\n"," f\"end={r['end_reason']}\"\n"," )\n"," eval_elapsed = time.perf_counter() - eval_t0\n"," print(f\"\\nEval took {eval_elapsed/60:.1f} min ({eval_elapsed/len(rows):.1f}s/episode)\")\n","\n"," out_dir = OUT_ROOT / tag\n"," out_dir.mkdir(parents=True, exist_ok=True)\n"," with open(out_dir / \"baseline_results.json\", \"w\") as f:\n"," json.dump({\n"," \"model_repo\": repo,\n"," \"model_tag\": tag,\n"," \"config\": {\n"," \"load_in_4bit\": LOAD_IN_4BIT,\n"," \"max_new_tokens\": MAX_NEW_TOKENS,\n"," \"temperature\": TEMPERATURE,\n"," \"max_steps_per_episode\": MAX_STEPS_PER_EPISODE,\n"," \"eval_seeds\": EVAL_SEEDS,\n"," \"tasks\": TASKS,\n"," },\n"," \"rows\": rows,\n"," \"elapsed_seconds\": round(eval_elapsed, 1),\n"," }, f, indent=2)\n"," print(f\"Wrote {out_dir/'baseline_results.json'}\")\n","\n"," all_results[tag] = rows\n","\n"," del investigator\n"," gc.collect()\n"," if torch.cuda.is_available():\n"," torch.cuda.empty_cache()\n","\n","print(\"\\n\" + \"=\" * 70)\n","print(\"ALL MODELS DONE\")\n","print(\"=\" * 70)"]},{"cell_type": "markdown","id": "e149ad5a","metadata": {},"source": ["## Section 5 - Summary table + comparison plot\n","\n","A clean per-model summary, plus the figure your README and slide deck will reference."]},{"cell_type": "code","execution_count": null,"id": "4cf2ea68","metadata": {},"outputs": [],"source": ["def _gs(r): return r[\"grader_score\"] or 0.0\n","\n","summary_rows = []\n","for tag, rows in all_results.items():\n"," by_task = {t: [] for t in TASKS}\n"," for r in rows:\n"," by_task[r[\"task_id\"]].append(_gs(r))\n"," overall = sum(_gs(r) for r in rows) / max(1, len(rows))\n"," fb = sum(r[\"investigator_fallback\"] for r in rows)\n"," calls = sum(r[\"investigator_calls\"] for r in rows)\n"," summary_rows.append({\n"," \"model\": tag,\n"," \"task_1_mean\": sum(by_task[\"task_1\"]) / max(1, len(by_task[\"task_1\"])),\n"," \"task_2_mean\": sum(by_task[\"task_2\"]) / max(1, len(by_task[\"task_2\"])),\n"," \"task_3_mean\": sum(by_task[\"task_3\"]) / max(1, len(by_task[\"task_3\"])),\n"," \"overall_mean\": overall,\n"," \"fallback_rate\": fb / max(1, calls),\n"," })\n","\n","print(f\"\\n{'model':<14} {'task_1':>8} {'task_2':>8} {'task_3':>8} {'mean':>8} {'fb-rate':>8}\")\n","print(\"-\" * 60)\n","for s in summary_rows:\n"," print(\n"," f\"{s['model']:<14} \"\n"," f\"{s['task_1_mean']:>8.3f} \"\n"," f\"{s['task_2_mean']:>8.3f} \"\n"," f\"{s['task_3_mean']:>8.3f} \"\n"," f\"{s['overall_mean']:>8.3f} \"\n"," f\"{s['fallback_rate']:>8.2%}\"\n"," )\n","\n","with open(OUT_ROOT / \"baseline_summary.json\", \"w\") as f:\n"," json.dump(summary_rows, f, indent=2)\n","print(f\"\\nWrote {OUT_ROOT/'baseline_summary.json'}\")"]},{"cell_type": "code","execution_count": null,"id": "995e389c","metadata": {},"outputs": [],"source": ["import matplotlib.pyplot as plt\n","import numpy as np\n","\n","if summary_rows:\n"," tags = [s[\"model\"] for s in summary_rows]\n"," width = 0.18\n"," x = np.arange(len(tags))\n","\n"," fig, ax = plt.subplots(figsize=(10, 5.5))\n"," ax.bar(x - 1.5 * width, [s[\"task_1_mean\"] for s in summary_rows], width, label=\"task_1\", color=\"#4C72B0\")\n"," ax.bar(x - 0.5 * width, [s[\"task_2_mean\"] for s in summary_rows], width, label=\"task_2\", color=\"#55A868\")\n"," ax.bar(x + 0.5 * width, [s[\"task_3_mean\"] for s in summary_rows], width, label=\"task_3\", color=\"#C44E52\")\n"," ax.bar(x + 1.5 * width, [s[\"overall_mean\"] for s in summary_rows], width, label=\"overall\", color=\"#8172B2\")\n","\n"," ax.set_xticks(x)\n"," ax.set_xticklabels(tags, rotation=15, ha=\"right\")\n"," ax.set_ylabel(\"Mean grader_score\")\n"," ax.set_title(\"Baseline grader_score across models (no training)\")\n"," ax.set_ylim(0, 1.0)\n"," ax.axhline(0.45, ls=\"--\", color=\"gray\", lw=1, label=\"trainable bar\")\n"," ax.legend(ncol=5, fontsize=9, loc=\"upper right\")\n"," ax.grid(axis=\"y\", alpha=0.3)\n"," fig.tight_layout()\n"," plot_path = OUT_ROOT / \"baseline_comparison.png\"\n"," fig.savefig(plot_path, dpi=140, bbox_inches=\"tight\")\n"," plt.show()\n"," print(f\"\\nWrote {plot_path}\")\n","else:\n"," print(\"No results to plot.\")"]},{"cell_type": "markdown","id": "802d3ec2","metadata": {},"source": ["## Section 6 - (optional) Push artifacts to HF Hub\n","\n","Pushes the baseline JSON + plot to a HF dataset repo so judges can browse them. Set `BASELINE_HUB_REPO_ID` and re-run."]},{"cell_type": "code","execution_count": null,"id": "dcefbda3","metadata": {},"outputs": [],"source": ["BASELINE_HUB_REPO_ID = \"\" # e.g. \"your-username/counterfeint-baselines\"\n","\n","if BASELINE_HUB_REPO_ID:\n"," from huggingface_hub import HfApi, create_repo\n"," api = HfApi()\n"," create_repo(BASELINE_HUB_REPO_ID, repo_type=\"dataset\", exist_ok=True, private=False)\n"," api.upload_folder(\n"," folder_path=str(OUT_ROOT),\n"," repo_id=BASELINE_HUB_REPO_ID,\n"," repo_type=\"dataset\",\n"," commit_message=\"Upload CounterFeint baseline eval artifacts\",\n"," )\n"," print(f\"Pushed to https://huggingface.co/datasets/{BASELINE_HUB_REPO_ID}\")\n","else:\n"," print(\"Set BASELINE_HUB_REPO_ID to push results.\")"]}],"metadata": {"kernelspec": {"display_name": "Python 3","language": "python","name": "python3"},"language_info": {"name": "python","version": "3.11"}},"nbformat": 4,"nbformat_minor": 5}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370{"cells": [{"cell_type": "markdown","id": "8a4a82ed","metadata": {},"source": ["# CounterFeint - Compare runs\n","\n","Aggregates baseline + post-training results into a single set of plots + tables for the README and slide deck.\n","\n","## What it expects to find\n","\n","| Path | Source |\n","|---|---|\n","| `baseline_outputs/<model_tag>/baseline_results.json` | `baseline_eval.ipynb` |\n","| `outputs/<run_tag>/eval_summary.json` | `official_hf_training.ipynb` |\n","| `outputs/<run_tag>/log_history.json` | `official_hf_training.ipynb` |\n","| `outputs/<run_tag>/training_config.json` | `official_hf_training.ipynb` |\n","\n","You can run multiple training jobs back-to-back with different `RUN_TAG` values (e.g. `qwen3-0.6b-r16`, `qwen3-0.6b-r32`, `qwen2.5-1.5b-r16`) and this notebook will pull them all into one comparison.\n","\n","## Outputs\n","\n","- `comparison_outputs/before_after_grader.png` - bar chart of mean grader_score per task, baseline vs each trained run\n","- `comparison_outputs/training_curves.png` - reward + loss curves overlaid for all runs\n","- `comparison_outputs/comparison_table.csv` - one row per (run, task) for the README\n","\n","These are the figures you drop into your README and slide deck."]},{"cell_type": "code","execution_count": null,"id": "6fceaaef","metadata": {},"outputs": [],"source": ["import json\n","from pathlib import Path\n","from typing import Any, Dict, List\n","\n","import matplotlib.pyplot as plt\n","import numpy as np\n","\n","REPO_ROOT = next(\n"," (p for p in [Path.cwd(), *Path.cwd().parents] if (p / \"counterfeint\" / \"server\").exists()),\n"," Path.cwd(),\n",")\n","print(f\"REPO_ROOT = {REPO_ROOT}\")\n","\n","BASELINE_DIR = REPO_ROOT / \"baseline_outputs\"\n","TRAINED_DIR = REPO_ROOT / \"outputs\"\n","OUT_DIR = REPO_ROOT / \"comparison_outputs\"\n","OUT_DIR.mkdir(parents=True, exist_ok=True)\n","\n","print(f\"baseline_dir = {BASELINE_DIR} (exists={BASELINE_DIR.exists()})\")\n","print(f\"trained_dir = {TRAINED_DIR} (exists={TRAINED_DIR.exists()})\")"]},{"cell_type": "code","execution_count": null,"id": "2e02d660","metadata": {},"outputs": [],"source": ["def _episode_score(r: Dict[str, Any]) -> float:\n"," return float(r.get(\"grader_score\") or 0.0)\n","\n","\n","def per_task_means(rows: List[Dict[str, Any]]) -> Dict[str, float]:\n"," by_task: Dict[str, List[float]] = {}\n"," for r in rows:\n"," by_task.setdefault(r[\"task_id\"], []).append(_episode_score(r))\n"," out = {t: (sum(v) / len(v) if v else 0.0) for t, v in by_task.items()}\n"," if rows:\n"," out[\"overall\"] = sum(_episode_score(r) for r in rows) / len(rows)\n"," else:\n"," out[\"overall\"] = 0.0\n"," return out\n","\n","\n","def collect_baselines(baseline_dir: Path) -> List[Dict[str, Any]]:\n"," out = []\n"," if not baseline_dir.exists():\n"," return out\n"," for sub in sorted(p for p in baseline_dir.iterdir() if p.is_dir()):\n"," f = sub / \"baseline_results.json\"\n"," if not f.exists():\n"," continue\n"," data = json.loads(f.read_text())\n"," rows = data.get(\"rows\", [])\n"," out.append({\n"," \"kind\": \"baseline\",\n"," \"tag\": data.get(\"model_tag\", sub.name),\n"," \"model\": data.get(\"model_repo\", \"?\"),\n"," \"means\": per_task_means(rows),\n"," \"rows\": rows,\n"," })\n"," return out\n","\n","\n","def collect_trained(trained_dir: Path) -> List[Dict[str, Any]]:\n"," out = []\n"," if not trained_dir.exists():\n"," return out\n"," for sub in sorted(p for p in trained_dir.iterdir() if p.is_dir()):\n"," f = sub / \"eval_summary.json\"\n"," if not f.exists():\n"," continue\n"," data = json.loads(f.read_text())\n"," # eval_summary.json from official_hf_training.ipynb has shape:\n"," # { \"summary\": {...}, \"before\": [episode_dict, ...], \"after\": [...] }\n"," before_rows = data.get(\"before\") or []\n"," after_rows = data.get(\"after\") or []\n"," # base_model lives in training_config.json next to it.\n"," base_model = \"?\"\n"," cfg_path = sub / \"training_config.json\"\n"," if cfg_path.exists():\n"," try:\n"," cfg = json.loads(cfg_path.read_text())\n"," base_model = cfg.get(\"base_model\") or cfg.get(\"BASE_MODEL\", \"?\")\n"," except Exception:\n"," pass\n"," log_json = sub / \"log_history.json\"\n"," out.append({\n"," \"kind\": \"trained\",\n"," \"tag\": sub.name,\n"," \"model\": base_model,\n"," \"before_means\": per_task_means(before_rows),\n"," \"after_means\": per_task_means(after_rows),\n"," \"before_rows\": before_rows,\n"," \"after_rows\": after_rows,\n"," \"log_history_json\": str(log_json) if log_json.exists() else None,\n"," })\n"," return out\n","\n","\n","baselines = collect_baselines(BASELINE_DIR)\n","trained = collect_trained(TRAINED_DIR)\n","print(f\"Found {len(baselines)} baseline run(s) and {len(trained)} trained run(s).\")\n","for b in baselines:\n"," print(f\" baseline: {b['tag']:<20} -> overall={b['means']['overall']:.3f}\")\n","for t in trained:\n"," print(\n"," f\" trained : {t['tag']:<20} -> \"\n"," f\"before={t['before_means']['overall']:.3f} \"\n"," f\"after={t['after_means']['overall']:.3f} \"\n"," f\"delta={(t['after_means']['overall']-t['before_means']['overall']):+.3f}\"\n"," )"]},{"cell_type": "markdown","id": "32acc51e","metadata": {},"source": ["## Section 2 - Per-task mean grader_score (baseline vs trained)\n","\n","The headline plot for the README. Bars are mean grader_score per task; one group per run."]},{"cell_type": "code","execution_count": null,"id": "3684dcc4","metadata": {},"outputs": [],"source": ["labels = []\n","overall = []\n","t1, t2, t3 = [], [], []\n","colors = []\n","\n","for b in baselines:\n"," labels.append(f\"base:{b['tag']}\")\n"," overall.append(b[\"means\"][\"overall\"])\n"," t1.append(b[\"means\"].get(\"task_1\", 0.0))\n"," t2.append(b[\"means\"].get(\"task_2\", 0.0))\n"," t3.append(b[\"means\"].get(\"task_3\", 0.0))\n"," colors.append(\"#888888\")\n","\n","for t in trained:\n"," labels.append(f\"trained:{t['tag']}\")\n"," overall.append(t[\"after_means\"][\"overall\"])\n"," t1.append(t[\"after_means\"].get(\"task_1\", 0.0))\n"," t2.append(t[\"after_means\"].get(\"task_2\", 0.0))\n"," t3.append(t[\"after_means\"].get(\"task_3\", 0.0))\n"," colors.append(\"#4C72B0\")\n","\n","if labels:\n"," width = 0.20\n"," x = np.arange(len(labels))\n"," fig, ax = plt.subplots(figsize=(max(8, 0.9 * len(labels) + 4), 5.5))\n"," ax.bar(x - 1.5 * width, t1, width, label=\"task_1\", color=\"#4C72B0\")\n"," ax.bar(x - 0.5 * width, t2, width, label=\"task_2\", color=\"#55A868\")\n"," ax.bar(x + 0.5 * width, t3, width, label=\"task_3\", color=\"#C44E52\")\n"," ax.bar(x + 1.5 * width, overall, width, label=\"overall\", color=\"#8172B2\")\n"," ax.set_xticks(x)\n"," ax.set_xticklabels(labels, rotation=20, ha=\"right\")\n"," ax.set_ylabel(\"Mean grader_score\")\n"," ax.set_title(\"Per-task grader_score: baselines vs trained\")\n"," ax.set_ylim(0, 1.0)\n"," ax.axhline(0.45, ls=\"--\", color=\"gray\", lw=1, label=\"trainable bar (0.45)\")\n"," ax.axhline(0.80, ls=\"--\", color=\"green\", lw=1, label=\"strong bar (0.80)\")\n"," ax.legend(ncol=3, fontsize=9, loc=\"upper right\")\n"," ax.grid(axis=\"y\", alpha=0.3)\n"," fig.tight_layout()\n"," out_path = OUT_DIR / \"before_after_grader.png\"\n"," fig.savefig(out_path, dpi=140, bbox_inches=\"tight\")\n"," plt.show()\n"," print(f\"Wrote {out_path}\")\n","else:\n"," print(\"No runs found. Run baseline_eval.ipynb and/or official_hf_training.ipynb first.\")"]},{"cell_type": "markdown","id": "691907a5","metadata": {},"source": ["## Section 3 - Training curves overlaid\n","\n","Reads `log_history.json` from each trained run and overlays reward, loss, and KL curves."]},{"cell_type": "code","execution_count": null,"id": "01df2e8a","metadata": {},"outputs": [],"source": ["def load_log_history(path: str):\n"," raw = json.loads(Path(path).read_text())\n"," rows = []\n"," for entry in raw:\n"," step = entry.get(\"step\")\n"," if step is None:\n"," continue\n"," rows.append({\n"," \"step\": int(step),\n"," \"loss\": entry.get(\"loss\"),\n"," \"reward\": entry.get(\"reward\"),\n"," \"kl\": entry.get(\"kl\"),\n"," })\n"," return rows\n","\n","\n","curves = []\n","for t in trained:\n"," if not t[\"log_history_json\"]:\n"," continue\n"," try:\n"," rows = load_log_history(t[\"log_history_json\"])\n"," except Exception as exc:\n"," print(f\" [skip] {t['tag']}: cannot read log_history.json ({exc})\")\n"," continue\n"," if not rows:\n"," continue\n"," curves.append({\"tag\": t[\"tag\"], \"rows\": rows})\n","\n","if not curves:\n"," print(\"No log_history.json files found yet. Run official_hf_training.ipynb first.\")\n","else:\n"," fig, axes = plt.subplots(1, 3, figsize=(16, 5))\n"," for c in curves:\n"," steps = [r[\"step\"] for r in c[\"rows\"]]\n"," losses = [r[\"loss\"] for r in c[\"rows\"]]\n"," rewards = [r[\"reward\"] for r in c[\"rows\"]]\n"," kls = [r[\"kl\"] for r in c[\"rows\"]]\n"," s_l = [s for s, v in zip(steps, losses) if v is not None]\n"," v_l = [v for v in losses if v is not None]\n"," s_r = [s for s, v in zip(steps, rewards) if v is not None]\n"," v_r = [v for v in rewards if v is not None]\n"," s_k = [s for s, v in zip(steps, kls) if v is not None]\n"," v_k = [v for v in kls if v is not None]\n"," if v_l: axes[0].plot(s_l, v_l, label=c[\"tag\"], lw=1.5)\n"," if v_r: axes[1].plot(s_r, v_r, label=c[\"tag\"], lw=1.5)\n"," if v_k: axes[2].plot(s_k, v_k, label=c[\"tag\"], lw=1.5)\n"," axes[0].set_title(\"GRPO loss\"); axes[0].set_xlabel(\"step\"); axes[0].set_ylabel(\"loss\")\n"," axes[1].set_title(\"GRPO mean reward\"); axes[1].set_xlabel(\"step\"); axes[1].set_ylabel(\"reward\")\n"," axes[2].set_title(\"GRPO KL divergence\"); axes[2].set_xlabel(\"step\"); axes[2].set_ylabel(\"kl\")\n"," for ax in axes:\n"," ax.grid(alpha=0.3)\n"," ax.legend(fontsize=9)\n"," fig.tight_layout()\n"," out_path = OUT_DIR / \"training_curves.png\"\n"," fig.savefig(out_path, dpi=140, bbox_inches=\"tight\")\n"," plt.show()\n"," print(f\"Wrote {out_path}\")"]},{"cell_type": "markdown","id": "c1b209db","metadata": {},"source": ["## Section 4 - CSV table for the README"]},{"cell_type": "code","execution_count": null,"id": "01bc436c","metadata": {},"outputs": [],"source": ["import csv\n","\n","table_rows = []\n","for b in baselines:\n"," for task in (\"task_1\", \"task_2\", \"task_3\", \"overall\"):\n"," table_rows.append({\n"," \"kind\": \"baseline\",\n"," \"run_tag\": b[\"tag\"],\n"," \"model\": b[\"model\"],\n"," \"task\": task,\n"," \"score\": round(b[\"means\"].get(task, 0.0), 4),\n"," \"delta_vs_baseline\": \"\",\n"," })\n","\n","baseline_lookup = {(b[\"tag\"], task): b[\"means\"].get(task, 0.0) for b in baselines for task in (\"task_1\", \"task_2\", \"task_3\", \"overall\")}\n","\n","for t in trained:\n"," base_match = next((b for b in baselines if b[\"model\"] == t[\"model\"]), None)\n"," for task in (\"task_1\", \"task_2\", \"task_3\", \"overall\"):\n"," score = t[\"after_means\"].get(task, 0.0)\n"," delta = \"\"\n"," if base_match:\n"," delta = round(score - base_match[\"means\"].get(task, 0.0), 4)\n"," table_rows.append({\n"," \"kind\": \"trained\",\n"," \"run_tag\": t[\"tag\"],\n"," \"model\": t[\"model\"],\n"," \"task\": task,\n"," \"score\": round(score, 4),\n"," \"delta_vs_baseline\": delta,\n"," })\n","\n","if table_rows:\n"," csv_path = OUT_DIR / \"comparison_table.csv\"\n"," with open(csv_path, \"w\", newline=\"\") as f:\n"," w = csv.DictWriter(f, fieldnames=list(table_rows[0].keys()))\n"," w.writeheader()\n"," w.writerows(table_rows)\n"," print(f\"Wrote {csv_path}\")\n"," print(f\"\\n{'kind':<10} {'run_tag':<22} {'task':<10} {'score':>8} {'delta':>8}\")\n"," for r in table_rows:\n"," print(f\"{r['kind']:<10} {r['run_tag']:<22} {r['task']:<10} {r['score']:>8} {str(r['delta_vs_baseline']):>8}\")\n","else:\n"," print(\"Nothing to tabulate yet.\")"]}],"metadata": {"kernelspec": {"display_name": "Python 3","language": "python","name": "python3"},"language_info": {"name": "python","version": "3.11"}},"nbformat": 4,"nbformat_minor": 5}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370{"cells": [{"cell_type": "markdown","id": "8a4a82ed","metadata": {},"source": ["# CounterFeint - Compare runs\n","\n","Aggregates baseline + post-training results into a single set of plots + tables for the README and slide deck.\n","\n","## What it expects to find\n","\n","| Path | Source |\n","|---|---|\n","| `baseline_outputs/<model_tag>/baseline_results.json` | `baseline_eval.ipynb` |\n","| `outputs/<run_tag>/eval_summary.json` | `official_hf_training.ipynb` |\n","| `outputs/<run_tag>/log_history.json` | `official_hf_training.ipynb` |\n","| `outputs/<run_tag>/training_config.json` | `official_hf_training.ipynb` |\n","\n","You can run multiple training jobs back-to-back with different `RUN_TAG` values (e.g. `qwen3-0.6b-r16`, `qwen3-0.6b-r32`, `qwen2.5-1.5b-r16`) and this notebook will pull them all into one comparison.\n","\n","## Outputs\n","\n","- `comparison_outputs/before_after_grader.png` - bar chart of mean grader_score per task, baseline vs each trained run\n","- `comparison_outputs/training_curves.png` - reward + loss curves overlaid for all runs\n","- `comparison_outputs/comparison_table.csv` - one row per (run, task) for the README\n","\n","These are the figures you drop into your README and slide deck."]},{"cell_type": "code","execution_count": null,"id": "6fceaaef","metadata": {},"outputs": [],"source": ["import json\n","from pathlib import Path\n","from typing import Any, Dict, List\n","\n","import matplotlib.pyplot as plt\n","import numpy as np\n","\n","REPO_ROOT = next(\n"," (p for p in [Path.cwd(), *Path.cwd().parents] if (p / \"counterfeint\" / \"server\").exists()),\n"," Path.cwd(),\n",")\n","print(f\"REPO_ROOT = {REPO_ROOT}\")\n","\n","BASELINE_DIR = REPO_ROOT / \"baseline_outputs\"\n","TRAINED_DIR = REPO_ROOT / \"outputs\"\n","OUT_DIR = REPO_ROOT / \"comparison_outputs\"\n","OUT_DIR.mkdir(parents=True, exist_ok=True)\n","\n","print(f\"baseline_dir = {BASELINE_DIR} (exists={BASELINE_DIR.exists()})\")\n","print(f\"trained_dir = {TRAINED_DIR} (exists={TRAINED_DIR.exists()})\")"]},{"cell_type": "code","execution_count": null,"id": "2e02d660","metadata": {},"outputs": [],"source": ["def _episode_score(r: Dict[str, Any]) -> float:\n"," return float(r.get(\"grader_score\") or 0.0)\n","\n","\n","def per_task_means(rows: List[Dict[str, Any]]) -> Dict[str, float]:\n"," by_task: Dict[str, List[float]] = {}\n"," for r in rows:\n"," by_task.setdefault(r[\"task_id\"], []).append(_episode_score(r))\n"," out = {t: (sum(v) / len(v) if v else 0.0) for t, v in by_task.items()}\n"," if rows:\n"," out[\"overall\"] = sum(_episode_score(r) for r in rows) / len(rows)\n"," else:\n"," out[\"overall\"] = 0.0\n"," return out\n","\n","\n","def collect_baselines(baseline_dir: Path) -> List[Dict[str, Any]]:\n"," out = []\n"," if not baseline_dir.exists():\n"," return out\n"," for sub in sorted(p for p in baseline_dir.iterdir() if p.is_dir()):\n"," f = sub / \"baseline_results.json\"\n"," if not f.exists():\n"," continue\n"," data = json.loads(f.read_text())\n"," rows = data.get(\"rows\", [])\n"," out.append({\n"," \"kind\": \"baseline\",\n"," \"tag\": data.get(\"model_tag\", sub.name),\n"," \"model\": data.get(\"model_repo\", \"?\"),\n"," \"means\": per_task_means(rows),\n"," \"rows\": rows,\n"," })\n"," return out\n","\n","\n","def collect_trained(trained_dir: Path) -> List[Dict[str, Any]]:\n"," out = []\n"," if not trained_dir.exists():\n"," return out\n"," for sub in sorted(p for p in trained_dir.iterdir() if p.is_dir()):\n"," f = sub / \"eval_summary.json\"\n"," if not f.exists():\n"," continue\n"," data = json.loads(f.read_text())\n"," # eval_summary.json from official_hf_training.ipynb has shape:\n"," # { \"summary\": {...}, \"before\": [episode_dict, ...], \"after\": [...] }\n"," before_rows = data.get(\"before\") or []\n"," after_rows = data.get(\"after\") or []\n"," # base_model lives in training_config.json next to it.\n"," base_model = \"?\"\n"," cfg_path = sub / \"training_config.json\"\n"," if cfg_path.exists():\n"," try:\n"," cfg = json.loads(cfg_path.read_text())\n"," base_model = cfg.get(\"base_model\") or cfg.get(\"BASE_MODEL\", \"?\")\n"," except Exception:\n"," pass\n"," log_json = sub / \"log_history.json\"\n"," out.append({\n"," \"kind\": \"trained\",\n"," \"tag\": sub.name,\n"," \"model\": base_model,\n"," \"before_means\": per_task_means(before_rows),\n"," \"after_means\": per_task_means(after_rows),\n"," \"before_rows\": before_rows,\n"," \"after_rows\": after_rows,\n"," \"log_history_json\": str(log_json) if log_json.exists() else None,\n"," })\n"," return out\n","\n","\n","baselines = collect_baselines(BASELINE_DIR)\n","trained = collect_trained(TRAINED_DIR)\n","print(f\"Found {len(baselines)} baseline run(s) and {len(trained)} trained run(s).\")\n","for b in baselines:\n"," print(f\" baseline: {b['tag']:<20} -> overall={b['means']['overall']:.3f}\")\n","for t in trained:\n"," print(\n"," f\" trained : {t['tag']:<20} -> \"\n"," f\"before={t['before_means']['overall']:.3f} \"\n"," f\"after={t['after_means']['overall']:.3f} \"\n"," f\"delta={(t['after_means']['overall']-t['before_means']['overall']):+.3f}\"\n"," )"]},{"cell_type": "markdown","id": "32acc51e","metadata": {},"source": ["## Section 2 - Per-task mean grader_score (baseline vs trained)\n","\n","The headline plot for the README. Bars are mean grader_score per task; one group per run."]},{"cell_type": "code","execution_count": null,"id": "3684dcc4","metadata": {},"outputs": [],"source": ["labels = []\n","overall = []\n","t1, t2, t3 = [], [], []\n","colors = []\n","\n","for b in baselines:\n"," labels.append(f\"base:{b['tag']}\")\n"," overall.append(b[\"means\"][\"overall\"])\n"," t1.append(b[\"means\"].get(\"task_1\", 0.0))\n"," t2.append(b[\"means\"].get(\"task_2\", 0.0))\n"," t3.append(b[\"means\"].get(\"task_3\", 0.0))\n"," colors.append(\"#888888\")\n","\n","for t in trained:\n"," labels.append(f\"trained:{t['tag']}\")\n"," overall.append(t[\"after_means\"][\"overall\"])\n"," t1.append(t[\"after_means\"].get(\"task_1\", 0.0))\n"," t2.append(t[\"after_means\"].get(\"task_2\", 0.0))\n"," t3.append(t[\"after_means\"].get(\"task_3\", 0.0))\n"," colors.append(\"#4C72B0\")\n","\n","if labels:\n"," width = 0.20\n"," x = np.arange(len(labels))\n"," fig, ax = plt.subplots(figsize=(max(8, 0.9 * len(labels) + 4), 5.5))\n"," ax.bar(x - 1.5 * width, t1, width, label=\"task_1\", color=\"#4C72B0\")\n"," ax.bar(x - 0.5 * width, t2, width, label=\"task_2\", color=\"#55A868\")\n"," ax.bar(x + 0.5 * width, t3, width, label=\"task_3\", color=\"#C44E52\")\n"," ax.bar(x + 1.5 * width, overall, width, label=\"overall\", color=\"#8172B2\")\n"," ax.set_xticks(x)\n"," ax.set_xticklabels(labels, rotation=20, ha=\"right\")\n"," ax.set_ylabel(\"Mean grader_score\")\n"," ax.set_title(\"Per-task grader_score: baselines vs trained\")\n"," ax.set_ylim(0, 1.0)\n"," ax.axhline(0.45, ls=\"--\", color=\"gray\", lw=1, label=\"trainable bar (0.45)\")\n"," ax.axhline(0.80, ls=\"--\", color=\"green\", lw=1, label=\"strong bar (0.80)\")\n"," ax.legend(ncol=3, fontsize=9, loc=\"upper right\")\n"," ax.grid(axis=\"y\", alpha=0.3)\n"," fig.tight_layout()\n"," out_path = OUT_DIR / \"before_after_grader.png\"\n"," fig.savefig(out_path, dpi=140, bbox_inches=\"tight\")\n"," plt.show()\n"," print(f\"Wrote {out_path}\")\n","else:\n"," print(\"No runs found. Run baseline_eval.ipynb and/or official_hf_training.ipynb first.\")"]},{"cell_type": "markdown","id": "691907a5","metadata": {},"source": ["## Section 3 - Training curves overlaid\n","\n","Reads `log_history.json` from each trained run and overlays reward, loss, and KL curves."]},{"cell_type": "code","execution_count": null,"id": "01df2e8a","metadata": {},"outputs": [],"source": ["def load_log_history(path: str):\n"," raw = json.loads(Path(path).read_text())\n"," rows = []\n"," for entry in raw:\n"," step = entry.get(\"step\")\n"," if step is None:\n"," continue\n"," rows.append({\n"," \"step\": int(step),\n"," \"loss\": entry.get(\"loss\"),\n"," \"reward\": entry.get(\"reward\"),\n"," \"kl\": entry.get(\"kl\"),\n"," })\n"," return rows\n","\n","\n","curves = []\n","for t in trained:\n"," if not t[\"log_history_json\"]:\n"," continue\n"," try:\n"," rows = load_log_history(t[\"log_history_json\"])\n"," except Exception as exc:\n"," print(f\" [skip] {t['tag']}: cannot read log_history.json ({exc})\")\n"," continue\n"," if not rows:\n"," continue\n"," curves.append({\"tag\": t[\"tag\"], \"rows\": rows})\n","\n","if not curves:\n"," print(\"No log_history.json files found yet. Run official_hf_training.ipynb first.\")\n","else:\n"," fig, axes = plt.subplots(1, 3, figsize=(16, 5))\n"," for c in curves:\n"," steps = [r[\"step\"] for r in c[\"rows\"]]\n"," losses = [r[\"loss\"] for r in c[\"rows\"]]\n"," rewards = [r[\"reward\"] for r in c[\"rows\"]]\n"," kls = [r[\"kl\"] for r in c[\"rows\"]]\n"," s_l = [s for s, v in zip(steps, losses) if v is not None]\n"," v_l = [v for v in losses if v is not None]\n"," s_r = [s for s, v in zip(steps, rewards) if v is not None]\n"," v_r = [v for v in rewards if v is not None]\n"," s_k = [s for s, v in zip(steps, kls) if v is not None]\n"," v_k = [v for v in kls if v is not None]\n"," if v_l: axes[0].plot(s_l, v_l, label=c[\"tag\"], lw=1.5)\n"," if v_r: axes[1].plot(s_r, v_r, label=c[\"tag\"], lw=1.5)\n"," if v_k: axes[2].plot(s_k, v_k, label=c[\"tag\"], lw=1.5)\n"," axes[0].set_title(\"GRPO loss\"); axes[0].set_xlabel(\"step\"); axes[0].set_ylabel(\"loss\")\n"," axes[1].set_title(\"GRPO mean reward\"); axes[1].set_xlabel(\"step\"); axes[1].set_ylabel(\"reward\")\n"," axes[2].set_title(\"GRPO KL divergence\"); axes[2].set_xlabel(\"step\"); axes[2].set_ylabel(\"kl\")\n"," for ax in axes:\n"," ax.grid(alpha=0.3)\n"," ax.legend(fontsize=9)\n"," fig.tight_layout()\n"," out_path = OUT_DIR / \"training_curves.png\"\n"," fig.savefig(out_path, dpi=140, bbox_inches=\"tight\")\n"," plt.show()\n"," print(f\"Wrote {out_path}\")"]},{"cell_type": "markdown","id": "c1b209db","metadata": {},"source": ["## Section 4 - CSV table for the README"]},{"cell_type": "code","execution_count": null,"id": "01bc436c","metadata": {},"outputs": [],"source": ["import csv\n","\n","table_rows = []\n","for b in baselines:\n"," for task in (\"task_1\", \"task_2\", \"task_3\", \"overall\"):\n"," table_rows.append({\n"," \"kind\": \"baseline\",\n"," \"run_tag\": b[\"tag\"],\n"," \"model\": b[\"model\"],\n"," \"task\": task,\n"," \"score\": round(b[\"means\"].get(task, 0.0), 4),\n"," \"delta_vs_baseline\": \"\",\n"," })\n","\n","baseline_lookup = {(b[\"tag\"], task): b[\"means\"].get(task, 0.0) for b in baselines for task in (\"task_1\", \"task_2\", \"task_3\", \"overall\")}\n","\n","for t in trained:\n"," base_match = next((b for b in baselines if b[\"model\"] == t[\"model\"]), None)\n"," for task in (\"task_1\", \"task_2\", \"task_3\", \"overall\"):\n"," score = t[\"after_means\"].get(task, 0.0)\n"," delta = \"\"\n"," if base_match:\n"," delta = round(score - base_match[\"means\"].get(task, 0.0), 4)\n"," table_rows.append({\n"," \"kind\": \"trained\",\n"," \"run_tag\": t[\"tag\"],\n"," \"model\": t[\"model\"],\n"," \"task\": task,\n"," \"score\": round(score, 4),\n"," \"delta_vs_baseline\": delta,\n"," })\n","\n","if table_rows:\n"," csv_path = OUT_DIR / \"comparison_table.csv\"\n"," with open(csv_path, \"w\", newline=\"\") as f:\n"," w = csv.DictWriter(f, fieldnames=list(table_rows[0].keys()))\n"," w.writeheader()\n"," w.writerows(table_rows)\n"," print(f\"Wrote {csv_path}\")\n"," print(f\"\\n{'kind':<10} {'run_tag':<22} {'task':<10} {'score':>8} {'delta':>8}\")\n"," for r in table_rows:\n"," print(f\"{r['kind']:<10} {r['run_tag']:<22} {r['task']:<10} {r['score']:>8} {str(r['delta_vs_baseline']):>8}\")\n","else:\n"," print(\"Nothing to tabulate yet.\")"]}],"metadata": {"kernelspec": {"display_name": "Python 3","language": "python","name": "python3"},"language_info": {"name": "python","version": "3.11"}},"nbformat": 4,"nbformat_minor": 5}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950{"cells": [{"cell_type": "markdown","id": "433733d5","metadata": {},"source": ["# CounterFeint - Official HuggingFace GRPO Training\n","\n","GRPO fine-tuning of a small Qwen3 model as the **Investigator** in the CounterFeint multi-agent fraud-detection environment.\n","\n","## What this notebook does\n","\n","1. Loads `Qwen/Qwen3-0.6B` (smallest Qwen3) in 4-bit + LoRA on a T4 GPU\n","2. Collects multi-agent rollouts in-process (no HTTP server, no Ollama):\n"," - **Fraudster**: `ReactiveFraudster` (scripted, deterministic)\n"," - **Investigator**: our trainable `HFInvestigator` wrapping Qwen3-0.6B\n"," - **Auditor**: `HeuristicAuditor` (scripted, rule-based)\n","3. Trains the Investigator with TRL's `GRPOTrainer` using a verifiable proxy reward\n","4. Evaluates before/after on held-out seeds\n","5. Pushes the LoRA adapter to the Hugging Face Hub\n","\n","## Why this design\n","\n","- **Scripted Fraudster** (no LLM opponent for first training proof) keeps rollouts cheap and deterministic. Following the recommendation in `COUNTERFEINT_REVIEW.md` - `LLM_FRAUDSTER_RATIO = 0.0` for the first run.\n","- **In-process env** (`RefereeEnvironment`) skips the websocket/uvicorn server. Same env code as the production HTTP path; just no transport.\n","- **Two-phase pipeline** (collect rollouts -> GRPO on dataset) is more sample-efficient than online `rollout_func` for our 20-step episodes.\n","\n","## Run modes\n","\n","| MODE | episodes | epochs | est. time on T4 |\n","|-------|----------|--------|-----------------|\n","| `smoke` | 6 (2 seeds x 3 tasks) | 1 | ~5 min (just verify pipeline) |\n","| `demo` | 30 (10 seeds x 3 tasks) | 1 | ~30 min |\n","| `full` | 100 | 2 | ~2-3 hours |\n","\n","Set `MODE` in the config cell below."]},{"cell_type": "markdown","id": "bc290fdb","metadata": {},"source": ["## Section 1 - Setup and Install\n","\n","Installs CounterFeint (editable) plus the training dependencies (`trl`, `peft`, `bitsandbytes`, `accelerate`, `datasets`, `matplotlib`, `nest_asyncio`).\n","\n","If you're on **Colab** the first cell does a fresh clone + install. On **HuggingFace Spaces** with a notebook environment the same command works because the repo is already in the workspace.\n","\n","After install, restart the runtime if Colab asks - then re-run from Section 2."]},{"cell_type": "code","execution_count": null,"id": "14579f7c","metadata": {},"outputs": [],"source": ["import os\n","import sys\n","import subprocess\n","from pathlib import Path\n","\n","IN_COLAB = \"google.colab\" in sys.modules\n","print(f\"In Colab: {IN_COLAB}\")\n","\n","# Locate the CounterFeint repo root. On Colab we clone it; otherwise we\n","# expect the notebook to be opened from inside the existing repo.\n","if IN_COLAB:\n"," repo_dir = Path(\"/content/OpenEnv-Hackathon\")\n"," if not repo_dir.exists():\n"," # Replace this URL with your fork/clone if you've pushed somewhere else.\n"," subprocess.run(\n"," [\"git\", \"clone\", \"https://github.com/Abhijithreddydasari/OpenEnv-Hackathon.git\", str(repo_dir)],\n"," check=True,\n"," )\n"," REPO_ROOT = repo_dir\n","else:\n"," here = Path.cwd().resolve()\n"," REPO_ROOT = next(\n"," (p for p in [here, *here.parents] if (p / \"counterfeint\" / \"server\").exists()),\n"," here,\n"," )\n","\n","print(f\"REPO_ROOT = {REPO_ROOT}\")\n","os.chdir(REPO_ROOT)\n","if str(REPO_ROOT) not in sys.path:\n"," sys.path.insert(0, str(REPO_ROOT))"]},{"cell_type": "code","execution_count": null,"id": "0492ef99","metadata": {},"outputs": [],"source": ["os.chdir(\"/home/user/app/counterfeint\")\n","def pip_install(args):\n"," subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", *args], check=True)\n","\n","print(\"Installing CounterFeint (editable) ...\")\n","pip_install([\"-e\", \".\"])\n","\n","print(\"Installing training dependencies ...\")\n","pip_install([\"-r\", \"counterfeint/requirements-train.txt\"])\n","\n","print(\"Done. If Colab asks you to restart the runtime, restart it then resume from Section 2.\")"]},{"cell_type": "code","execution_count": null,"id": "f67bec69","metadata": {},"outputs": [],"source": ["try:\n"," from huggingface_hub import notebook_login\n"," notebook_login()\n","except Exception as exc:\n"," print(f\"[hf-login] skipped: {exc}\")\n"," print(\"You can also export HF_TOKEN as an env var before launching the notebook.\")"]},{"cell_type": "code","execution_count": null,"id": "7ac3d20b","metadata": {},"outputs": [],"source": ["import torch\n","import nest_asyncio\n","\n","nest_asyncio.apply()\n","\n","print(f\"PyTorch version: {torch.__version__}\")\n","print(f\"CUDA available: {torch.cuda.is_available()}\")\n","if torch.cuda.is_available():\n"," print(f\"GPU: {torch.cuda.get_device_name(0)}\")\n"," print(f\"VRAM: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB\")\n","else:\n"," print(\"WARNING: no GPU detected. GRPO will be extremely slow on CPU.\")"]},{"cell_type": "markdown","id": "7a8bfb32","metadata": {},"source": ["## Section 2 - Configuration\n","\n","All knobs in one place. Default is `MODE = \"proper\"` for a real training run. Use `MODE = \"smoke\"` first if you want to verify the pipeline cheaply.\n","\n","| MODE | episodes | epochs | est. T4 wall-time | use case |\n","|--------|----------|--------|-------------------|----------|\n","| smoke | 6 | 1 | ~5 min | pipeline check, no real learning |\n","| demo | 30 | 1 | ~30-45 min | first weak signal, plot sanity |\n","| proper | 60 | 2 | ~2-3 hrs | first real grader_score lift |\n","| full | 60 | 3 | ~6-8 hrs | aim for the 0.8+ ceiling |\n","\n","You can also override from the shell: `COUNTERFEINT_MODE=demo` then run the cell.\n","\n","**Baseline reference** (untrained Qwen2.5-1.5B against scripted Fraudster, from the latest `replay_*.md` logs):\n","\n","| Task | grader_score |\n","|--------|--------------|\n","| task_1 | ~0.84-0.85 |\n","| task_2 | ~0.64 |\n","| task_3 | ~0.32 (link_accounts is the weak spot) |\n","\n","GRPO's job: lift task_3 toward 0.55+ and hold task_1/2 above 0.8."]},{"cell_type": "code","execution_count": null,"id": "01c46d84","metadata": {},"outputs": [],"source": ["import json\n","import os\n","from typing import Dict, List\n","\n","# On HF Spaces, ensure CWD is the counterfeint package root so\n","# relative output paths like 'outputs/' land inside the repo tree.\n","for _candidate in ['/data/counterfeint', '/home/user/app/counterfeint']:\n"," if os.path.isdir(_candidate):\n"," os.chdir(_candidate)\n"," break\n","print(f'Working directory: {os.getcwd()}')\n","\n","# Pick MODE here. With a 12-hr budget on a T4 ($0.60/hr -> ~$7), one\n","# \"proper\" run is the right default. \"smoke\" is for verifying the\n","# pipeline in 5 min before committing to the real run.\n","MODE = os.environ.get(\"COUNTERFEINT_MODE\", \"proper\")\n","\n","BASE_MODEL = \"Qwen/Qwen3.5-0.8B\"\n","TRAINED_TAG = \"counterfeint-investigator-qwen35-08b-grpo\"\n","\n","# Hub repo where the LoRA adapter will be pushed at the end. Replace\n","# `<your-username>` with your HF username before running with push_to_hub=True.\n","HUB_REPO_ID = f\"<your-username>/{TRAINED_TAG}\"\n","\n","OUTPUT_DIR = Path(\"outputs\") / TRAINED_TAG\n","OUTPUT_DIR.mkdir(parents=True, exist_ok=True)\n","\n","# ---- Episode / dataset knobs ----------------------------------------\n","TASKS = [\"task_1\", \"task_2\", \"task_3\"]\n","\n","# Each MODE picks: seeds-per-task, training epochs, eval seed count.\n","MODE_PRESETS = {\n"," \"smoke\": {\"seeds\": [11, 13], \"epochs\": 1, \"eval_seeds\": [101]},\n"," \"demo\": {\"seeds\": list(range(11, 21)), \"epochs\": 1, \"eval_seeds\": [101, 103, 107]},\n"," \"proper\": {\"seeds\": list(range(11, 21)) * 2,\n"," \"epochs\": 2, \"eval_seeds\": [101, 103, 107, 109, 113]},\n"," \"full\": {\"seeds\": list(range(11, 31)),\n"," \"epochs\": 3, \"eval_seeds\": [101, 103, 107, 109, 113]},\n","}\n","preset = MODE_PRESETS[MODE]\n","train_seeds = preset[\"seeds\"]\n","EVAL_SEEDS = preset[\"eval_seeds\"]\n","\n","TRAIN_SEEDS_BY_TASK: Dict[str, List[int]] = {t: list(train_seeds) for t in TASKS}\n","EVAL_SEEDS_BY_TASK: Dict[str, List[int]] = {t: list(EVAL_SEEDS) for t in TASKS}\n","\n","# ---- LoRA / model knobs ---------------------------------------------\n","LOAD_IN_4BIT = True\n","MAX_NEW_TOKENS = 128 # actions are tiny JSON; 128 is plenty\n","TEMPERATURE = 0.3 # low temperature => low fallback rate\n","\n","# r=16 gives 4x the capacity vs r=8 at <1% extra params on a 0.6B base;\n","# task_3 (link_accounts) needs the extra plasticity.\n","LORA_R = 16\n","LORA_ALPHA = 32\n","LORA_DROPOUT = 0.05\n","LORA_TARGETS = [\"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\"]\n","\n","# ---- GRPO knobs ------------------------------------------------------\n","LEARNING_RATE = 2e-5\n","NUM_GENERATIONS = 4 # group size for GRPO\n","KL_BETA = 0.01\n","PER_DEVICE_BATCH = 2\n","GRAD_ACCUM = 8\n","MAX_COMPLETION_LEN = 256\n","MAX_PROMPT_LEN = 1024\n","NUM_EPOCHS = preset[\"epochs\"]\n","SAVE_STEPS = 50\n","LOG_STEPS = 1\n","SEED = 7\n","\n","# Skip the BEFORE eval (saves ~5-10 min by not reloading the base model\n","# a second time). Flip to True only on your first run, or when you change\n","# the base model.\n","RUN_BEFORE_EVAL = True\n","\n","PUSH_TO_HUB = False # flip to True after setting HUB_REPO_ID\n","\n","config_summary = {\n"," \"mode\": MODE,\n"," \"base_model\": BASE_MODEL,\n"," \"n_episodes\": len(TASKS) * len(train_seeds),\n"," \"n_eval_episodes\": len(TASKS) * len(EVAL_SEEDS),\n"," \"epochs\": NUM_EPOCHS,\n"," \"lora\": {\"r\": LORA_R, \"alpha\": LORA_ALPHA, \"targets\": LORA_TARGETS},\n"," \"grpo\": {\n"," \"lr\": LEARNING_RATE, \"num_generations\": NUM_GENERATIONS,\n"," \"kl_beta\": KL_BETA, \"max_completion_len\": MAX_COMPLETION_LEN,\n"," },\n"," \"output_dir\": str(OUTPUT_DIR),\n"," \"push_to_hub\": PUSH_TO_HUB,\n"," \"run_before_eval\": RUN_BEFORE_EVAL,\n","}\n","print(json.dumps(config_summary, indent=2))"]},{"cell_type": "markdown","id": "03d80250","metadata": {},"source": ["## Section 3 - Load Qwen3-0.6B + LoRA\n","\n","We load the model in 4-bit (NF4) to fit on a T4 with room for activations and the LoRA optimizer state, then attach a small LoRA on the attention projections only.\n","\n","`HFInvestigator` wraps the base model + tokenizer with the same prompt-builder, JSON parser, and scripted-fallback wiring that the production HTTP investigator uses, so the trained policy ports cleanly.\n","\n","`enable_thinking=False` tells Qwen3's chat template to skip its chain-of-thought wrapper - we want the model to output the JSON action directly."]},{"cell_type": "code","execution_count": null,"id": "35451786","metadata": {},"outputs": [],"source": ["from counterfeint.agents import HFInvestigator\n","\n","print(f\"Loading {BASE_MODEL} (load_in_4bit={LOAD_IN_4BIT}) ...\")\n","hf_investigator = HFInvestigator.from_pretrained(\n"," BASE_MODEL,\n"," load_in_4bit=LOAD_IN_4BIT,\n"," max_new_tokens=MAX_NEW_TOKENS,\n"," temperature=TEMPERATURE,\n"," do_sample=True,\n"," enable_thinking=False,\n",")\n","print(\"Loaded.\")"]},{"cell_type": "code","execution_count": null,"id": "2d54dd78","metadata": {},"outputs": [],"source": ["from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training\n","\n","if LOAD_IN_4BIT:\n"," hf_investigator.model = prepare_model_for_kbit_training(hf_investigator.model)\n","\n","lora_cfg = LoraConfig(\n"," r=LORA_R,\n"," lora_alpha=LORA_ALPHA,\n"," lora_dropout=LORA_DROPOUT,\n"," target_modules=LORA_TARGETS,\n"," bias=\"none\",\n"," task_type=\"CAUSAL_LM\",\n",")\n","hf_investigator.model = get_peft_model(hf_investigator.model, lora_cfg)\n","hf_investigator.model.print_trainable_parameters()"]},{"cell_type": "code","execution_count": null,"id": "ad0f5b1e","metadata": {},"outputs": [],"source": ["probe_msgs = [\n"," {\"role\": \"system\", \"content\": \"You output one line of valid JSON only.\"},\n"," {\"role\": \"user\", \"content\": \"Reply with {\\\"ok\\\": true}\"},\n","]\n","probe_text = hf_investigator._call_chat(probe_msgs)\n","print(f\"Smoke-test completion (first 200 chars):\\n{probe_text[:200]!r}\")"]},{"cell_type": "markdown","id": "3b58950d","metadata": {},"source": ["## Section 4 - Collect rollouts\n","\n","Run multi-agent episodes in-process (`RefereeEnvironment` directly) with the trainable Investigator + scripted Fraudster + heuristic Auditor. We record every Investigator `act()` call as a `(prompt, completion, reward)` row.\n","\n","**Reward shaping** (in `records_to_samples`): the episode-level Investigator reward is split across turns 80/20 between verdict-class and investigate-class actions. This gives stronger gradient on the actions that actually move the grader.\n","\n","The smoke run with 6 episodes typically takes ~3-5 min on a T4."]},{"cell_type": "code","execution_count": null,"id": "442c8c21","metadata": {},"outputs": [],"source": ["import time\n","from counterfeint.training import (\n"," collect_dataset_in_process,\n"," samples_to_hf_dataset,\n",")\n","from counterfeint.scripted import HeuristicAuditor, ReactiveFraudster\n","\n","t0 = time.perf_counter()\n","samples = collect_dataset_in_process(\n"," hf_investigator=hf_investigator,\n"," seeds_by_task=TRAIN_SEEDS_BY_TASK,\n"," fraudster_factory=lambda: ReactiveFraudster(seed=42),\n"," auditor_factory=lambda: HeuristicAuditor(),\n"," max_steps=80,\n"," show_trace=False,\n",")\n","elapsed = time.perf_counter() - t0\n","print(f\"\\nCollected {len(samples)} training rows in {elapsed:.1f}s \"\n"," f\"({elapsed / max(1, len(samples)):.2f}s/row).\")\n","print(f\"Investigator fallback: {hf_investigator.fallback_count}/{hf_investigator.call_count}\")"]},{"cell_type": "code","execution_count": null,"id": "4cde9e16","metadata": {},"outputs": [],"source": ["if not samples:\n"," raise RuntimeError(\n"," \"No usable Investigator turns were collected. Every step must have \"\n"," \"fallen back to the scripted policy. Check fallback_count above and \"\n"," \"the smoke-test completion in Section 3.\"\n"," )\n","\n","import statistics\n","\n","rewards = [s.reward for s in samples]\n","grader_scores = sorted({(s.task_id, s.seed, s.terminal_grader_score) for s in samples})\n","class_counts = {\"verdict\": 0, \"investigate\": 0}\n","for s in samples:\n"," class_counts[s.metadata.get(\"action_class\", \"investigate\")] += 1\n","\n","print(f\"Rows: {len(samples)}\")\n","print(f\"Reward mean: {statistics.mean(rewards):+.4f}\")\n","print(f\"Reward stdev: {statistics.pstdev(rewards):+.4f}\")\n","print(f\"Reward min/max: {min(rewards):+.4f} / {max(rewards):+.4f}\")\n","print(f\"Action classes: {class_counts}\")\n","print(f\"\\nPer-episode grader_score:\")\n","for task_id, seed, gs in grader_scores:\n"," print(f\" {task_id} seed={seed:>3}: {gs:+.4f}\")"]},{"cell_type": "code","execution_count": null,"id": "1978e460","metadata": {},"outputs": [],"source": ["# Drop any rows where the recorded completion was empty / not-JSON. The\n","# proxy reward already penalizes invalid JSON, but training on a dataset\n","# of mostly-broken completions wastes batches; the model learns more from\n","# good examples. We keep at most 90% of original rows.\n","def _looks_like_json(completion):\n"," if not completion:\n"," return False\n"," stripped = completion.strip()\n"," return stripped.startswith(\"{\") and \"action_type\" in stripped\n","\n","clean_samples = [s for s in samples if _looks_like_json(s.completion)]\n","dropped = len(samples) - len(clean_samples)\n","if dropped:\n"," print(f\"Filtered out {dropped}/{len(samples)} rows with invalid completions.\")\n","samples = clean_samples or samples # fall back if filter would empty everything\n","\n","from counterfeint.agents.prompts import INVESTIGATOR_SYSTEM_PROMPT\n","train_dataset = samples_to_hf_dataset(samples, system_prompt=INVESTIGATOR_SYSTEM_PROMPT)\n","print(train_dataset)\n","print(\"\\nFirst row preview:\")\n","preview = train_dataset[0]\n","print(f\" prompt (first 300 chars): {preview['prompt'][:300]!r}\")\n","print(f\" completion (first 200 chars): {preview['completion'][:200]!r}\")\n","print(f\" reward : {preview['reward']:+.4f}\")\n","print(f\" task_id / seed : {preview['task_id']} / {preview['seed']}\")\n","print(f\" action_class : {preview['metadata'].get('action_class')}\")"]},{"cell_type": "markdown","id": "ec036f17","metadata": {},"source": ["## Section 5 - GRPO Training\n","\n","The `proxy_reward_fn` scores any `(prompt, completion)` pair without touching the env, so it works on TRL's freshly-generated rollouts. It rewards:\n","\n","- **+0.6** for valid `AdReviewAction` JSON (schema validity)\n","- **+0.1** each for `ad_id` / `linked_ad_id` referenced in the prompt (coherence)\n","- **+0.2** for matching the recorded gold action class (verdict / investigate / link)\n","- **up to +0.6** for matching the recorded gold decision, scaled by the episode's `grader_score` quality\n","\n","Range: roughly `[-0.5, +2.0]`.\n","\n","`GRPOTrainer` runs `num_generations=4` rollouts per prompt, scores them with this reward, and updates LoRA via group-relative policy optimization with `KL_BETA=0.01` regularization to the frozen base."]},{"cell_type": "code","execution_count": null,"id": "230d00e4","metadata": {},"outputs": [],"source": ["from counterfeint.training import build_gold_lookup, make_proxy_reward_fn\n","\n","gold_lookup = build_gold_lookup(samples)\n","proxy_reward_fn = make_proxy_reward_fn(gold_lookup=gold_lookup)\n","print(f\"Built gold lookup with {len(gold_lookup)} entries.\")\n","\n","# Quick sanity check: score a known-good completion.\n","sample_prompt = samples[0].prompt\n","sample_completion = samples[0].completion\n","sample_reward = proxy_reward_fn([sample_prompt], [sample_completion])\n","print(f\"Proxy reward on a recorded completion: {sample_reward}\")"]},{"cell_type": "code","execution_count": null,"id": "2b13794d","metadata": {},"outputs": [],"source": ["import inspect\n","from trl import GRPOConfig, GRPOTrainer\n","\n","# Build the config kwargs incrementally so we tolerate older/newer TRL\n","# versions: ``max_prompt_length`` was removed in TRL >=1.0 (the prompt is\n","# now truncated by tokenizer.model_max_length).\n","_grpo_kwargs = dict(\n"," output_dir=str(OUTPUT_DIR / \"trl_checkpoints\"),\n"," learning_rate=LEARNING_RATE,\n"," num_generations=NUM_GENERATIONS,\n"," beta=KL_BETA,\n"," per_device_train_batch_size=PER_DEVICE_BATCH,\n"," gradient_accumulation_steps=GRAD_ACCUM,\n"," max_completion_length=MAX_COMPLETION_LEN,\n"," num_train_epochs=NUM_EPOCHS,\n"," save_steps=SAVE_STEPS,\n"," logging_steps=LOG_STEPS,\n"," gradient_checkpointing=True,\n"," gradient_checkpointing_kwargs={\"use_reentrant\": False},\n"," report_to=\"none\",\n"," seed=SEED,\n"," remove_unused_columns=False,\n",")\n","_grpo_params = set(inspect.signature(GRPOConfig.__init__).parameters)\n","if \"max_prompt_length\" in _grpo_params:\n"," _grpo_kwargs[\"max_prompt_length\"] = MAX_PROMPT_LEN\n","else:\n"," hf_investigator.tokenizer.model_max_length = max(\n"," MAX_PROMPT_LEN + MAX_COMPLETION_LEN,\n"," getattr(hf_investigator.tokenizer, \"model_max_length\", 0) or 0,\n"," )\n","\n","if \"temperature\" in _grpo_params:\n"," _grpo_kwargs[\"temperature\"] = 0.9\n","\n","trl_config = GRPOConfig(**_grpo_kwargs)\n","\n","trainer = GRPOTrainer(\n"," model=hf_investigator.model,\n"," args=trl_config,\n"," train_dataset=train_dataset,\n"," reward_funcs=[proxy_reward_fn],\n"," processing_class=hf_investigator.tokenizer,\n",")\n","if hasattr(trainer, \"generation_config\"):\n"," trainer.generation_config.temperature = 0.9\n"," trainer.generation_config.do_sample = True\n","print(\"GRPOTrainer ready (generation temperature=0.9).\")"]},{"cell_type": "code","execution_count": null,"id": "5a73186c","metadata": {},"outputs": [],"source": ["train_t0 = time.perf_counter()\n","train_result = trainer.train()\n","print(f\"\\nTraining took {(time.perf_counter() - train_t0) / 60:.1f} min.\")\n","print(train_result)"]},{"cell_type": "code","execution_count": null,"id": "903ec104","metadata": {},"outputs": [],"source": ["lora_dir = OUTPUT_DIR / \"lora_adapter\"\n","lora_dir.mkdir(parents=True, exist_ok=True)\n","\n","trainer.save_model(str(lora_dir))\n","hf_investigator.tokenizer.save_pretrained(str(lora_dir))\n","\n","with open(OUTPUT_DIR / \"training_config.json\", \"w\") as f:\n"," json.dump(config_summary, f, indent=2)\n","\n","print(f\"Saved LoRA adapter + tokenizer to: {lora_dir}\")"]},{"cell_type": "markdown","id": "8b537a16","metadata": {},"source": ["## Section 6 - Loss / reward curves\n","\n","The submission requirement asks for \"loss and reward plots from a real run.\" We pull TRL's `log_history` (which contains per-`logging_steps` records of `loss`, `reward`, `kl`, `learning_rate`, ...) and render them with matplotlib."]},{"cell_type": "code","execution_count": null,"id": "93451503","metadata": {},"outputs": [],"source": ["import matplotlib.pyplot as plt\n","\n","log_history = trainer.state.log_history\n","log_path = OUTPUT_DIR / \"log_history.json\"\n","with open(log_path, \"w\") as f:\n"," json.dump(log_history, f, indent=2, default=str)\n","print(f\"Wrote {log_path} ({len(log_history)} entries).\")\n","\n","steps_loss, losses = [], []\n","steps_rew, rewards_log = [], []\n","steps_kl, kls = [], []\n","\n","for entry in log_history:\n"," step = entry.get(\"step\")\n"," if step is None:\n"," continue\n"," if \"loss\" in entry:\n"," steps_loss.append(step); losses.append(entry[\"loss\"])\n"," if \"reward\" in entry:\n"," steps_rew.append(step); rewards_log.append(entry[\"reward\"])\n"," if \"kl\" in entry:\n"," steps_kl.append(step); kls.append(entry[\"kl\"])\n","\n","fig, axes = plt.subplots(1, 3, figsize=(15, 4))\n","\n","axes[0].plot(steps_loss, losses, color=\"tab:red\")\n","axes[0].set_title(\"GRPO loss\")\n","axes[0].set_xlabel(\"step\"); axes[0].set_ylabel(\"loss\")\n","axes[0].grid(True, alpha=0.3)\n","\n","axes[1].plot(steps_rew, rewards_log, color=\"tab:green\")\n","axes[1].set_title(\"Mean reward\")\n","axes[1].set_xlabel(\"step\"); axes[1].set_ylabel(\"reward\")\n","axes[1].grid(True, alpha=0.3)\n","\n","axes[2].plot(steps_kl, kls, color=\"tab:blue\")\n","axes[2].set_title(\"KL divergence\")\n","axes[2].set_xlabel(\"step\"); axes[2].set_ylabel(\"KL\")\n","axes[2].grid(True, alpha=0.3)\n","\n","fig.suptitle(f\"GRPO training - {BASE_MODEL} - mode={MODE}\")\n","fig.tight_layout()\n","\n","plot_path = OUTPUT_DIR / \"training_curves.png\"\n","fig.savefig(plot_path, dpi=120, bbox_inches=\"tight\")\n","plt.show()\n","print(f\"Saved plot to {plot_path}\")"]},{"cell_type": "markdown","id": "09aeb21f","metadata": {},"source": ["## Section 7 - Before/After evaluation\n","\n","Run the **trained** Investigator on held-out seeds and compare the grader_score against:\n","\n","- **Before**: the *base* Qwen3-0.6B without LoRA (i.e. what we started with)\n","\n","We use the in-process driver again (no HTTP server needed). The Fraudster + Auditor are deterministic so the only thing that changes between Before and After is the Investigator's policy."]},{"cell_type": "code","execution_count": null,"id": "432e5f62","metadata": {},"outputs": [],"source": ["from counterfeint.server.referee import RefereeEnvironment\n","\n","\n","def run_eval_episode(investigator, *, task_id: str, seed: int, max_steps: int = 80):\n"," \"\"\"In-process episode runner for evaluation. Returns flat metrics dict.\"\"\"\n"," env = RefereeEnvironment()\n"," env.reset_match(task_id=task_id, seed=seed)\n","\n"," fraudster = ReactiveFraudster(seed=42)\n"," auditor = HeuristicAuditor()\n","\n"," role_handlers = {\n"," \"fraudster_turn\": (fraudster, env.build_fraudster_observation, env.step_as_fraudster),\n"," \"investigator_turn\":(investigator, env.build_investigator_observation, env.step_as_investigator),\n"," \"audit_phase\": (auditor, env.build_auditor_observation, env.step_as_auditor),\n"," }\n","\n"," step_idx = 0\n"," n_verdicts = 0\n"," while env.phase in role_handlers:\n"," current_phase = env.phase\n"," policy, build_obs, step_fn = role_handlers[current_phase]\n"," if current_phase != \"audit_phase\" and step_idx >= max_steps:\n"," break\n"," obs = build_obs().model_dump()\n"," for slot in (\"last_prompt\", \"last_completion\", \"last_error\"):\n"," if hasattr(policy, slot):\n"," setattr(policy, slot, None)\n"," try:\n"," action = policy.act(obs)\n"," except Exception:\n"," break\n"," try:\n"," step_fn(action)\n"," except Exception:\n"," break\n"," if current_phase != \"audit_phase\":\n"," step_idx += 1\n"," if current_phase == \"investigator_turn\" and getattr(action, \"action_type\", None) in (\"verdict\", \"link_accounts\"):\n"," n_verdicts += 1\n","\n"," state = env.state\n"," return {\n"," \"task_id\": task_id,\n"," \"seed\": seed,\n"," \"grader_score\": getattr(state, \"grader_score\", None),\n"," \"end_reason\": getattr(state, \"end_reason\", None),\n"," \"stopped_phase\": env.phase,\n"," \"n_verdicts\": n_verdicts,\n"," \"investigator_fallback\": getattr(investigator, \"fallback_count\", 0),\n"," }\n","\n","\n","def run_eval_suite(investigator, *, label: str, seeds_by_task):\n"," print(f\"\\n=== Evaluating {label} ===\")\n"," results = []\n"," for task_id, seeds in seeds_by_task.items():\n"," for seed in seeds:\n"," fb_before = getattr(investigator, \"fallback_count\", 0)\n"," r = run_eval_episode(investigator, task_id=task_id, seed=seed)\n"," r[\"investigator_fallback_delta\"] = (\n"," getattr(investigator, \"fallback_count\", 0) - fb_before\n"," )\n"," results.append(r)\n"," print(f\" {task_id} seed={seed:>3}: grader={r['grader_score']} \"\n"," f\"verdicts={r['n_verdicts']} fallback+={r['investigator_fallback_delta']}\")\n"," return results"]},{"cell_type": "code","execution_count": null,"id": "0b36c76c","metadata": {},"outputs": [],"source": ["after_results = run_eval_suite(\n"," hf_investigator,\n"," label=\"AFTER (trained Qwen3-0.6B + LoRA)\",\n"," seeds_by_task=EVAL_SEEDS_BY_TASK,\n",")"]},{"cell_type": "code","execution_count": null,"id": "741c6e04","metadata": {},"outputs": [],"source": ["import gc\n","\n","if not RUN_BEFORE_EVAL:\n"," print(\"RUN_BEFORE_EVAL=False - skipping the base-model reload pass.\")\n"," print(\"Using a synthetic BEFORE = 0.0 baseline (or paste numbers from a\")\n"," print(\"previous run into `before_results` below if you have them).\")\n"," before_results = [\n"," {\n"," \"task_id\": r[\"task_id\"], \"seed\": r[\"seed\"], \"grader_score\": 0.0,\n"," \"end_reason\": \"skipped\", \"stopped_phase\": \"skipped\",\n"," \"n_verdicts\": 0, \"investigator_fallback\": 0,\n"," \"investigator_fallback_delta\": 0,\n"," }\n"," for r in after_results\n"," ]\n","else:\n"," del trainer\n"," del hf_investigator\n"," gc.collect()\n"," if torch.cuda.is_available():\n"," torch.cuda.empty_cache()\n"," print(\"Trained model unloaded; reloading the *base* Qwen3-0.6B for the BEFORE eval ...\")\n","\n"," baseline_investigator = HFInvestigator.from_pretrained(\n"," BASE_MODEL,\n"," load_in_4bit=LOAD_IN_4BIT,\n"," max_new_tokens=MAX_NEW_TOKENS,\n"," temperature=TEMPERATURE,\n"," do_sample=True,\n"," enable_thinking=False,\n"," )\n","\n"," before_results = run_eval_suite(\n"," baseline_investigator,\n"," label=\"BEFORE (base Qwen3-0.6B, no LoRA)\",\n"," seeds_by_task=EVAL_SEEDS_BY_TASK,\n"," )"]},{"cell_type": "code","execution_count": null,"id": "9366f804","metadata": {},"outputs": [],"source": ["def _scores(rows):\n"," return [r[\"grader_score\"] or 0.0 for r in rows]\n","\n","before_scores = _scores(before_results)\n","after_scores = _scores(after_results)\n","\n","eval_summary = {\n"," \"n_eval_episodes\": len(before_results),\n"," \"before\": {\n"," \"mean_grader_score\": sum(before_scores) / max(1, len(before_scores)),\n"," \"verdicts_total\": sum(r[\"n_verdicts\"] for r in before_results),\n"," \"fallback_total\": sum(r[\"investigator_fallback_delta\"] for r in before_results),\n"," },\n"," \"after\": {\n"," \"mean_grader_score\": sum(after_scores) / max(1, len(after_scores)),\n"," \"verdicts_total\": sum(r[\"n_verdicts\"] for r in after_results),\n"," \"fallback_total\": sum(r[\"investigator_fallback_delta\"] for r in after_results),\n"," },\n","}\n","eval_summary[\"delta_grader_score\"] = (\n"," eval_summary[\"after\"][\"mean_grader_score\"] - eval_summary[\"before\"][\"mean_grader_score\"]\n",")\n","\n","print(json.dumps(eval_summary, indent=2))\n","\n","with open(OUTPUT_DIR / \"eval_summary.json\", \"w\") as f:\n"," json.dump({\n"," \"summary\": eval_summary,\n"," \"before\": before_results,\n"," \"after\": after_results,\n"," }, f, indent=2)"]},{"cell_type": "code","execution_count": null,"id": "7b53775e","metadata": {},"outputs": [],"source": ["labels = [f\"{r['task_id']}/{r['seed']}\" for r in before_results]\n","x = list(range(len(labels)))\n","width = 0.4\n","\n","fig, ax = plt.subplots(figsize=(max(8, len(labels) * 0.6), 5))\n","ax.bar([xi - width/2 for xi in x], before_scores, width, label=\"Before (base)\", color=\"tab:gray\")\n","ax.bar([xi + width/2 for xi in x], after_scores, width, label=\"After (trained)\", color=\"tab:green\")\n","ax.set_xticks(x)\n","ax.set_xticklabels(labels, rotation=45, ha=\"right\")\n","ax.set_ylabel(\"grader_score\")\n","ax.set_title(f\"Before vs After - {BASE_MODEL} - mode={MODE}\")\n","ax.legend()\n","ax.grid(True, axis=\"y\", alpha=0.3)\n","fig.tight_layout()\n","\n","eval_plot_path = OUTPUT_DIR / \"eval_plot.png\"\n","fig.savefig(eval_plot_path, dpi=120, bbox_inches=\"tight\")\n","plt.show()\n","print(f\"Saved {eval_plot_path}\")"]},{"cell_type": "markdown","id": "e20c9615","metadata": {},"source": ["## Section 8 - Push to Hub (optional)\n","\n","Set `PUSH_TO_HUB = True` in Section 2 and replace `<your-username>` in `HUB_REPO_ID` to push the LoRA adapter + tokenizer + training/eval artefacts to a public HF Hub repo. The README on your CounterFeint env Space can then link to this adapter."]},{"cell_type": "code","execution_count": null,"id": "a8d0f210","metadata": {},"outputs": [],"source": ["if not PUSH_TO_HUB:\n"," print(\"PUSH_TO_HUB=False — skipping. Flip it in Section 2 once you're ready.\")\n","else:\n"," if HUB_REPO_ID.startswith(\"<\"):\n"," raise RuntimeError(\n"," \"Set HUB_REPO_ID in Section 2 to '<your-hf-username>/<repo-name>' \"\n"," \"before pushing.\"\n"," )\n","\n"," from huggingface_hub import HfApi\n","\n"," api = HfApi()\n"," api.create_repo(repo_id=HUB_REPO_ID, private=False, exist_ok=True)\n"," print(f\"Created/found repo {HUB_REPO_ID}\")\n","\n"," api.upload_folder(\n"," repo_id=HUB_REPO_ID,\n"," folder_path=str(OUTPUT_DIR),\n"," commit_message=f\"GRPO {MODE} run on {BASE_MODEL}\",\n"," )\n"," print(f\"Uploaded {OUTPUT_DIR} -> {HUB_REPO_ID}\")"]},{"cell_type": "markdown","id": "d4279d60","metadata": {},"source": ["## Done\n","\n","You should now have, under `OUTPUT_DIR`:\n","\n","- `lora_adapter/` - the trained PEFT adapter (`adapter_config.json` + safetensors) and tokenizer\n","- `training_curves.png` - GRPO loss / reward / KL curves\n","- `eval_plot.png` - before/after grader_score per held-out episode\n","- `eval_summary.json` - mean grader_score before/after, fallback counts\n","- `log_history.json` - raw TRL training log\n","- `training_config.json` - the config that produced this run\n","\n","To run a bigger experiment: change `MODE = \"demo\"` in Section 2, restart the kernel, and re-run all cells. With the $30 HF Spaces budget you have ~20 demo-mode runs to iterate on hyperparameters / model size."]}],"metadata": {"kernelspec": {"display_name": "Python 3","language": "python","name": "python3"},"language_info": {"name": "python","version": "3.11"}},"nbformat": 4,"nbformat_minor": 5}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950{"cells": [{"cell_type": "markdown","id": "433733d5","metadata": {},"source": ["# CounterFeint - Official HuggingFace GRPO Training\n","\n","GRPO fine-tuning of a small Qwen3 model as the **Investigator** in the CounterFeint multi-agent fraud-detection environment.\n","\n","## What this notebook does\n","\n","1. Loads `Qwen/Qwen3-0.6B` (smallest Qwen3) in 4-bit + LoRA on a T4 GPU\n","2. Collects multi-agent rollouts in-process (no HTTP server, no Ollama):\n"," - **Fraudster**: `ReactiveFraudster` (scripted, deterministic)\n"," - **Investigator**: our trainable `HFInvestigator` wrapping Qwen3-0.6B\n"," - **Auditor**: `HeuristicAuditor` (scripted, rule-based)\n","3. Trains the Investigator with TRL's `GRPOTrainer` using a verifiable proxy reward\n","4. Evaluates before/after on held-out seeds\n","5. Pushes the LoRA adapter to the Hugging Face Hub\n","\n","## Why this design\n","\n","- **Scripted Fraudster** (no LLM opponent for first training proof) keeps rollouts cheap and deterministic. Following the recommendation in `COUNTERFEINT_REVIEW.md` - `LLM_FRAUDSTER_RATIO = 0.0` for the first run.\n","- **In-process env** (`RefereeEnvironment`) skips the websocket/uvicorn server. Same env code as the production HTTP path; just no transport.\n","- **Two-phase pipeline** (collect rollouts -> GRPO on dataset) is more sample-efficient than online `rollout_func` for our 20-step episodes.\n","\n","## Run modes\n","\n","| MODE | episodes | epochs | est. time on T4 |\n","|-------|----------|--------|-----------------|\n","| `smoke` | 6 (2 seeds x 3 tasks) | 1 | ~5 min (just verify pipeline) |\n","| `demo` | 30 (10 seeds x 3 tasks) | 1 | ~30 min |\n","| `full` | 100 | 2 | ~2-3 hours |\n","\n","Set `MODE` in the config cell below."]},{"cell_type": "markdown","id": "bc290fdb","metadata": {},"source": ["## Section 1 - Setup and Install\n","\n","Installs CounterFeint (editable) plus the training dependencies (`trl`, `peft`, `bitsandbytes`, `accelerate`, `datasets`, `matplotlib`, `nest_asyncio`).\n","\n","If you're on **Colab** the first cell does a fresh clone + install. On **HuggingFace Spaces** with a notebook environment the same command works because the repo is already in the workspace.\n","\n","After install, restart the runtime if Colab asks - then re-run from Section 2."]},{"cell_type": "code","execution_count": null,"id": "14579f7c","metadata": {},"outputs": [],"source": ["import os\n","import sys\n","import subprocess\n","from pathlib import Path\n","\n","IN_COLAB = \"google.colab\" in sys.modules\n","print(f\"In Colab: {IN_COLAB}\")\n","\n","# Locate the CounterFeint repo root. On Colab we clone it; otherwise we\n","# expect the notebook to be opened from inside the existing repo.\n","if IN_COLAB:\n"," repo_dir = Path(\"/content/OpenEnv-Hackathon\")\n"," if not repo_dir.exists():\n"," # Replace this URL with your fork/clone if you've pushed somewhere else.\n"," subprocess.run(\n"," [\"git\", \"clone\", \"https://github.com/Abhijithreddydasari/OpenEnv-Hackathon.git\", str(repo_dir)],\n"," check=True,\n"," )\n"," REPO_ROOT = repo_dir\n","else:\n"," here = Path.cwd().resolve()\n"," REPO_ROOT = next(\n"," (p for p in [here, *here.parents] if (p / \"counterfeint\" / \"server\").exists()),\n"," here,\n"," )\n","\n","print(f\"REPO_ROOT = {REPO_ROOT}\")\n","os.chdir(REPO_ROOT)\n","if str(REPO_ROOT) not in sys.path:\n"," sys.path.insert(0, str(REPO_ROOT))"]},{"cell_type": "code","execution_count": null,"id": "0492ef99","metadata": {},"outputs": [],"source": ["os.chdir(\"/home/user/app/counterfeint\")\n","def pip_install(args):\n"," subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", *args], check=True)\n","\n","print(\"Installing CounterFeint (editable) ...\")\n","pip_install([\"-e\", \".\"])\n","\n","print(\"Installing training dependencies ...\")\n","pip_install([\"-r\", \"counterfeint/requirements-train.txt\"])\n","\n","print(\"Done. If Colab asks you to restart the runtime, restart it then resume from Section 2.\")"]},{"cell_type": "code","execution_count": null,"id": "f67bec69","metadata": {},"outputs": [],"source": ["try:\n"," from huggingface_hub import notebook_login\n"," notebook_login()\n","except Exception as exc:\n"," print(f\"[hf-login] skipped: {exc}\")\n"," print(\"You can also export HF_TOKEN as an env var before launching the notebook.\")"]},{"cell_type": "code","execution_count": null,"id": "7ac3d20b","metadata": {},"outputs": [],"source": ["import torch\n","import nest_asyncio\n","\n","nest_asyncio.apply()\n","\n","print(f\"PyTorch version: {torch.__version__}\")\n","print(f\"CUDA available: {torch.cuda.is_available()}\")\n","if torch.cuda.is_available():\n"," print(f\"GPU: {torch.cuda.get_device_name(0)}\")\n"," print(f\"VRAM: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB\")\n","else:\n"," print(\"WARNING: no GPU detected. GRPO will be extremely slow on CPU.\")"]},{"cell_type": "markdown","id": "7a8bfb32","metadata": {},"source": ["## Section 2 - Configuration\n","\n","All knobs in one place. Default is `MODE = \"proper\"` for a real training run. Use `MODE = \"smoke\"` first if you want to verify the pipeline cheaply.\n","\n","| MODE | episodes | epochs | est. T4 wall-time | use case |\n","|--------|----------|--------|-------------------|----------|\n","| smoke | 6 | 1 | ~5 min | pipeline check, no real learning |\n","| demo | 30 | 1 | ~30-45 min | first weak signal, plot sanity |\n","| proper | 60 | 2 | ~2-3 hrs | first real grader_score lift |\n","| full | 60 | 3 | ~6-8 hrs | aim for the 0.8+ ceiling |\n","\n","You can also override from the shell: `COUNTERFEINT_MODE=demo` then run the cell.\n","\n","**Baseline reference** (untrained Qwen2.5-1.5B against scripted Fraudster, from the latest `replay_*.md` logs):\n","\n","| Task | grader_score |\n","|--------|--------------|\n","| task_1 | ~0.84-0.85 |\n","| task_2 | ~0.64 |\n","| task_3 | ~0.32 (link_accounts is the weak spot) |\n","\n","GRPO's job: lift task_3 toward 0.55+ and hold task_1/2 above 0.8."]},{"cell_type": "code","execution_count": null,"id": "01c46d84","metadata": {},"outputs": [],"source": ["import json\n","import os\n","from typing import Dict, List\n","\n","# On HF Spaces, ensure CWD is the counterfeint package root so\n","# relative output paths like 'outputs/' land inside the repo tree.\n","for _candidate in ['/data/counterfeint', '/home/user/app/counterfeint']:\n"," if os.path.isdir(_candidate):\n"," os.chdir(_candidate)\n"," break\n","print(f'Working directory: {os.getcwd()}')\n","\n","# Pick MODE here. With a 12-hr budget on a T4 ($0.60/hr -> ~$7), one\n","# \"proper\" run is the right default. \"smoke\" is for verifying the\n","# pipeline in 5 min before committing to the real run.\n","MODE = os.environ.get(\"COUNTERFEINT_MODE\", \"proper\")\n","\n","BASE_MODEL = \"Qwen/Qwen3.5-0.8B\"\n","TRAINED_TAG = \"counterfeint-investigator-qwen35-08b-grpo\"\n","\n","# Hub repo where the LoRA adapter will be pushed at the end. Replace\n","# `<your-username>` with your HF username before running with push_to_hub=True.\n","HUB_REPO_ID = f\"<your-username>/{TRAINED_TAG}\"\n","\n","OUTPUT_DIR = Path(\"outputs\") / TRAINED_TAG\n","OUTPUT_DIR.mkdir(parents=True, exist_ok=True)\n","\n","# ---- Episode / dataset knobs ----------------------------------------\n","TASKS = [\"task_1\", \"task_2\", \"task_3\"]\n","\n","# Each MODE picks: seeds-per-task, training epochs, eval seed count.\n","MODE_PRESETS = {\n"," \"smoke\": {\"seeds\": [11, 13], \"epochs\": 1, \"eval_seeds\": [101]},\n"," \"demo\": {\"seeds\": list(range(11, 21)), \"epochs\": 1, \"eval_seeds\": [101, 103, 107]},\n"," \"proper\": {\"seeds\": list(range(11, 21)) * 2,\n"," \"epochs\": 2, \"eval_seeds\": [101, 103, 107, 109, 113]},\n"," \"full\": {\"seeds\": list(range(11, 31)),\n"," \"epochs\": 3, \"eval_seeds\": [101, 103, 107, 109, 113]},\n","}\n","preset = MODE_PRESETS[MODE]\n","train_seeds = preset[\"seeds\"]\n","EVAL_SEEDS = preset[\"eval_seeds\"]\n","\n","TRAIN_SEEDS_BY_TASK: Dict[str, List[int]] = {t: list(train_seeds) for t in TASKS}\n","EVAL_SEEDS_BY_TASK: Dict[str, List[int]] = {t: list(EVAL_SEEDS) for t in TASKS}\n","\n","# ---- LoRA / model knobs ---------------------------------------------\n","LOAD_IN_4BIT = True\n","MAX_NEW_TOKENS = 128 # actions are tiny JSON; 128 is plenty\n","TEMPERATURE = 0.3 # low temperature => low fallback rate\n","\n","# r=16 gives 4x the capacity vs r=8 at <1% extra params on a 0.6B base;\n","# task_3 (link_accounts) needs the extra plasticity.\n","LORA_R = 16\n","LORA_ALPHA = 32\n","LORA_DROPOUT = 0.05\n","LORA_TARGETS = [\"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\"]\n","\n","# ---- GRPO knobs ------------------------------------------------------\n","LEARNING_RATE = 2e-5\n","NUM_GENERATIONS = 4 # group size for GRPO\n","KL_BETA = 0.01\n","PER_DEVICE_BATCH = 2\n","GRAD_ACCUM = 8\n","MAX_COMPLETION_LEN = 256\n","MAX_PROMPT_LEN = 1024\n","NUM_EPOCHS = preset[\"epochs\"]\n","SAVE_STEPS = 50\n","LOG_STEPS = 1\n","SEED = 7\n","\n","# Skip the BEFORE eval (saves ~5-10 min by not reloading the base model\n","# a second time). Flip to True only on your first run, or when you change\n","# the base model.\n","RUN_BEFORE_EVAL = True\n","\n","PUSH_TO_HUB = False # flip to True after setting HUB_REPO_ID\n","\n","config_summary = {\n"," \"mode\": MODE,\n"," \"base_model\": BASE_MODEL,\n"," \"n_episodes\": len(TASKS) * len(train_seeds),\n"," \"n_eval_episodes\": len(TASKS) * len(EVAL_SEEDS),\n"," \"epochs\": NUM_EPOCHS,\n"," \"lora\": {\"r\": LORA_R, \"alpha\": LORA_ALPHA, \"targets\": LORA_TARGETS},\n"," \"grpo\": {\n"," \"lr\": LEARNING_RATE, \"num_generations\": NUM_GENERATIONS,\n"," \"kl_beta\": KL_BETA, \"max_completion_len\": MAX_COMPLETION_LEN,\n"," },\n"," \"output_dir\": str(OUTPUT_DIR),\n"," \"push_to_hub\": PUSH_TO_HUB,\n"," \"run_before_eval\": RUN_BEFORE_EVAL,\n","}\n","print(json.dumps(config_summary, indent=2))"]},{"cell_type": "markdown","id": "03d80250","metadata": {},"source": ["## Section 3 - Load Qwen3-0.6B + LoRA\n","\n","We load the model in 4-bit (NF4) to fit on a T4 with room for activations and the LoRA optimizer state, then attach a small LoRA on the attention projections only.\n","\n","`HFInvestigator` wraps the base model + tokenizer with the same prompt-builder, JSON parser, and scripted-fallback wiring that the production HTTP investigator uses, so the trained policy ports cleanly.\n","\n","`enable_thinking=False` tells Qwen3's chat template to skip its chain-of-thought wrapper - we want the model to output the JSON action directly."]},{"cell_type": "code","execution_count": null,"id": "35451786","metadata": {},"outputs": [],"source": ["from counterfeint.agents import HFInvestigator\n","\n","print(f\"Loading {BASE_MODEL} (load_in_4bit={LOAD_IN_4BIT}) ...\")\n","hf_investigator = HFInvestigator.from_pretrained(\n"," BASE_MODEL,\n"," load_in_4bit=LOAD_IN_4BIT,\n"," max_new_tokens=MAX_NEW_TOKENS,\n"," temperature=TEMPERATURE,\n"," do_sample=True,\n"," enable_thinking=False,\n",")\n","print(\"Loaded.\")"]},{"cell_type": "code","execution_count": null,"id": "2d54dd78","metadata": {},"outputs": [],"source": ["from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training\n","\n","if LOAD_IN_4BIT:\n"," hf_investigator.model = prepare_model_for_kbit_training(hf_investigator.model)\n","\n","lora_cfg = LoraConfig(\n"," r=LORA_R,\n"," lora_alpha=LORA_ALPHA,\n"," lora_dropout=LORA_DROPOUT,\n"," target_modules=LORA_TARGETS,\n"," bias=\"none\",\n"," task_type=\"CAUSAL_LM\",\n",")\n","hf_investigator.model = get_peft_model(hf_investigator.model, lora_cfg)\n","hf_investigator.model.print_trainable_parameters()"]},{"cell_type": "code","execution_count": null,"id": "ad0f5b1e","metadata": {},"outputs": [],"source": ["probe_msgs = [\n"," {\"role\": \"system\", \"content\": \"You output one line of valid JSON only.\"},\n"," {\"role\": \"user\", \"content\": \"Reply with {\\\"ok\\\": true}\"},\n","]\n","probe_text = hf_investigator._call_chat(probe_msgs)\n","print(f\"Smoke-test completion (first 200 chars):\\n{probe_text[:200]!r}\")"]},{"cell_type": "markdown","id": "3b58950d","metadata": {},"source": ["## Section 4 - Collect rollouts\n","\n","Run multi-agent episodes in-process (`RefereeEnvironment` directly) with the trainable Investigator + scripted Fraudster + heuristic Auditor. We record every Investigator `act()` call as a `(prompt, completion, reward)` row.\n","\n","**Reward shaping** (in `records_to_samples`): the episode-level Investigator reward is split across turns 80/20 between verdict-class and investigate-class actions. This gives stronger gradient on the actions that actually move the grader.\n","\n","The smoke run with 6 episodes typically takes ~3-5 min on a T4."]},{"cell_type": "code","execution_count": null,"id": "442c8c21","metadata": {},"outputs": [],"source": ["import time\n","from counterfeint.training import (\n"," collect_dataset_in_process,\n"," samples_to_hf_dataset,\n",")\n","from counterfeint.scripted import HeuristicAuditor, ReactiveFraudster\n","\n","t0 = time.perf_counter()\n","samples = collect_dataset_in_process(\n"," hf_investigator=hf_investigator,\n"," seeds_by_task=TRAIN_SEEDS_BY_TASK,\n"," fraudster_factory=lambda: ReactiveFraudster(seed=42),\n"," auditor_factory=lambda: HeuristicAuditor(),\n"," max_steps=80,\n"," show_trace=False,\n",")\n","elapsed = time.perf_counter() - t0\n","print(f\"\\nCollected {len(samples)} training rows in {elapsed:.1f}s \"\n"," f\"({elapsed / max(1, len(samples)):.2f}s/row).\")\n","print(f\"Investigator fallback: {hf_investigator.fallback_count}/{hf_investigator.call_count}\")"]},{"cell_type": "code","execution_count": null,"id": "4cde9e16","metadata": {},"outputs": [],"source": ["if not samples:\n"," raise RuntimeError(\n"," \"No usable Investigator turns were collected. Every step must have \"\n"," \"fallen back to the scripted policy. Check fallback_count above and \"\n"," \"the smoke-test completion in Section 3.\"\n"," )\n","\n","import statistics\n","\n","rewards = [s.reward for s in samples]\n","grader_scores = sorted({(s.task_id, s.seed, s.terminal_grader_score) for s in samples})\n","class_counts = {\"verdict\": 0, \"investigate\": 0}\n","for s in samples:\n"," class_counts[s.metadata.get(\"action_class\", \"investigate\")] += 1\n","\n","print(f\"Rows: {len(samples)}\")\n","print(f\"Reward mean: {statistics.mean(rewards):+.4f}\")\n","print(f\"Reward stdev: {statistics.pstdev(rewards):+.4f}\")\n","print(f\"Reward min/max: {min(rewards):+.4f} / {max(rewards):+.4f}\")\n","print(f\"Action classes: {class_counts}\")\n","print(f\"\\nPer-episode grader_score:\")\n","for task_id, seed, gs in grader_scores:\n"," print(f\" {task_id} seed={seed:>3}: {gs:+.4f}\")"]},{"cell_type": "code","execution_count": null,"id": "1978e460","metadata": {},"outputs": [],"source": ["# Drop any rows where the recorded completion was empty / not-JSON. The\n","# proxy reward already penalizes invalid JSON, but training on a dataset\n","# of mostly-broken completions wastes batches; the model learns more from\n","# good examples. We keep at most 90% of original rows.\n","def _looks_like_json(completion):\n"," if not completion:\n"," return False\n"," stripped = completion.strip()\n"," return stripped.startswith(\"{\") and \"action_type\" in stripped\n","\n","clean_samples = [s for s in samples if _looks_like_json(s.completion)]\n","dropped = len(samples) - len(clean_samples)\n","if dropped:\n"," print(f\"Filtered out {dropped}/{len(samples)} rows with invalid completions.\")\n","samples = clean_samples or samples # fall back if filter would empty everything\n","\n","from counterfeint.agents.prompts import INVESTIGATOR_SYSTEM_PROMPT\n","train_dataset = samples_to_hf_dataset(samples, system_prompt=INVESTIGATOR_SYSTEM_PROMPT)\n","print(train_dataset)\n","print(\"\\nFirst row preview:\")\n","preview = train_dataset[0]\n","print(f\" prompt (first 300 chars): {preview['prompt'][:300]!r}\")\n","print(f\" completion (first 200 chars): {preview['completion'][:200]!r}\")\n","print(f\" reward : {preview['reward']:+.4f}\")\n","print(f\" task_id / seed : {preview['task_id']} / {preview['seed']}\")\n","print(f\" action_class : {preview['metadata'].get('action_class')}\")"]},{"cell_type": "markdown","id": "ec036f17","metadata": {},"source": ["## Section 5 - GRPO Training\n","\n","The `proxy_reward_fn` scores any `(prompt, completion)` pair without touching the env, so it works on TRL's freshly-generated rollouts. It rewards:\n","\n","- **+0.6** for valid `AdReviewAction` JSON (schema validity)\n","- **+0.1** each for `ad_id` / `linked_ad_id` referenced in the prompt (coherence)\n","- **+0.2** for matching the recorded gold action class (verdict / investigate / link)\n","- **up to +0.6** for matching the recorded gold decision, scaled by the episode's `grader_score` quality\n","\n","Range: roughly `[-0.5, +2.0]`.\n","\n","`GRPOTrainer` runs `num_generations=4` rollouts per prompt, scores them with this reward, and updates LoRA via group-relative policy optimization with `KL_BETA=0.01` regularization to the frozen base."]},{"cell_type": "code","execution_count": null,"id": "230d00e4","metadata": {},"outputs": [],"source": ["from counterfeint.training import build_gold_lookup, make_proxy_reward_fn\n","\n","gold_lookup = build_gold_lookup(samples)\n","proxy_reward_fn = make_proxy_reward_fn(gold_lookup=gold_lookup)\n","print(f\"Built gold lookup with {len(gold_lookup)} entries.\")\n","\n","# Quick sanity check: score a known-good completion.\n","sample_prompt = samples[0].prompt\n","sample_completion = samples[0].completion\n","sample_reward = proxy_reward_fn([sample_prompt], [sample_completion])\n","print(f\"Proxy reward on a recorded completion: {sample_reward}\")"]},{"cell_type": "code","execution_count": null,"id": "2b13794d","metadata": {},"outputs": [],"source": ["import inspect\n","from trl import GRPOConfig, GRPOTrainer\n","\n","# Build the config kwargs incrementally so we tolerate older/newer TRL\n","# versions: ``max_prompt_length`` was removed in TRL >=1.0 (the prompt is\n","# now truncated by tokenizer.model_max_length).\n","_grpo_kwargs = dict(\n"," output_dir=str(OUTPUT_DIR / \"trl_checkpoints\"),\n"," learning_rate=LEARNING_RATE,\n"," num_generations=NUM_GENERATIONS,\n"," beta=KL_BETA,\n"," per_device_train_batch_size=PER_DEVICE_BATCH,\n"," gradient_accumulation_steps=GRAD_ACCUM,\n"," max_completion_length=MAX_COMPLETION_LEN,\n"," num_train_epochs=NUM_EPOCHS,\n"," save_steps=SAVE_STEPS,\n"," logging_steps=LOG_STEPS,\n"," gradient_checkpointing=True,\n"," gradient_checkpointing_kwargs={\"use_reentrant\": False},\n"," report_to=\"none\",\n"," seed=SEED,\n"," remove_unused_columns=False,\n",")\n","_grpo_params = set(inspect.signature(GRPOConfig.__init__).parameters)\n","if \"max_prompt_length\" in _grpo_params:\n"," _grpo_kwargs[\"max_prompt_length\"] = MAX_PROMPT_LEN\n","else:\n"," hf_investigator.tokenizer.model_max_length = max(\n"," MAX_PROMPT_LEN + MAX_COMPLETION_LEN,\n"," getattr(hf_investigator.tokenizer, \"model_max_length\", 0) or 0,\n"," )\n","\n","if \"temperature\" in _grpo_params:\n"," _grpo_kwargs[\"temperature\"] = 0.9\n","\n","trl_config = GRPOConfig(**_grpo_kwargs)\n","\n","trainer = GRPOTrainer(\n"," model=hf_investigator.model,\n"," args=trl_config,\n"," train_dataset=train_dataset,\n"," reward_funcs=[proxy_reward_fn],\n"," processing_class=hf_investigator.tokenizer,\n",")\n","if hasattr(trainer, \"generation_config\"):\n"," trainer.generation_config.temperature = 0.9\n"," trainer.generation_config.do_sample = True\n","print(\"GRPOTrainer ready (generation temperature=0.9).\")"]},{"cell_type": "code","execution_count": null,"id": "5a73186c","metadata": {},"outputs": [],"source": ["train_t0 = time.perf_counter()\n","train_result = trainer.train()\n","print(f\"\\nTraining took {(time.perf_counter() - train_t0) / 60:.1f} min.\")\n","print(train_result)"]},{"cell_type": "code","execution_count": null,"id": "903ec104","metadata": {},"outputs": [],"source": ["lora_dir = OUTPUT_DIR / \"lora_adapter\"\n","lora_dir.mkdir(parents=True, exist_ok=True)\n","\n","trainer.save_model(str(lora_dir))\n","hf_investigator.tokenizer.save_pretrained(str(lora_dir))\n","\n","with open(OUTPUT_DIR / \"training_config.json\", \"w\") as f:\n"," json.dump(config_summary, f, indent=2)\n","\n","print(f\"Saved LoRA adapter + tokenizer to: {lora_dir}\")"]},{"cell_type": "markdown","id": "8b537a16","metadata": {},"source": ["## Section 6 - Loss / reward curves\n","\n","The submission requirement asks for \"loss and reward plots from a real run.\" We pull TRL's `log_history` (which contains per-`logging_steps` records of `loss`, `reward`, `kl`, `learning_rate`, ...) and render them with matplotlib."]},{"cell_type": "code","execution_count": null,"id": "93451503","metadata": {},"outputs": [],"source": ["import matplotlib.pyplot as plt\n","\n","log_history = trainer.state.log_history\n","log_path = OUTPUT_DIR / \"log_history.json\"\n","with open(log_path, \"w\") as f:\n"," json.dump(log_history, f, indent=2, default=str)\n","print(f\"Wrote {log_path} ({len(log_history)} entries).\")\n","\n","steps_loss, losses = [], []\n","steps_rew, rewards_log = [], []\n","steps_kl, kls = [], []\n","\n","for entry in log_history:\n"," step = entry.get(\"step\")\n"," if step is None:\n"," continue\n"," if \"loss\" in entry:\n"," steps_loss.append(step); losses.append(entry[\"loss\"])\n"," if \"reward\" in entry:\n"," steps_rew.append(step); rewards_log.append(entry[\"reward\"])\n"," if \"kl\" in entry:\n"," steps_kl.append(step); kls.append(entry[\"kl\"])\n","\n","fig, axes = plt.subplots(1, 3, figsize=(15, 4))\n","\n","axes[0].plot(steps_loss, losses, color=\"tab:red\")\n","axes[0].set_title(\"GRPO loss\")\n","axes[0].set_xlabel(\"step\"); axes[0].set_ylabel(\"loss\")\n","axes[0].grid(True, alpha=0.3)\n","\n","axes[1].plot(steps_rew, rewards_log, color=\"tab:green\")\n","axes[1].set_title(\"Mean reward\")\n","axes[1].set_xlabel(\"step\"); axes[1].set_ylabel(\"reward\")\n","axes[1].grid(True, alpha=0.3)\n","\n","axes[2].plot(steps_kl, kls, color=\"tab:blue\")\n","axes[2].set_title(\"KL divergence\")\n","axes[2].set_xlabel(\"step\"); axes[2].set_ylabel(\"KL\")\n","axes[2].grid(True, alpha=0.3)\n","\n","fig.suptitle(f\"GRPO training - {BASE_MODEL} - mode={MODE}\")\n","fig.tight_layout()\n","\n","plot_path = OUTPUT_DIR / \"training_curves.png\"\n","fig.savefig(plot_path, dpi=120, bbox_inches=\"tight\")\n","plt.show()\n","print(f\"Saved plot to {plot_path}\")"]},{"cell_type": "markdown","id": "09aeb21f","metadata": {},"source": ["## Section 7 - Before/After evaluation\n","\n","Run the **trained** Investigator on held-out seeds and compare the grader_score against:\n","\n","- **Before**: the *base* Qwen3-0.6B without LoRA (i.e. what we started with)\n","\n","We use the in-process driver again (no HTTP server needed). The Fraudster + Auditor are deterministic so the only thing that changes between Before and After is the Investigator's policy."]},{"cell_type": "code","execution_count": null,"id": "432e5f62","metadata": {},"outputs": [],"source": ["from counterfeint.server.referee import RefereeEnvironment\n","\n","\n","def run_eval_episode(investigator, *, task_id: str, seed: int, max_steps: int = 80):\n"," \"\"\"In-process episode runner for evaluation. Returns flat metrics dict.\"\"\"\n"," env = RefereeEnvironment()\n"," env.reset_match(task_id=task_id, seed=seed)\n","\n"," fraudster = ReactiveFraudster(seed=42)\n"," auditor = HeuristicAuditor()\n","\n"," role_handlers = {\n"," \"fraudster_turn\": (fraudster, env.build_fraudster_observation, env.step_as_fraudster),\n"," \"investigator_turn\":(investigator, env.build_investigator_observation, env.step_as_investigator),\n"," \"audit_phase\": (auditor, env.build_auditor_observation, env.step_as_auditor),\n"," }\n","\n"," step_idx = 0\n"," n_verdicts = 0\n"," while env.phase in role_handlers:\n"," current_phase = env.phase\n"," policy, build_obs, step_fn = role_handlers[current_phase]\n"," if current_phase != \"audit_phase\" and step_idx >= max_steps:\n"," break\n"," obs = build_obs().model_dump()\n"," for slot in (\"last_prompt\", \"last_completion\", \"last_error\"):\n"," if hasattr(policy, slot):\n"," setattr(policy, slot, None)\n"," try:\n"," action = policy.act(obs)\n"," except Exception:\n"," break\n"," try:\n"," step_fn(action)\n"," except Exception:\n"," break\n"," if current_phase != \"audit_phase\":\n"," step_idx += 1\n"," if current_phase == \"investigator_turn\" and getattr(action, \"action_type\", None) in (\"verdict\", \"link_accounts\"):\n"," n_verdicts += 1\n","\n"," state = env.state\n"," return {\n"," \"task_id\": task_id,\n"," \"seed\": seed,\n"," \"grader_score\": getattr(state, \"grader_score\", None),\n"," \"end_reason\": getattr(state, \"end_reason\", None),\n"," \"stopped_phase\": env.phase,\n"," \"n_verdicts\": n_verdicts,\n"," \"investigator_fallback\": getattr(investigator, \"fallback_count\", 0),\n"," }\n","\n","\n","def run_eval_suite(investigator, *, label: str, seeds_by_task):\n"," print(f\"\\n=== Evaluating {label} ===\")\n"," results = []\n"," for task_id, seeds in seeds_by_task.items():\n"," for seed in seeds:\n"," fb_before = getattr(investigator, \"fallback_count\", 0)\n"," r = run_eval_episode(investigator, task_id=task_id, seed=seed)\n"," r[\"investigator_fallback_delta\"] = (\n"," getattr(investigator, \"fallback_count\", 0) - fb_before\n"," )\n"," results.append(r)\n"," print(f\" {task_id} seed={seed:>3}: grader={r['grader_score']} \"\n"," f\"verdicts={r['n_verdicts']} fallback+={r['investigator_fallback_delta']}\")\n"," return results"]},{"cell_type": "code","execution_count": null,"id": "0b36c76c","metadata": {},"outputs": [],"source": ["after_results = run_eval_suite(\n"," hf_investigator,\n"," label=\"AFTER (trained Qwen3-0.6B + LoRA)\",\n"," seeds_by_task=EVAL_SEEDS_BY_TASK,\n",")"]},{"cell_type": "code","execution_count": null,"id": "741c6e04","metadata": {},"outputs": [],"source": ["import gc\n","\n","if not RUN_BEFORE_EVAL:\n"," print(\"RUN_BEFORE_EVAL=False - skipping the base-model reload pass.\")\n"," print(\"Using a synthetic BEFORE = 0.0 baseline (or paste numbers from a\")\n"," print(\"previous run into `before_results` below if you have them).\")\n"," before_results = [\n"," {\n"," \"task_id\": r[\"task_id\"], \"seed\": r[\"seed\"], \"grader_score\": 0.0,\n"," \"end_reason\": \"skipped\", \"stopped_phase\": \"skipped\",\n"," \"n_verdicts\": 0, \"investigator_fallback\": 0,\n"," \"investigator_fallback_delta\": 0,\n"," }\n"," for r in after_results\n"," ]\n","else:\n"," del trainer\n"," del hf_investigator\n"," gc.collect()\n"," if torch.cuda.is_available():\n"," torch.cuda.empty_cache()\n"," print(\"Trained model unloaded; reloading the *base* Qwen3-0.6B for the BEFORE eval ...\")\n","\n"," baseline_investigator = HFInvestigator.from_pretrained(\n"," BASE_MODEL,\n"," load_in_4bit=LOAD_IN_4BIT,\n"," max_new_tokens=MAX_NEW_TOKENS,\n"," temperature=TEMPERATURE,\n"," do_sample=True,\n"," enable_thinking=False,\n"," )\n","\n"," before_results = run_eval_suite(\n"," baseline_investigator,\n"," label=\"BEFORE (base Qwen3-0.6B, no LoRA)\",\n"," seeds_by_task=EVAL_SEEDS_BY_TASK,\n"," )"]},{"cell_type": "code","execution_count": null,"id": "9366f804","metadata": {},"outputs": [],"source": ["def _scores(rows):\n"," return [r[\"grader_score\"] or 0.0 for r in rows]\n","\n","before_scores = _scores(before_results)\n","after_scores = _scores(after_results)\n","\n","eval_summary = {\n"," \"n_eval_episodes\": len(before_results),\n"," \"before\": {\n"," \"mean_grader_score\": sum(before_scores) / max(1, len(before_scores)),\n"," \"verdicts_total\": sum(r[\"n_verdicts\"] for r in before_results),\n"," \"fallback_total\": sum(r[\"investigator_fallback_delta\"] for r in before_results),\n"," },\n"," \"after\": {\n"," \"mean_grader_score\": sum(after_scores) / max(1, len(after_scores)),\n"," \"verdicts_total\": sum(r[\"n_verdicts\"] for r in after_results),\n"," \"fallback_total\": sum(r[\"investigator_fallback_delta\"] for r in after_results),\n"," },\n","}\n","eval_summary[\"delta_grader_score\"] = (\n"," eval_summary[\"after\"][\"mean_grader_score\"] - eval_summary[\"before\"][\"mean_grader_score\"]\n",")\n","\n","print(json.dumps(eval_summary, indent=2))\n","\n","with open(OUTPUT_DIR / \"eval_summary.json\", \"w\") as f:\n"," json.dump({\n"," \"summary\": eval_summary,\n"," \"before\": before_results,\n"," \"after\": after_results,\n"," }, f, indent=2)"]},{"cell_type": "code","execution_count": null,"id": "7b53775e","metadata": {},"outputs": [],"source": ["labels = [f\"{r['task_id']}/{r['seed']}\" for r in before_results]\n","x = list(range(len(labels)))\n","width = 0.4\n","\n","fig, ax = plt.subplots(figsize=(max(8, len(labels) * 0.6), 5))\n","ax.bar([xi - width/2 for xi in x], before_scores, width, label=\"Before (base)\", color=\"tab:gray\")\n","ax.bar([xi + width/2 for xi in x], after_scores, width, label=\"After (trained)\", color=\"tab:green\")\n","ax.set_xticks(x)\n","ax.set_xticklabels(labels, rotation=45, ha=\"right\")\n","ax.set_ylabel(\"grader_score\")\n","ax.set_title(f\"Before vs After - {BASE_MODEL} - mode={MODE}\")\n","ax.legend()\n","ax.grid(True, axis=\"y\", alpha=0.3)\n","fig.tight_layout()\n","\n","eval_plot_path = OUTPUT_DIR / \"eval_plot.png\"\n","fig.savefig(eval_plot_path, dpi=120, bbox_inches=\"tight\")\n","plt.show()\n","print(f\"Saved {eval_plot_path}\")"]},{"cell_type": "markdown","id": "e20c9615","metadata": {},"source": ["## Section 8 - Push to Hub (optional)\n","\n","Set `PUSH_TO_HUB = True` in Section 2 and replace `<your-username>` in `HUB_REPO_ID` to push the LoRA adapter + tokenizer + training/eval artefacts to a public HF Hub repo. The README on your CounterFeint env Space can then link to this adapter."]},{"cell_type": "code","execution_count": null,"id": "a8d0f210","metadata": {},"outputs": [],"source": ["if not PUSH_TO_HUB:\n"," print(\"PUSH_TO_HUB=False — skipping. Flip it in Section 2 once you're ready.\")\n","else:\n"," if HUB_REPO_ID.startswith(\"<\"):\n"," raise RuntimeError(\n"," \"Set HUB_REPO_ID in Section 2 to '<your-hf-username>/<repo-name>' \"\n"," \"before pushing.\"\n"," )\n","\n"," from huggingface_hub import HfApi\n","\n"," api = HfApi()\n"," api.create_repo(repo_id=HUB_REPO_ID, private=False, exist_ok=True)\n"," print(f\"Created/found repo {HUB_REPO_ID}\")\n","\n"," api.upload_folder(\n"," repo_id=HUB_REPO_ID,\n"," folder_path=str(OUTPUT_DIR),\n"," commit_message=f\"GRPO {MODE} run on {BASE_MODEL}\",\n"," )\n"," print(f\"Uploaded {OUTPUT_DIR} -> {HUB_REPO_ID}\")"]},{"cell_type": "markdown","id": "d4279d60","metadata": {},"source": ["## Done\n","\n","You should now have, under `OUTPUT_DIR`:\n","\n","- `lora_adapter/` - the trained PEFT adapter (`adapter_config.json` + safetensors) and tokenizer\n","- `training_curves.png` - GRPO loss / reward / KL curves\n","- `eval_plot.png` - before/after grader_score per held-out episode\n","- `eval_summary.json` - mean grader_score before/after, fallback counts\n","- `log_history.json` - raw TRL training log\n","- `training_config.json` - the config that produced this run\n","\n","To run a bigger experiment: change `MODE = \"demo\"` in Section 2, restart the kernel, and re-run all cells. With the $30 HF Spaces budget you have ~20 demo-mode runs to iterate on hyperparameters / model size."]}],"metadata": {"kernelspec": {"display_name": "Python 3","language": "python","name": "python3"},"language_info": {"name": "python","version": "3.11"}},"nbformat": 4,"nbformat_minor": 5}
.gitattributes+4
README.md+115-452
agents/llm_fraudster.py+287-287
assets/Fraudster Reward.pngAdded

Large File Pointer Details
- SHA256: 2fbbfbb1ea90cf5dd1e6db74bebfff66cae97cd1a71b412768ba9d3d5a237f94
- Pointer size: 131 Bytes
- Size of remote file: 236 kB
assets/HF Spaces.pngAdded

Large File Pointer Details
- SHA256: a06f876e4177aa6966d4b0dbd264923987b8aa2350b6c83eb4032dcc64e6f8cf
- Pointer size: 131 Bytes
- Size of remote file: 324 kB
assets/Investigator Reward.pngAdded

Large File Pointer Details
- SHA256: c3a71f67e5422133ac8e2984f36c39a9abf72dd69434ddc1b7614b2088961bff
- Pointer size: 131 Bytes
- Size of remote file: 723 kB
assets/Loss-reward-KL curve.pngAdded

Large File Pointer Details
- SHA256: e18d130a67a1a1127fc5c63cc41d1365846f28f84fadfc62cfba83e28d43bcb5
- Pointer size: 131 Bytes
- Size of remote file: 185 kB
blog.mdAdded+102
training/TRAINING_GUIDE.md+366-366
training/baseline_eval.ipynb+512-512
training/compare_runs.ipynb+370-370
training/official_hf_training.ipynb+950-950
training/train_investigator.ipynb