# Caveat classifier: training brief This is the full brief for training and shipping the in-browser classifier behind [`Devseis/Caveat`](https://huggingface.co/spaces/Devseis/Caveat). It is written so a coding agent or a person can run it end to end. **Follow the rules in §2**, and stop to ask in the situations listed in §8. --- ## 1. Context Caveat takes a free-text description of an AI system and returns its EU AI Act tier: | Label | Meaning | |---|---| | `prohibited` | Art 5 banned practice | | `high_risk` | Annex III use case, or Annex I product safety component | | `limited_risk` | Art 50 transparency duties (chatbots, deepfakes, AI-written public text) | | `minimal_risk` | none of the above | - **The model has exactly these 4 classes.** General-purpose AI (GPAI) models are handled by a separate rule, `../caveat-gpai/gpai_rule.js`, which runs *before* the model. **Do not add GPAI classes to the model.** - **It runs in the browser.** The model is served through transformers.js, as an int8 ONNX export of about 70 MB or less. - **Machine:** an Intel Mac, CPU only, PyTorch 2.2.2 (the last version for Intel Macs). The pinned versions are in `requirements.txt`, and `.venv` is already set up. - **The published baseline** is `Devseis/eu-ai-act-classifier-experiment` (DistilBERT). On `test_v2` it scores accuracy **0.765**, macro-F1 **0.794** and prohibited recall **0.900**. `compare.py` reproduces these numbers first, as a sanity check. ### Scenarios vs rows A **scenario** is one distinct use case with one label. Each scenario appears as **3 rows** in the CSVs: the same text, with a different opening phrase (for example "Our client wants to deploy…"). Splits are made **by scenario**, so all 3 rows of a scenario are always in the same split. This means the real sample size is the scenario count, not the row count. Always report both. --- ## 2. Rules (non-negotiable) 1. **Never edit anything in `data/`, `data_v3/`, `data_v4/` or `data_v4_systems/`.** They are versioned inputs. If data needs changing, stop and ask. 2. **Never move rows between splits, and never re-split.** The scenario-grouped splits are deliberate. 3. **Choose checkpoints and hyperparameters on validation only.** Evaluate on test **once per final configuration**. Never pick a model, epoch or learning rate by looking at test scores. 4. **The model has 4 classes.** Use `data_v5_systems/`, not `data_v4/` (which has GPAI classes and is for reference only). 5. **Don't push anything to the Hugging Face Hub** (models, Space or dataset) without explicit approval from Umer. 6. Keep `results/` (the v2 comparison) as it is. Write new results to `results_v4/`. --- ## 3. Data versions | Folder | Scenarios | Rows (train / val / test) | Use for | |---|---|---|---| | `data/` (`*_v2.csv`) | 268 | 519 / 123 / 162 | Only for reproducing the published baseline and the running backbone comparison | | `data_v3/` | 267 | 519 / 120 / 162 | Label fixes only (see `data_v3/CHANGES.md`) | | `data_v4/` | 344 | 678 / 150 / 204 | 6 labels incl. GPAI. Reference, **not for training** | | `data_v4_systems/` | 304 | 597 / 132 / 183 | v4 model comparison (done; results in `results_v4/`) | | **`data_v5_systems/`** | **327** | **636 / 147 / 198** | **Training and evaluation for the shipped model** (v4 + limited_risk fix, see its `CHANGES.md`) | The v3/v4 changes are documented in each folder's `CHANGES.md`. In summary: - Six v2 labels were wrong under the Act and have been fixed. Three of them were in test: scenario 148. - Seven scenarios were reworded so the text states the legal test. - One contradictory duplicate was dropped. - All 661 ungrammatical template rows were fixed. - New scenarios were added: Annex I products, the AI Omnibus prohibitions (Art 5(1)(ba)/(bb), which apply from 2 Dec 2026), the Art 6(3) profiling counter-examples and derogations, contrast cases, and downstream builders. The new v4 scenarios are listed in `relabel_audit/new_scenarios_v4.csv`, with their split and legal basis. --- ## 4. Steps ### Step 1: Finish the running backbone comparison (v2) `compare.py` is running DistilBERT, legal-bert-small and SetFit (bge-small-en-v1.5), each over 3 seeds, on `data/*_v2.csv`. Let it finish, and **don't edit `compare.py` while it runs**. The output goes to `results/summary.md`. This tells us which backbone suits the data. It is **not** the final model. ### Step 2: Make the script data-version aware Copy `compare.py` to `train_v4.py` and change it to: - read `data_v4_systems/{train,val,test}_v4.csv` (add `--data` and `--suffix` arguments) - write to `results_v4/` - skip the published-checkpoint sanity check, which only applies to v2, or run it on `test_v4` and report it as the old baseline. Leave `LABELS` in the same order as the published `id2label`: `["minimal_risk","limited_risk","high_risk","prohibited"]`. ### Step 3: Tune every model the same way, on validation Every backbone gets the same budget, and the choice is made on **validation macro-F1** only: - **Fine-tuned models (DistilBERT, legal-bert-small, optionally deberta-v3-xsmall):** - learning rate ∈ {2e-5, 3e-5, 5e-5} - up to 15 epochs, keeping the best epoch by validation macro-F1 - batch size 16, weight decay 0.01, warmup 10% - **SetFit (bge-small-en-v1.5):** `num_iterations` ∈ {10, 20} × `num_epochs` ∈ {1, 2}. - **Imbalance handling:** try class-weighted cross-entropy (weights = inverse class frequency) on the fine-tuned models. Keep it if validation macro-F1 doesn't drop and **validation prohibited recall** improves. A missed banned practice is the most costly error Caveat can make. - Run the tuning with seed 42 only. ### Step 4: Final runs For each backbone's best configuration, train with seeds **42, 43, 44** and evaluate on `test_v4` **once**. ### Step 5: Report (write to `results_v4/report.md`) For each model, give the mean ± std over the 3 seeds for: - accuracy, macro-F1, and per-class recall; **prohibited recall is the headline metric** - **95% bootstrap confidence intervals** for accuracy and macro-F1, resampling **by scenario** (1,000 resamples; all 3 rows of a scenario go together) - **severe errors**: the count of prohibited scenarios predicted as `minimal_risk` or `limited_risk`, shown separately from prohibited→high_risk errors - the confusion matrix (summed over seeds) - **subgroup scores**: original v3 scenarios vs the new v4 scenarios (join on text with `relabel_audit/new_scenarios_v4.csv`), and within the new ones, per area (Annex I, Omnibus prohibitions, Art 6(3), contrasts) - the number of test scenarios and test rows, e.g. "183 rows / 61 scenarios" **Optional out-of-distribution check.** If `../eu-ai-act-risk-classification/synthetic/test.csv` exists (the v2.2 dataset package): 1. Drop the rows labelled `gpai` or `gpai_systemic_risk`. 2. Evaluate on the remaining rows. This set was written in a different style by a different generator. 3. Report it separately. A large drop compared with `test_v4` means the model learned the templates rather than the law. ### Step 6: Choose the model Pick the highest test macro-F1, with these tiebreaks: - **When the confidence intervals overlap:** prefer higher prohibited recall, then fewer severe errors, then the smaller ONNX export. - **When no model beats the others outside its confidence interval:** say so plainly in the report. Don't declare a winner on noise. ### Step 7: Export for the browser 1. Retrain the chosen configuration (seed 42), then export to ONNX and quantise to int8 (`optimum` / `onnxruntime`) in the format transformers.js expects. 2. Check that the int8 file is ≈ 70 MB or less. 3. Check that the ONNX int8 predictions agree with the PyTorch predictions on ≥ 99% of `test_v4` rows. Report any disagreements. 4. Save to `export/`. Do **not** upload. ### Step 8: Wire in the GPAI rule Copy `../caveat-gpai/gpai_rule.js` into the Space code and call it before the classifier. The snippet is in `../caveat-gpai/README.md`. Run `node test.mjs` in `../caveat-gpai/`; it must print `655/655 correct`. ### Step 9: Draft the model card (don't publish) Write `export/MODEL_CARD.md`. It must state: - the training data (`data_v4_systems`, scenario and row counts), and that the data is synthetic and template-expanded - the v3/v4 label corrections, including that 3 `test_v2` labels were wrong in the published evaluation - the test results with confidence intervals and the headline prohibited recall - that **age/sex estimation from biometrics** is labelled `high_risk` (Annex III(1)(b)) as a policy choice, because the law is unsettled on this - that **the Omnibus prohibitions** (Art 5(1)(ba)/(bb)) apply from **2 Dec 2026**, so the labels reflect the law from that date - that **GPAI is decided by a rule**, not by the model - that the tool is not legal advice --- ## 4b. Retrain on v5 (current task, decided 2026-09-30) The v4 comparison chose **legal-bert-small** (tie on macro-F1; much higher prohibited recall; half the size). Class weights were **not** approved. 1. Train legal-bert-small on `data_v5_systems/` using the v4-tuned config (lr 2e-5, no class weights, best epoch by val macro-F1), with seeds 42, 43, 44. Write to `results_v5/`. 2. Report everything from Step 5, twice: on the full `test_v5`, and on the `test_v4` subset (drop the test rows listed in `relabel_audit/new_scenarios_v5.csv`). 3. Also show limited_risk recall per scenario on the 5 original limited test scenarios: the phone agents are the ones to watch. 4. Compare against the published model on the `test_v4` subset, and against the v4 legal-bert results. 5. If v5 matches or beats the published model on prohibited recall, with no more severe errors, continue with Steps 7–9 (export, GPAI rule, model card). Otherwise stop and report. ## 5. Folder map ``` model-comparison/ README.md ← this brief compare.py backbone comparison on v2 (running; don't edit) requirements.txt pinned deps (Intel Mac) data/ data_v3/ data_v4/ data_v4_systems/ data_v5_systems/ versioned datasets, each with a CHANGES.md relabel_audit/ audit + build scripts (relabel_audit.py, apply_relabels.py, extend_v4.py) results/ v2 comparison output results_v4/ ← new results go here export/ ← ONNX + model card go here ../caveat-gpai/ GPAI rule for Caveat (JS) + tests ../eu-ai-act-risk-classification/ reference table (v1 on disk; v2.2 package delivered separately) ``` ## 6. Known data caveats (keep them in mind when reading results) - All scenarios are synthetic and template-expanded, so test scores are an **upper bound**. The real test would be real-world system descriptions labelled by a qualified reviewer. - The test sets are small: about 61 scenarios in `test_v4`. A gap of under about 5 points between models is usually noise. - `limited_risk` is the smallest class (22 scenarios in total), so expect its recall to vary most between seeds. ## 7. Time budget Everything runs on CPU. Roughly 5–15 minutes per fine-tuning run and 2–5 minutes per SetFit run. Run in the background and log to `run_v4.log`. ## 8. Stop and ask Umer when - the published checkpoint doesn't reproduce 0.765 / 0.794 / 0.900 on `test_v2` (the setup is wrong) - any data file looks wrong, or you want to change data or splits - the export is well over 70 MB, or ONNX/PyTorch agreement is below 99% - the results suggest a winner only by looking at test scores - before anything is uploaded to the Hugging Face Hub