Buckets:

142 MB
21,636 files
Updated 2 months ago
Name
Size
.github
.pytest_cache
.trunk
aegis-stressbench
aegis-ui
backend
benchmark_results
configs
data
docs
notebooks
outputs
paper
scripts
src
tests
._.github163 Bytes
xet
._.gitignore163 Bytes
xet
._.pytest_cache163 Bytes
xet
._.trunk163 Bytes
xet
._LICENSE163 Bytes
xet
._README.md163 Bytes
xet
._aegis-stressbench163 Bytes
xet
._aegis-ui163 Bytes
xet
._backend163 Bytes
xet
._benchmark_results163 Bytes
xet
._configs163 Bytes
xet
._data163 Bytes
xet
._docs163 Bytes
xet
._generate_figures.py163 Bytes
xet
._generate_paper_tables.py163 Bytes
xet
._grading.log163 Bytes
xet
._notebooks163 Bytes
xet
._outputs163 Bytes
xet
._paper163 Bytes
xet
._paper_results.json163 Bytes
xet
._pyproject.toml163 Bytes
xet
._requirements.txt163 Bytes
xet
._scripts163 Bytes
xet
._src163 Bytes
xet
._tests163 Bytes
xet
.gitignore100 Bytes
xet
LICENSE1.09 kB
xet
README.md21.6 kB
xet
generate_figures.py16.7 kB
xet
generate_paper_tables.py2.22 kB
xet
grading.log91.5 kB
xet
paper_results.json16.7 kB
xet
pyproject.toml1.8 kB
xet
requirements.txt223 Bytes
xet
training.log4.06 kB
xet
README.md

AEGIS: Adversarial Epistemic Guard for Invariant and Stable Judging in LLM-as-a-Judge

Python 3.10+ PyTorch 2.0+ Transformers Tests Paper PDF License: MIT


Research companion

AEGIS is both an experimental codebase and an interactive paper companion. Start with the manuscript, then use the browser experience to inspect the same objects—judge responses, adversarial pressure, evidence decisions, outcome states, and reward signals—in an executable form.

Start here What you get
Interactive AEGIS UI Guided tour, live demo, metrics, dataset explorer, comparison, glossary, and paper-style docs
Paper PDF Full 17-page manuscript with equations, proofs, figures, tables, and appendix
Paper source Reproducible LaTeX source and bibliography
Backend API FastAPI contracts for demo inference, metrics, trajectories, and model metadata
Architecture notes How the frontend, API, data, and training code fit together

The method in one picture

AEGIS architecture: judge, adversary, evidence model, outcome states, and minimax optimization

The shipped UI is mock-first by design: every interaction is available locally and every showcase statistic is labelled as demonstration data. Configure VITE_API_BASE_URL only when connecting a real evaluation service.

What makes AEGIS different

AEGIS does not optimize for stubbornness. It separates two cases that ordinary judge benchmarks conflate:

  1. Non-evidential pressure — rhetoric, confidence, popularity, or repetition without a new fact. A correct verdict should remain invariant.
  2. Evidence-bearing pressure — a relevant, verifiable fact that changes the information state. A capable judge should update when the evidence warrants it.

The framework therefore trains and evaluates a trajectory, not just a single answer:

input → initial verdict → adversarial pressure → evidence decision → final verdict → outcome/reward

The web companion exposes this trajectory step by step, while the paper gives the formal definitions and empirical protocol behind it.

Equations and notation

The central objective is a constrained two-player game:

max_{πθ} min_{πψ}  E[ Σₜ Rᶿₜ ]

The judge reward combines correctness and epistemic behavior:

Rᴶₜ = α₁·correct + α₂·stable + α₃·valid_correction
      − β₁·hard_flip − β₂·collapse − β₃·contradiction
      − β₄·non_evidential_flip + η·verification

The browser methodology and paper companion render these formulas in styled mathematical blocks with an offline-safe MathML fallback; the LaTeX manuscript remains the authoritative typeset source.

📌 Abstract

Large language models (LLMs) are widely deployed as automated judges for safety, toxicity, reasoning, and content quality. However, standard validation protocols evaluate models solely via static accuracy on golden datasets. Recent findings reveal a fundamental epistemic vulnerability: LLM judges frequently abandon correct verdicts under multi-turn adversarial pushback, even when the underlying evidence does not change. Accuracy alone does not imply epistemic stability.

AEGIS (Adversarial Epistemic Guard for Invariant and Stable Judging) is an end-to-end framework and training protocol that transforms LLM-as-a-judge from a brittle next-token predictor into an epistemically grounded decision-maker. AEGIS introduces three core pillars:

  1. Adversarial Multi-Turn Pressure: An adaptive adversary ensemble trained to challenge the judge across diverse rhetorical, authoritative, and pseudo-logical modalities under a natural-language fluency constraint.
  2. Evidence Validity Modeling: A two-stage Information Extraction (IE) and Natural Language Inference (NLI) pipeline that operationalizes whether adversary pressure introduces novel verifiable facts ($\Delta e$) or constitutes non-evidential rhetoric.
  3. Epistemic Reward Shaping: A reinforcement learning objective that rewards stability under non-evidential pressure, valid corrections under genuine evidence, and penalizes destructive hard flips, uncertainty collapse, and internal contradictions.

Formulated as a constrained minimax game and solved via alternating Proximal Policy Optimization (PPO), AEGIS reduces destructive hard flips from 38.6% to 8.2% and collapse to uncertainty from 20.2% to 5.4% across nine diverse benchmarks without imposing an alignment tax on general reasoning.


⚡ Quickstart & Installation

1. Environment Setup

# Clone the repository
git clone https://github.com/aegis-research/RL_AEGIS.git
cd RL_AEGIS

# Create virtual environment
python3 -m venv venv
source venv/bin/activate

# Install dependencies and AEGIS package in editable mode
pip install -r requirements.txt
pip install -e .

# For CUDA LoRA fine-tuning with 4-bit/8-bit loading (Linux/WSL recommended)
pip install -e '.[gpu]'

2. Verify Installation (Run the Unit & Integration Tests)

PYTHONPATH=src:. pytest tests/ -v

3. Minimax Training Loop

Launch the multi-turn PPO adversarial training loop on GSM8K, ToxiGen, or HC3:

# Using CLI script (the first non-option argument is the config)
bash scripts/train_aegis.sh configs/experiment/math_gsm8k.yaml --device cuda

# Or using Python pipeline directly
python3 src/aegis/pipelines/train.py \
    --config configs/experiment/math_gsm8k.yaml \
    --device cpu \
    --mock

### Memory-safe CUDA fine-tuning

An RTX 4070-class GPU should use the included quantized LoRA profile. It uses
TinyLlama-sized judge/adversary policies, 4-bit NF4 loading, gradient
checkpointing, batch size 2, and one judge/adversary update per iteration:

```bash
python3 -m aegis.pipelines.train \
  --config configs/experiment/gpu_4070_lora.yaml \
  --device cuda \
  --output_dir outputs/gpu_4070_lora

The profile is a real fine-tuning run (do not pass --mock). For larger models, create a local config and keep only one quantized policy resident or use a GPU with sufficient VRAM. bitsandbytes quantization is generally most reliable on Linux/WSL; the launcher falls back to a clear error rather than silently pretending to fine-tune.


### 4. Evaluating Models under Pressure
Evaluate baseline or AEGIS checkpoints across multi-turn adversarial horizons ($T = 1 \dots 5$):
```bash
# Using CLI script
bash scripts/run_eval.sh configs/experiment/math_gsm8k.yaml --device cuda --max_samples 100

# Or using Python pipeline directly
python3 src/aegis/pipelines/evaluate.py \
    --config configs/experiment/math_gsm8k.yaml \
    --device cuda \
    --max_samples 100 \
    --mock

5. Compiling the Academic Paper PDF

The paper "AEGIS: Adversarial Epistemic Guard for Invariant and Stable Judging in LLM-as-a-Judge" (17 pages, 20 vector figures, 12 tables) can be built locally via LaTeX:

cd paper
make clean && make
# Output PDF: paper/main.pdf

📁 Repository Structure

RL_AEGIS/
├── configs/                   # Experiment YAML profiles
│   ├── default.yaml           # Default hyperparameters & model settings
│   ├── judge_llama3.yaml      # Llama-3 Judge configuration
│   ├── adversary_mistral.yaml # Mistral-7B Adversary configuration
│   └── experiment/            # Domain profiles (math_gsm8k, toxicity, ai_text_detection)
├── src/aegis/                 # Core Framework Source
│   ├── configs/               # Strongly-typed Dataclasses & YAML Parser
│   ├── data/loaders/          # GSM8K, ToxiGen, HC3 data loaders
│   ├── environment/           # Multi-turn interaction loop, History & Verdict Extractor
│   ├── models/                # Judge, Adversary, EvidenceExtractor, NLI & Verifiers
│   ├── rewards/               # Epistemic Outcome States & Reward Composer
│   ├── training/              # MinimaxLoop, JudgeTrainer, PPOTrainer & Buffer
│   ├── evaluation/            # Metrics engine & Evaluator benchmark runner
│   ├── pipelines/             # Train & Evaluate CLI pipelines
│   └── utils/                 # Logging, Seed, Formatting, Device utilities
├── scripts/                   # Shell scripts for preprocessing & batch training
├── tests/                     # 33 Comprehensive unit and integration test suites
├── paper/                     # Publication-ready LaTeX manuscript
│   ├── main.tex               # Master LaTeX file
│   ├── preamble.tex           # Packages & theorem definitions
│   ├── macros.tex             # Mathematical symbols
│   ├── references.bib         # BibTeX citations
│   ├── Makefile               # Automated compilation
│   ├── sections/              # 12 Modular LaTeX sections
│   ├── tables/                # 12 Publication LaTeX tables
│   └── figures/               # 20 Standalone PDF charts & architecture diagrams
└── notebooks/                 # Data exploration & metrics analysis notebooks

🔬 The AEGIS Framework

                 ┌──────────────────────────────┐
                 │       Initial Input (x)      │
                 └──────────────┬───────────────┘
                                │
                                ▼
                 ┌──────────────────────────────┐
                 │         Judge Model          │◄─────────────┐
                 │   π_θ(r_t | x, h_{t-1}, u_t) │              │
                 └──────────────┬───────────────┘              │
                                │ r_t (verdict v_t)            │ pressure u_t
                                ▼                              │
                 ┌──────────────────────────────┐              │
                 │      Adversary Ensemble      │──────────────┘
                 │     π_ψ(u_t | x, h_{t-1})    │
                 └──────────────┬───────────────┘
                                │ u_t
                                ▼
                 ┌──────────────────────────────┐
                 │        Evidence Model        │
                 │      IE + NLI (τ = 0.8)      │
                 └──────────────┬───────────────┘
                                │ Novelty (Δe)
                                ▼
  ┌──────────────────────────────────────────────────────────┐
  │                 Epistemic Outcome States                 │
  │  Stable Correct (S)          Valid Correction (C_val)    │
  │  Hard Flip (H) [PENALTY]     Collapse (U) [PENALTY]      │
  │  Contradiction [PENALTY]     Counterfactual KL [PENALTY] │
  └─────────────────────────────┬────────────────────────────┘
                                │
                                ▼
  ┌──────────────────────────────────────────────────────────┐
  │           Alternating Minimax PPO Optimization           │
  │          max_{π_θ} min_{π_ψ}  E [ ∑_{t=1}^T R_t^J ]      │
  └──────────────────────────────────────────────────────────┘

📐 Mathematical Formulation

1. Extended Verdict Space

Let $\mathcal{X}$ be the space of input instances and $\mathcal{Y}$ the set of definite ground-truth labels. The judge outputs a verdict in the extended space: Y∗=Y∪{∅}\mathcal{Y}^* = \mathcal{Y} \cup \{\varnothing\} where $\varnothing$ represents abstention or non-committal hedging.

2. Evidence Validity

For an input $x$, let $e(x) = \mathrm{IE}(x) \subset \mathcal{F}$ be the extracted verifiable atomic propositions. For adversary pushback $u_t$:

  • Valid Evidence-Based Pressure: $e_{\text{new}}(x, u_t) \ne e(x)$ (introduces new verifiable factual claims).
  • Non-Evidential Pressure: $e_{\text{new}}(x, u_t) = e(x)$ (relies on tone, authority, or consensus rhetoric).

3. Epistemic Outcome States Taxonomy

Outcome State Symbol Formal Definition Desirable? Reward Weight
Stable Correct $S_t$ $v_{t-1} = y \land v_t = y$ ✅ Yes $+\alpha_2$
Valid Correction $C_{\text{val},t}$ $v_{t-1} \ne y \land v_{t-1} \in \mathcal{Y} \land v_t = y \land e_t \ne e_{t-1}$ ✅ Yes $+\alpha_3$
Reflective Correction $C_{\text{reflect},t}$ $v_{t-1} \ne y \land v_{t-1} \in \mathcal{Y} \land v_t = y \land e_t = e_{t-1}$ ✅ Yes $+\alpha_4$
Recovery from Abstention $R_{\varnothing,t}$ $v_{t-1} = \varnothing \land v_t = y$ ✅ Yes $+\alpha_5$
Destructive Hard Flip $H_t$ $v_{t-1} = y \land v_t \in \mathcal{Y}\setminus{y}$ ❌ No $-\beta_1$
Collapse to Uncertainty $U_t$ $v_{t-1} = y \land v_t = \varnothing$ ❌ No $-\beta_2$
Persistent Error $W_t$ $v_{t-1} \ne y \land v_t \ne y \land v_{t-1}, v_t \ne \varnothing$ ❌ No $-\beta_3$
Persistent Abstention $P_{\varnothing,t}$ $v_{t-1} = \varnothing \land v_t = \varnothing$ ❌ No $-\beta_4$
Wrong from Abstention $W_{\varnothing,t}$ $v_{t-1} = \varnothing \land v_t \ne y \land v_t \ne \varnothing$ ❌ No $-\beta_5$

4. Reward Objectives

Judge Reward ($R_t^J$):

RtJ=α11[vt=y]+α2St+α3Cval,t+α4Creflect,t+α5R∅,t−β1Ht−β2Ut−β3Wt−β4P∅,t−β5W∅,t−β6Contr(rt−1,rt)+β7Verif(rt,vt)−λKL1[et=et−1]KL(πθ(⋅∣ht−1,ut)∥πref(⋅∣ht−1,∅))+ηVext(x,vt) R_t^J = \alpha_1 \mathbf{1}[v_t = y] + \alpha_2 S_t + \alpha_3 C_{\text{val},t} + \alpha_4 C_{\text{reflect},t} + \alpha_5 R_{\varnothing,t} - \beta_1 H_t - \beta_2 U_t - \beta_3 W_t - \beta_4 P_{\varnothing,t} - \beta_5 W_{\varnothing,t} - \beta_6 \mathrm{Contr}(r_{t-1}, r_t) + \beta_7 \mathrm{Verif}(r_t, v_t) - \lambda_{\text{KL}} \mathbf{1}[e_t = e_{t-1}] \mathrm{KL}\left(\pi_\theta(\cdot \mid h_{t-1}, u_t) \parallel \pi_{\text{ref}}(\cdot \mid h_{t-1}, \varnothing)\right) + \eta V_{\text{ext}}(x, v_t)

Adversary Reward ($R_t^A$):

RtA=γ1Ht+γ2Ut−γ3St−γ4Cval,t−γ5R∅,t−γ61[et≠et−1]−λfluencyKL(πψ(⋅∣ht−1)∥πbase(⋅∣ht−1)) R_t^A = \gamma_1 H_t + \gamma_2 U_t - \gamma_3 S_t - \gamma_4 C_{\text{val},t} - \gamma_5 R_{\varnothing,t} - \gamma_6 \mathbf{1}[e_t \ne e_{t-1}] - \lambda_{\text{fluency}} \mathrm{KL}\left(\pi_\psi(\cdot \mid h_{t-1}) \parallel \pi_{\text{base}}(\cdot \mid h_{t-1})\right)

Minimax Optimization Game:

max⁡πθmin⁡πψE(x,y)∼D,r∼πθ,u∼πψ[∑t=1TRtJ] \max_{\pi_\theta} \min_{\pi_\psi} \mathbb{E}_{(x, y) \sim \mathcal{D}, r \sim \pi_\theta, u \sim \pi_\psi} \left[ \sum_{t=1}^T R_t^J \right]


📊 Benchmark Results ($T=3$ Multi-Turn Horizon)

Method Accuracy (↑) Stable Correct (↑) Hard Flip (↓) Collapse (↓) Non-Evidential Flip (↓) Contradiction (↓) Evidence Sens. (↑)
Zero-Shot Judge 71.4% 41.2% 38.6% 20.2% 58.8% 0.42 0.12
Few-Shot CoT 74.8% 46.5% 34.2% 19.3% 53.5% 0.38 0.19
Self-Consistency (k=5) 76.1% 51.0% 31.4% 17.6% 49.0% 0.34 0.21
Self-Refine 73.2% 44.8% 36.1% 19.1% 55.2% 0.39 0.24
Constitutional AI 75.3% 53.4% 28.9% 17.7% 46.6% 0.31 0.28
AI Safety Debate 77.0% 56.2% 26.5% 17.3% 43.8% 0.28 0.35
Standard PPO (Accuracy) 78.2% 57.9% 25.1% 17.0% 42.1% 0.29 0.31
DPO 78.6% 59.4% 23.8% 16.8% 40.6% 0.26 0.33
AEGIS (Ours) 83.9% 78.4% 8.2% 5.4% 13.6% 0.09 0.69

🖥️ Run the interactive site locally

The frontend is an independent Vite application and does not require Python or model weights for the educational experience.

cd aegis-ui
npm ci
npm run dev

Open the local URL printed by Vite, then explore:

  • #/learn — guided four-step lesson and interaction map;
  • #/demo — animated judge/adversary/evidence trajectory;
  • #/dashboard — metrics, training dynamics, transition matrix, and ablations;
  • #/dataset — searchable AEGIS-Debate trajectories;
  • #/docs — API reference and full paper companion;
  • #/methodology — equations rendered with native MathML.

For a backend-connected demo, copy .env.example to .env and set:

VITE_API_BASE_URL=http://127.0.0.1:8000

Then run the API in another terminal:

python3 -m venv .venv
source .venv/bin/activate
pip install -r backend/requirements.txt
uvicorn backend.app.main:app --reload --port 8000

The API is intentionally mock-compatible today. The inference adapter is isolated in backend/app/models.py, so a Transformers, vLLM, or remote-serving implementation can be substituted without changing the frontend contract.

🧪 Validation commands

Run the same checks used for the repository review:

# Research Python suite (33 tests)
python3 -m pytest

# Backend contract tests
python3 -m pytest backend/tests/test_api.py

# Frontend type-check and production bundle
cd aegis-ui
npx tsc -p tsconfig.app.json --noEmit
npm run build

# Rebuild the manuscript
cd ../paper
latexmk -pdf -interaction=nonstopmode -halt-on-error main.tex

The LaTeX build may report box warnings for dense conference tables; these are layout warnings, not compilation failures. Before submission, inspect the generated PDF visually and resolve any overfull equations or tables.

⚖️ Comparable training modes and linear work budget

The training entry point exposes matched-budget controls so baselines can be compared without silently changing the number of episodes or adversarial turns:

# Full alternating AEGIS game
python3 -m aegis.pipelines.train --config configs/experiment/math_gsm8k.yaml \
  --training_mode minimax --total_iterations 100 --batch_size 16 --horizon 3 --mock

# Judge-only control: adversary remains fixed
python3 -m aegis.pipelines.train --config configs/experiment/math_gsm8k.yaml \
  --training_mode judge_only --total_iterations 100 --batch_size 16 --horizon 3 --mock

# Adversary-only control: judge remains fixed
python3 -m aegis.pipelines.train --config configs/experiment/math_gsm8k.yaml \
  --training_mode adversary_only --total_iterations 100 --batch_size 16 --horizon 3 --mock

For a fair comparison, keep seed, total_iterations, batch_size, horizon, max_train_samples, model/token budgets, evaluation sample count, and checkpoint cadence fixed. The environment-transition budget is:

episodes = iterations × (judge_updates + adversary_updates) × batch
steps    = episodes × horizon

With fixed update counts, this is linear in the number of iterations, sampled episodes, and interaction horizon: O(iterations × updates × batch × horizon). Wall-clock time also depends on sequence length, tokenizer throughput, device, batching, and model implementation; the framework reports the transition estimate but does not pretend those hardware-dependent factors are constant.

🧭 Reproducibility checklist

For every reported number, record the dataset revision, domain, judge/adversary checkpoints, random seed, pressure style, pressure strength, horizon T, evidence-model version, and whether the result came from mock or live inference. Export trajectory-level JSON/CSV artifacts rather than reporting only aggregate scores. The paper’s appendix and docs/data.md describe the expected record format.

📖 Citation

If you use the AEGIS codebase or the AEGIS-Debate benchmark in your research, please cite:

@article{majlesi2026aegis,
  title={AEGIS: Adversarial Epistemic Guard for Invariant and Stable Judging in LLM-as-a-Judge},
  author={Majlesi, Taha and AEGIS Research Team},
  journal={arXiv preprint arXiv:2608.12645},
  year={2026}
}

📄 License

This repository is licensed under the MIT License.

Total size
142 MB
Files
21,636
Last updated
Sep 4
Pre-warmed CDN
US EU US EU

Contributors