Spaces:
Sleeping
Sleeping
Deploy degeneration-probe Gradio Space (Qwen-0.5B demo)
Browse filesFiles changed (25)
- README.md+398-6
- app.pyAdded+65
- requirements.txtAdded+23
- src/degeneration_probe/__init__.pyAdded+1
- src/degeneration_probe/__main__.pyAdded+202
- src/degeneration_probe/_feature_probes_path.pyAdded+26
- src/degeneration_probe/config.pyAdded+136
- src/degeneration_probe/model_utils.pyAdded+89
- src/degeneration_probe/probe/__init__.pyAdded+5
- src/degeneration_probe/probe/data_loader.pyAdded+309
- src/degeneration_probe/probe/evaluate.pyAdded+183
- src/degeneration_probe/probe/loader.pyAdded+71
- src/degeneration_probe/probe/train.pyAdded+574
- src/degeneration_probe/server/__init__.pyAdded
- src/degeneration_probe/server/app.pyAdded+38
- src/degeneration_probe/server/database.pyAdded+109
- src/degeneration_probe/server/routes_sessions.pyAdded+38
- src/degeneration_probe/server/ws_generate.pyAdded+115
- src/degeneration_probe/ui/__init__.pyAdded
- src/degeneration_probe/ui/app.pyAdded+1465
- src/degeneration_probe/ui/dataset_stats.jsonAdded+62
- src/degeneration_probe/worker/__init__.pyAdded
- src/degeneration_probe/worker/engine.pyAdded+210
- src/degeneration_probe/worker/serve.pyAdded+267
- src/degeneration_probe/worker/steering.pyAdded+54
12345678910111213---title: Degeneration Probeemoji: ⚡colorFrom: graycolorTo: greensdk: gradiosdk_version: 6.15.2python_version: '3.13'app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405---title: Degeneration Probeemoji: 🔬colorFrom: bluecolorTo: purplesdk: gradiosdk_version: 6.11.0app_file: app.pypinned: false---# degeneration-probeA research pipeline for training a **degeneration probe** — a small head on top of a frozen LLM that predicts, from internal hidden states, how repetitive the next 256 tokens of generation are about to be. It forecasts collapse (the model getting stuck in a loop) one window ahead, so a worker can intervene before the loop locks in.> **🤗 Try it online → [degeneration-probe Space](https://huggingface.co/spaces/mo378/degeneration-probe)** — runs Qwen-0.5B-Instruct with no setup. For the full Apertus-8B demo with a trained probe, see [Cluster (CSCS Clariden)](#cluster-cscs-clariden).The repo has two tracks that share one codebase and one CLI (`python -m degeneration_probe …`):- **Data pipeline:** train a probe on the per-token 1 − TTR signal from a HuggingFace dataset of LLM completions → evaluate on a held-out split.- **Interactive UI:** a backend + worker + Gradio UI that streams tokens from a live model, colours each one by probe score, and can steer the model out of degenerate loops.## Contents- [Setup](#setup)- [Try the demo (one command)](#try-the-demo-one-command)- [Building a probe](#building-a-probe)- [Train on the aggregate HF dataset](#train-on-the-aggregate-hf-dataset)- [Evaluate a checkpoint](#evaluate-a-checkpoint)- [Creating your own configs](#creating-your-own-configs)- [Interactive UI](#interactive-ui)- [Quick start (local)](#quick-start-local)- [Using a trained probe](#using-a-trained-probe)- [Steering](#steering)- [Cluster (CSCS Clariden)](#cluster-cscs-clariden)- [One-shot UI launch](#one-shot-ui-launch)- [Submitting batch jobs](#submitting-batch-jobs)- [HuggingFace Spaces deployment](#huggingface-spaces-deployment)- [Troubleshooting](#troubleshooting)- [Reference](#reference)- [CLI commands](#cli-commands)- [API endpoints](#api-endpoints)- [Dataset schema](#dataset-schema)- [Metrics](#metrics)- [How the probe is trained](#how-the-probe-is-trained)---## Setup**Prerequisites**- Python 3.10–3.12- [uv](https://docs.astral.sh/uv/) (Python package manager)- A HuggingFace [access token](https://huggingface.co/settings/tokens). Request access on the HF page for whichever of these you need:- [`mo378/degeneration-probe-instruct-balanced`](https://huggingface.co/datasets/mo378/degeneration-probe-instruct-balanced) — the training dataset (private; needed if you want to train your own probe).- [`swiss-ai/Apertus-8B-Instruct-2509`](https://huggingface.co/swiss-ai/Apertus-8B-Instruct-2509) — the gated base model used by the demo probe and by Apertus generation/training (needed for *running* the demo or training on Apertus).- A GPU is recommended. Qwen-0.5B runs on CPU/MPS but is slow.**Install**```bashgit clone <repo-url>cd degeneration-probegit submodule update --init --recursive # vendors the swiss-ai/feature-probes submoduleuv sync# Save your HuggingFace token in .env (read by both local runs and cluster jobs).echo 'HF_TOKEN=hf_YOUR_TOKEN_HERE' >> .env```When running the CLI locally, source `.env` first (or add it to your shell rc):```bashset -a; source .env; set +a```The cluster sbatch scripts source `.env` automatically.---## Try the demo (one command)If you just want to see the probe in action without training anything: a pre-trained Apertus-8B-Instruct probe ships in [`demo_probe/`](demo_probe/) (4.8 MB). After the Setup steps above plus the [Cluster prerequisites](#one-shot-ui-launch) (cscs-key in your ssh-agent, `~/degeneration-probe` cloned on Clariden, `my_env` container set up), run:```bashPROBE=demo_probe ./cluster/start.sh```That's it. ~3–5 min later the script prints `UI: http://localhost:7860`. Tear down with `./cluster/stop.sh`.---## Building a probeThe probe is a per-token regressor: it predicts `1 − TTR` over a forward sliding window of 256 tokens, given the model's hidden state at one specific layer. Training adds a LoRA adapter on layers `0..probe_layer` of an otherwise frozen LLM, plus a single-output linear head.### Train on the aggregate HF datasetTwo ready-to-go configs in `configs/train/`:| Config | Model | Probe layer | LoRA layer(s) | Where to run ||---|---|---|---|---|| `qwen05b_hf.yaml` | Qwen-0.5B base | 12 | 0..12 | local (CPU/MPS) **or** cluster || `apertus8b_hf.yaml` | Apertus-8B-Instruct | 31 (last) | [16] | cluster only (~16 GB GPU) |Both pull from `mo378/degeneration-probe-instruct-balanced` — a per-source 50/50 balanced subset (~1.8k train / 230 validation rows) of Apertus-8B-Instruct completions on prompts from Llama-Nemotron, Numinamath, Medical-O1, IF-SFT, and Deepmath.```bashuv run python -m degeneration_probe train --config configs/train/qwen05b_hf.yaml```Both configs default to `max_train_rows: null` / `max_eval_rows: null` (use the full ~1.8k/230-row balanced split). Set them to integers to subsample.Output (e.g. `outputs/probes/20260428_175939/`):| File | What ||---|---|| `checkpoint/probe_head.bin` | Trained value head (linear, hidden → 1) || `checkpoint/adapter_model.safetensors` | LoRA weights || `checkpoint/adapter_config.json` | PEFT config || `checkpoint/probe_config.json` | Layer index, hidden size || `config.json` | Full training-config snapshot (model name, window params, ttr_threshold, etc.) — the single source of truth that `evaluate` and the worker read || `summary.json` | Timing, device fingerprint, per-epoch metrics |Key knobs:- `probe.layer` — which transformer layer to read (12 = middle of Qwen-0.5B's 24; 16 = middle of Apertus-8B's 32).- `probe.lora.{rank,alpha,dropout}` — LoRA adapter shape.- `probe.lora.layers` — explicit list of layer indices to attach LoRA to. Defaults to `0..probe.layer` inclusive when omitted. For Apertus-8B the LoRA-layer sweep found a clear mid-stack peak at `[16]` (see `docs/reports/lora_layer_sweep.tex`); pinning LoRA at the probe layer itself (`[probe.layer]`) is the worst single-layer setting.- `label.{window_size,primary_n}` — forward sliding-window size (256) and TTR n-gram size (2 = bigrams) for the per-token target.- `learning_rate.{head,lora}` — separate LRs for the value head vs LoRA params.- `model.name` — the model whose hidden states you're probing. Required.- `hf_dataset.name`, `hf_dataset.train_split`, `hf_dataset.eval_split` — HuggingFace Hub dataset and which splits to use. `hf_dataset.max_train_rows` / `max_eval_rows` cap the number of rows; `train_positive_fraction` / `eval_positive_fraction` rebalance to a target positive ratio.- `num_epochs`, `batch_size`, `max_length`, `seed` — standard.- `gradient_checkpointing` (default `false` in `TrainConfig`) — trades ~25% step time for ~40-50% activation memory savings; turn on if you need larger batches on Apertus-8B than the default fits.### Evaluate a checkpoint```bashuv run python -m degeneration_probe evaluate \--checkpoint outputs/probes/20260512_000422/checkpoint \--hf-dataset luca-sartori/degeneration-probe-instruct \--hf-split test```Reports MSE, MAE, Pearson correlation, and the full feature-probes classification suite (accuracy, precision, recall, F1, AUC, optimal_threshold, recall_at_0.1_fpr, TP/TN/FP/FN). The model name and window params are read from the run's `config.json` (sitting one level above the checkpoint dir) automatically; pass `--model_name` to override.Other flags: `--hf-max-rows N` (default: full split), `--batch_size N` (default 4), `--max_length N` (default 2048), `--output_dir PATH` and `--output_filename NAME` to control where the metrics JSON is written.### Creating your own configsCopy an existing training config and edit:```bashcp configs/train/qwen05b_hf.yaml configs/train/my_training.yaml```For local-only configs you don't want committed, name the file `*.local.yaml` — `configs/*.local.yaml` is gitignored automatically.---## Interactive UIThe UI streams tokens from a live model and colours each one by its probe score (green → safe, amber → borderline, red → degenerate). It has two tabs — **Probe** (the live generation surface with a real-time score chart, generation/steering sliders, and a temperature trace) and **About Degeneration** (a self-contained explainer covering what degeneration is, why it happens, a concrete chat example, the sliding-window TTR labeling method, and interactive dataset-statistics charts). It runs as three independent processes:| Component | Command | Default port | Purpose ||---|---|---|---|| Backend | `python -m degeneration_probe serve` | 8000 | FastAPI: REST + WebSocket relay || Worker | `python -m degeneration_probe worker --model …` | 9000 | Loads the LLM + probe; emits tokens || UI | `python -m degeneration_probe ui` | 7860 | Gradio web interface |The UI talks to the backend on `localhost:8000`; the backend forwards generation requests to the worker on `localhost:9000` (which can be local or an SSH tunnel to a cluster node).### Quick start (local)Three terminals:```bash# Tab 1: backenduv run python -m degeneration_probe serve# Tab 2: worker (small CPU/MPS-friendly model)uv run python -m degeneration_probe worker --model Qwen/Qwen2.5-0.5B-Instruct --dtype float32# Tab 3: UIuv run python -m degeneration_probe ui```Open **http://localhost:7860**. The UI auto-connects to the local worker on startup.### Using a trained probePass a checkpoint dir to the worker — `--model` becomes optional because the worker reads it from the run's `config.json` (one level above the checkpoint dir):```bashuv run python -m degeneration_probe worker \--probe outputs/probes/20260428_175939/checkpoint \--dtype float32```If you also pass `--model`, it must match the probe's trained model — the worker errors out at startup otherwise (loading a probe on a different base produces meaningless scores). The UI then colours each emitted token by the probe's predicted score.A pre-trained checkpoint for **Apertus-8B-Instruct-2509** ships in [`demo_probe/`](demo_probe/) (~4.8 MB). For the cluster-backed UI launcher see [Try the demo (one command)](#try-the-demo-one-command); for a local worker (only viable on a beefy GPU since the base model is 8B):```bashuv run python -m degeneration_probe worker --probe demo_probe --dtype bfloat16```### SteeringToggle steering in the UI sidebar. When the probe score crosses the threshold, the active strategy modifies the model's output distribution to break out of repetition.Available strategies:- **Temperature Boost** — divides logits by a higher temperature when degeneration is detected, increasing diversity.---## Cluster (CSCS Clariden)### One-shot UI launchFor demoing Apertus-8B (or any cluster-only model) with a local UI, the repo ships a launcher that submits the worker job, opens the SSH tunnel, and starts the local backend + UI.**Prerequisites** (one-time, per machine)- SSH access to Clariden — load the cscs cert into your agent: `ssh-add -t 1d ~/.ssh/cscs-key`.- The repo cloned at `~/degeneration-probe` on Clariden (`start.sh` hard-resets it to `origin/main` by default — override with `BRANCH=feat/foo ./cluster/start.sh`).- A container environment `my_env` set up in `~/.edf/` on Clariden.- *Optional*: for agent-forwarded git on Clariden, also load your GitHub key and publish the agent socket: `ssh-add ~/.ssh/id_ed25519 && launchctl setenv SSH_AUTH_SOCK "$SSH_AUTH_SOCK"`.**Launch**```bash# default: bare Apertus-8B base model on the debug partition (1 h cap)./cluster/start.sh# the demo probe (auto-resolves to Apertus-8B-Instruct-2509)PROBE=demo_probe ./cluster/start.sh# any other model, no probeMODEL=Qwen/Qwen2.5-7B-Instruct PARTITION=normal TIME=04:00:00 ./cluster/start.sh# a probe you trained yourselfPROBE=outputs/probes/20260429_001809/checkpoint ./cluster/start.sh```Available env vars: `MODEL`, `PROBE`, `PARTITION`, `TIME`, `WORKER_PORT`, `BACKEND_PORT`, `UI_PORT`, `SSH_HOST`. When `PROBE` is set, `MODEL` is optional (and must match the probe's trained model if supplied).The script prints `UI: http://localhost:7860` once the stack is up (~3–5 min). Runtime state (PIDs, job ID, logs) lives in `.run/`.**Tear down**```bash./cluster/stop.sh```Kills local processes, closes the tunnel, and cancels the SLURM job.### Submitting batch jobsFor training and bulk generation jobs (no interactive UI), use the dedicated sbatch scripts directly on Clariden:```bashssh claridencd ~/degeneration-probe# Train a probe (the heavy one — Apertus-8B on the full HF dataset takes hours)sbatch cluster/clariden_train.sh configs/train/apertus8b_hf.yaml# Re-evaluate a manifest of saved checkpoints against an HF split (one array task per checkpoint)N=$(grep -cv '^\s*\(#\|$\)' cluster/reeval_manifests/pre_feature_probes_migration.txt)sbatch --array=1-${N}%4 cluster/clariden_reeval_array.sh \cluster/reeval_manifests/pre_feature_probes_migration.txt```Logs land in `/iopsstor/scratch/cscs/$USER/logs/degen_train_<jobid>.{out,err}` for the train job, and `degen_reeval_<jobid>_<taskid>.{out,err}` (one pair per array task) for the re-eval job. Probe outputs land in `~/degeneration-probe/outputs/probes/`.The sbatch scripts source `.env` so `HF_TOKEN` is available to gated dataset / model downloads.---## HuggingFace Spaces deploymentThe repo is ready to deploy as a HuggingFace Space (Gradio SDK). The pieces are already in place:| File | Purpose ||---|---|| `app.py` | Space entrypoint — inits the git submodule, starts the FastAPI backend + inference worker as background threads, then launches the Gradio UI on port 7860. || `requirements.txt` | pip-installable dependency list the Space builder reads. || `README.md` | The YAML frontmatter at the top (`sdk: gradio`, `app_file: app.py`, `sdk_version`) is what HF reads to configure the Space. || `src/degeneration_probe/ui/dataset_stats.json` | Pre-computed dataset statistics committed into the repo so the About tab's charts render without an HF token. |**Deploy to your own Space:**```bash# Create a Space at huggingface.co/new-space (Gradio SDK; pick a GPU if available),# then push this repo to it:git remote add space https://huggingface.co/spaces/<your-username>/degeneration-probegit push space feat/integrate-viz-site:main```The Space installs `requirements.txt`, runs `app.py`, and serves the UI on Qwen-0.5B.**Notes:**- The Space defaults to **Qwen-0.5B-Instruct** (public, no token). The Apertus-8B demo needs the CSCS cluster and is not available on Spaces.- The submodule `third_party/hallucination_probes` must be publicly cloneable for `app.py`'s startup `git submodule update` to succeed.- On a CPU-only Space the model load is slow (~30–60 s); a small GPU Space is recommended.- This repo uses **Git LFS** for the activation dumps; if your Space pulls them, ensure LFS is enabled (or keep those paths out of the Space — they aren't needed at runtime).---## Troubleshooting**`error: runtime state exists in .run/. Run ./cluster/stop.sh first.`**A previous launch left stale state. `./cluster/stop.sh` cleans it up. If `stop.sh` itself complains about a missing PID, the processes are already dead — `rm .run/*.pid .run/jobid` and try again.**`ssh clariden` says "Permission denied (publickey)" or just hangs at `ssh -W [clariden]:22 cscs-ela`.**Your cscs-key isn't loaded into the agent (or its 24-hour `-t 1d` lifetime expired). Re-add: `ssh-add -t 1d ~/.ssh/cscs-key`.**`gh` / git commands inside Clariden fail with "Permission denied (publickey)".**Agent forwarding has nothing to forward — your local ssh-agent isn't reachable. In your terminal: `eval "$(ssh-agent -s)" && ssh-add ~/.ssh/id_ed25519` and (on macOS) publish the socket so non-interactive shells inherit it: `launchctl setenv SSH_AUTH_SOCK "$SSH_AUTH_SOCK"`.**HF download fails with 401 / 403.**Either `HF_TOKEN` isn't in `.env`, or your account hasn't been granted access to a gated repo. Check `huggingface-cli whoami` (must show your username) and visit the dataset/model page on huggingface.co to request access. After approval, downloads work immediately — no retry delay.**Worker errors out with `--model X disagrees with the probe's trained model Y`.**The run's `config.json` (sitting one level above the checkpoint dir) records which model the probe was trained on. The worker refuses to load a probe on a different base because the scores would be meaningless. Drop your `--model` flag, or pass the matching one.**`UI: http://localhost:7860` printed but the page is unreachable.**The Gradio process is binding to `0.0.0.0` — try the URL in a fresh tab. If still empty, check `tail .run/logs/ui.log` for an import error or port collision. Default port 7860 conflicts with other Gradio apps; override with `UI_PORT=7861 ./cluster/start.sh`.---## Reference### ScriptsOne-off utilities in `scripts/` for dataset analysis and the activation visualizations behind the About tab and standalone HTML pages. The heavy plotting libraries they need (matplotlib, bokeh, umap-learn) are an optional install: `uv sync --extra viz`.| Script(s) | Purpose ||---|---|| `compute_dataset_stats.py` | Computes per-source-dataset statistics and writes `src/degeneration_probe/ui/dataset_stats.json`, consumed by the About-tab charts. Requires `HF_TOKEN`. || `compute_pca_activations.py`, `compute_pca_3d.py`, `compute_tsne_umap.py` | Project captured per-layer hidden states into 2D/3D for the embedding plots. || `parallel_coords_*.py`, `interactive_pca*.py`, `pca_*.py`, `trajectory_lora.py`, `make_token_plot.py`, `export_ply.py` | Render the interactive Plotly/Bokeh HTML and `.ply` point clouds under `saved_activation_states/`. || `analyze_degeneration_types.py`, `pick_best_examples.py` | Surface representative degeneration examples (feed `degeneration_examples.md` / `degeneration_best_examples.md`). |Large binary inputs/outputs (`.npz` activation dumps, `.ply` point clouds, viz PNGs) are tracked via **Git LFS** — `git lfs install` once, then a normal clone fetches them.### CLI commandsAll routed through `python -m degeneration_probe`:| Command | Purpose ||---|---|| `train` | Train a probe head + LoRA adapter from a HuggingFace dataset. || `evaluate` | Evaluate a saved probe checkpoint on a HuggingFace dataset split (regression metrics + full feature-probes classification suite). || `serve` | Start the FastAPI backend (default `0.0.0.0:8000`). || `worker` | Start the inference worker (default `0.0.0.0:9000`). || `ui` | Start the Gradio UI (default `0.0.0.0:7860`). |### API endpointsThe backend exposes:| Method | Path | Purpose ||---|---|---|| `POST` | `/api/sessions` | Register the active worker — body: `{"worker_host": "...", "worker_port": 9000}` || `GET` | `/api/worker/info` | Ask the active worker which model it's serving || `WS` | `/api/generate` | Streaming generation — relayed by the backend to the worker |### Dataset schemaEach HF row provides `prompt` + `generated_text` (the completion the probe will read) plus the row-level `degenerating: bool` flag used for balanced batch sampling:```json{"prompt_id": "tatsu-lab_alpaca-train-0","prompt": "Give three tips for staying healthy.","source_dataset": "tatsu-lab/alpaca","model_name": "Qwen/Qwen2.5-0.5B-Instruct","generated_text": "1. Eat a balanced diet...","degenerating": false}````degenerating: true` indicates the completion contains a degenerate region by the source dataset's definition (e.g. unigram `max_repetition > 0.9` over some 256-token chunk). The per-token training target is computed independently from raw token TTR over a sliding window, but the row flag is used at the **row** level for stratified batch sampling (each batch holds equal numbers of `degenerating=true` and `degenerating=false` rows).### Metrics- **TTR (type-token ratio):** `unique_ngrams / total_ngrams`. 1.0 = fully diverse, 0.0 = fully repetitive.- **Repetition:** `1 − TTR`.- During probe training, the per-token target is `1 − TTR` over a **forward sliding window** of `window_size` tokens (default 256, n=2 — bigrams capture phrase-level repetition more cleanly than unigrams, which would penalise common words like "the"/"is"). Tokens within the last window of a completion get no target (masked out of the loss).### How the probe is trained1. Load the base LLM frozen — no gradient updates flow to its original weights.2. Attach a LoRA adapter (PEFT) to the layers in `probe.lora.layers` (defaults to `0..probe_layer` when unset) so the model can adapt its hidden states for the probing task without touching the rest.3. Attach a forward hook at `probe_layer`: every token's hidden state passes through a single `nn.Linear(hidden_size, 1)` — the value head.4. Compute the per-token target on-the-fly during collation: tokenise the completion, then for each position `t` set `target[t] = 1 − TTR(tokens[t:t+window_size])`. Mask positions where the window doesn't fit. When `label.ttr_threshold` is set, the target becomes binary (`1 iff TTR ≤ threshold`) and `label.smoothing: true` switches it to the fraction of overlapping windows whose TTR is below threshold.5. Optimise either masked-MSE on `sigmoid(probe_logit)` (regression mode) or masked BCE-with-logits (when `ttr_threshold` is set), with two AdamW parameter groups (head LR, LoRA LR). Batches are row-level balanced 50/50 between `degenerating=true` and `degenerating=false` rows when the dataset exposes that label. Gradient checkpointing is enabled by default.6. Per-epoch eval reports MSE, MAE, Pearson correlation, and the full feature-probes classification suite (accuracy, precision, recall, F1, AUC, optimal_threshold, threshold_optimized_accuracy, recall_at_0.1_fpr, TP/TN/FP/FN), plus a per-epoch checkpoint dumped under `outputs/probes/<ts>/checkpoint_epoch_<N>/`.The training loop lives in our package at `src/degeneration_probe/probe/train.py`; `swiss-ai/feature-probes` is consumed as a pinned submodule (`third_party/feature_probes/`) for `ValueHeadProbe`, LoRA setup, model utilities, and the classification metric suite. `cmd_train` translates our YAML config into `TrainConfig` and calls `train()` directly.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465"""HuggingFace Spaces entrypoint.
Starts the FastAPI backend and inference worker as background threads,then launches the Gradio UI on port 7860 (the default Spaces port)."""from __future__ import annotations
import osimport subprocessimport sysimport threadingimport timefrom pathlib import Path
# ── Make the src/-layout package importable without an editable install ───────# Needed on HF Spaces (which only `pip install -r requirements.txt`): put src/# on sys.path for this process AND, via PYTHONPATH, for the# `python -m degeneration_probe` subprocesses spawned below._SRC = str(Path(__file__).resolve().parent / "src")sys.path.insert(0, _SRC)os.environ["PYTHONPATH"] = _SRC + os.pathsep + os.environ.get("PYTHONPATH", "")
# ── Init git submodule (third_party/feature_probes) ───────────────────────────subprocess.run( ["git", "submodule", "update", "--init", "--recursive"], check=False, capture_output=True,)
# ── Runtime data dir (SQLite lives here, not version-controlled) ──────────────Path("data").mkdir(exist_ok=True)
def _start_backend() -> None: subprocess.run([ sys.executable, "-m", "degeneration_probe", "serve", "--host", "127.0.0.1", "--port", "8000", "--db-path", "data/degeneration_probe.db", ])
def _start_worker() -> None: subprocess.run([ sys.executable, "-m", "degeneration_probe", "worker", "--model", "Qwen/Qwen2.5-0.5B-Instruct", "--host", "127.0.0.1", "--port", "9000", ])
# Start backend first, give it a few seconds, then start workerthreading.Thread(target=_start_backend, daemon=True).start()time.sleep(4)threading.Thread(target=_start_worker, daemon=True).start()
# Give the worker time to download and load the model on first run# (Qwen-0.5B is ~1 GB; on a cold Space this can take 30–60 s)time.sleep(20)
# ── Gradio UI ─────────────────────────────────────────────────────────────────from degeneration_probe.ui.app import build_ui, CSS # noqa: E402
demo = build_ui()demo.launch(css=CSS)1234567891011121314151617181920212223# Core MLtorch>=2.4.0transformers>=4.56.0peft>=0.10.0accelerate>=0.20.0datasets>=2.0.0
# Web / APIfastapi>=0.115.0uvicorn[standard]>=0.30.0aiosqlite>=0.20.0websockets>=13.0websocket-client>=1.6.0
# UIgradio>=6.0.0plotly>=6.0.0
# Utilitiespyyaml>=6.0scikit-learn>=1.3.0jaxtyping>=0.3.7termcolor>=3.3.01"""degeneration_probe: pipeline for measuring LLM text degeneration via n-gram TTR."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202"""Unified CLI: python -m degeneration_probe {train,evaluate,serve,worker,ui}."""
from __future__ import annotations
import argparseimport jsonimport loggingimport sysfrom pathlib import Path
log = logging.getLogger(__name__)
from degeneration_probe._feature_probes_path import ensure_feature_probes_on_syspath
# ---------------------------------------------------------------------------# train# ---------------------------------------------------------------------------
def cmd_train(args: argparse.Namespace) -> None: from degeneration_probe.config import load_training_config
ensure_feature_probes_on_syspath() from degeneration_probe.probe.train import TrainConfig, train
cfg = load_training_config(Path(args.config)) if cfg.hf_dataset is None: raise SystemExit("Error: 'hf_dataset' is required in the training config.") if cfg.model is None: raise SystemExit( "Error: 'model.name' must be set explicitly in the training config." )
train_cfg = TrainConfig( model_name=cfg.model.name, layer=cfg.probe.layer, lora_enabled=cfg.probe.lora.enabled, lora_rank=cfg.probe.lora.rank, lora_alpha=cfg.probe.lora.alpha, lora_dropout=cfg.probe.lora.dropout, lora_layers=list(cfg.probe.lora.layers) if cfg.probe.lora.layers else None, hf_dataset=cfg.hf_dataset.name, hf_train_split=cfg.hf_dataset.train_split, hf_eval_split=cfg.hf_dataset.eval_split, hf_max_train_rows=cfg.hf_dataset.max_train_rows, hf_max_eval_rows=cfg.hf_dataset.max_eval_rows, hf_train_positive_fraction=cfg.hf_dataset.train_positive_fraction, hf_eval_positive_fraction=cfg.hf_dataset.eval_positive_fraction, hf_positive_label_field=cfg.hf_dataset.positive_label_field, eval_fraction=cfg.eval_fraction, max_length=cfg.max_length, window_size=cfg.label.window_size, primary_n=cfg.label.primary_n, ttr_threshold=cfg.label.ttr_threshold, head_lr=cfg.learning_rate.head, lora_lr=cfg.learning_rate.lora, batch_size=cfg.batch_size, num_epochs=cfg.num_epochs, seed=cfg.seed, output_dir=cfg.output_dir, wandb_project=cfg.wandb_project, wandb_entity=cfg.wandb_entity, wandb_run_name=cfg.wandb_run_name, ) ckpt = train(train_cfg) print(f"Probe saved to {ckpt}")
# ---------------------------------------------------------------------------# evaluate# ---------------------------------------------------------------------------
def cmd_evaluate(args: argparse.Namespace) -> None: ensure_feature_probes_on_syspath() from degeneration_probe.probe.evaluate import evaluate_checkpoint
metrics = evaluate_checkpoint( checkpoint_dir=args.checkpoint, hf_dataset=args.hf_dataset, hf_split=args.hf_split, hf_max_rows=args.hf_max_rows, batch_size=args.batch_size, max_length=args.max_length, output_dir=args.output_dir, output_filename=args.output_filename, model_name=args.model_name, ) print(json.dumps(metrics, indent=2))
# ---------------------------------------------------------------------------# serve / worker / ui# ---------------------------------------------------------------------------
def cmd_serve(args: argparse.Namespace) -> None: """Start the FastAPI backend server.""" import uvicorn from degeneration_probe.server.app import create_app
app = create_app(db_path=args.db_path) uvicorn.run(app, host=args.host, port=args.port)
def cmd_worker(args: argparse.Namespace) -> None: """Start the inference worker.""" # The worker imports from feature-probes at load time; make it importable. ensure_feature_probes_on_syspath() from degeneration_probe.worker.serve import main as worker_main sys.argv = ["worker", "--host", args.host, "--port", str(args.port)] if args.model: sys.argv.extend(["--model", args.model]) if args.probe: sys.argv.extend(["--probe", args.probe]) if args.dtype: sys.argv.extend(["--dtype", args.dtype]) worker_main()
def cmd_ui(args: argparse.Namespace) -> None: """Start the Gradio UI.""" from degeneration_probe.ui.app import build_ui demo = build_ui() demo.launch(server_name=args.host, server_port=args.port)
# ---------------------------------------------------------------------------# CLI# ---------------------------------------------------------------------------
def main() -> None: logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
parser = argparse.ArgumentParser( prog="degeneration_probe", description="Degeneration probe research pipeline.", ) subparsers = parser.add_subparsers(dest="command", required=True)
# train p_train = subparsers.add_parser("train", help="Train a degeneration probe") p_train.add_argument("--config", required=True, help="Path to training YAML config") p_train.set_defaults(func=cmd_train)
# evaluate p_eval = subparsers.add_parser("evaluate", help="Evaluate a saved probe checkpoint") p_eval.add_argument("--checkpoint", required=True, help="Path to probe checkpoint dir") p_eval.add_argument( "--hf-dataset", dest="hf_dataset", required=True, help="HuggingFace Hub dataset name to evaluate against", ) p_eval.add_argument( "--hf-split", dest="hf_split", default="validation", help="Split inside --hf-dataset (default: validation)", ) p_eval.add_argument( "--hf-max-rows", dest="hf_max_rows", type=int, default=None, help="Optional cap on --hf-dataset rows; default = all", ) p_eval.add_argument("--model_name", default=None, help="Model name override") p_eval.add_argument("--batch_size", type=int, default=4) p_eval.add_argument("--max_length", type=int, default=2048) p_eval.add_argument("--output_dir", default=None, help="Where to save results") p_eval.add_argument( "--output_filename", default="metrics.json", help="Filename for the metrics dump (default: metrics.json)", ) p_eval.set_defaults(func=cmd_evaluate)
sp_serve = subparsers.add_parser("serve", help="Start the FastAPI backend server") sp_serve.add_argument("--host", default="0.0.0.0") sp_serve.add_argument("--port", type=int, default=8000) sp_serve.add_argument("--db-path", default="data/degeneration_probe.db") sp_serve.set_defaults(func=cmd_serve)
sp_worker = subparsers.add_parser("worker", help="Start the inference worker") sp_worker.add_argument("--model", default=None, help="HuggingFace model name (optional if --probe is given; the probe meta names its model)") sp_worker.add_argument("--probe", default=None, help="Path to saved probe checkpoint") sp_worker.add_argument("--dtype", default=None, help="Model dtype") sp_worker.add_argument("--host", default="0.0.0.0") sp_worker.add_argument("--port", type=int, default=9000) sp_worker.set_defaults(func=cmd_worker)
sp_ui = subparsers.add_parser("ui", help="Start the Gradio UI") sp_ui.add_argument("--host", default="0.0.0.0") sp_ui.add_argument("--port", type=int, default=7860) sp_ui.set_defaults(func=cmd_ui)
args = parser.parse_args() args.func(args)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526"""Make the swiss-ai/feature-probes submodule importable.
Call `ensure_feature_probes_on_syspath()` before importing from`feature_probes.*` (the submodule's top-level package)."""
from __future__ import annotations
import sysfrom pathlib import Path
FEATURE_PROBES_ROOT = ( Path(__file__).resolve().parent.parent.parent / "third_party" / "feature_probes")
def ensure_feature_probes_on_syspath() -> None: p = str(FEATURE_PROBES_ROOT) if not FEATURE_PROBES_ROOT.exists(): raise SystemExit( f"feature-probes submodule not found at {FEATURE_PROBES_ROOT}. " f"Run `git submodule update --init` to populate it." ) if p not in sys.path: sys.path.insert(0, p)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136"""YAML training-config loading and dataclasses for the degeneration probe."""
from __future__ import annotations
from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import List, Optional
import yaml
# ---------------------------------------------------------------------------# Probe training configuration (degeneration regression probe)# ---------------------------------------------------------------------------
@dataclassclass LoRAConfig: """LoRA adapter configuration."""
enabled: bool = True rank: int = 16 alpha: int = 32 dropout: float = 0.0 # Optional explicit layer list; default = layers 0..probe.layer (inclusive). layers: Optional[List[int]] = None
@dataclassclass ProbeConfig: """Probe architecture / hook configuration."""
layer: int = 12 # middle-ish layer; override per model lora: LoRAConfig = field(default_factory=LoRAConfig)
@dataclassclass LabelConfig: """How per-token 1 - TTR labels are computed from the completion."""
window_size: int = 256 # TTR computed over next N tokens primary_n: int = 1 # n-gram size for TTR # If set, labels become binary: 1 iff TTR(next window) <= ttr_threshold, # and the trainer switches from MSE on sigmoid to BCE-with-logits. ttr_threshold: Optional[float] = None
@dataclassclass LearningRateConfig: """Per-component learning rates."""
head: float = 5.0e-3 lora: float = 5.0e-5
@dataclassclass HFDatasetConfig: """Optional HuggingFace dataset spec (alternative to local JSONL paths)."""
name: str train_split: str = "train" eval_split: Optional[str] = "validation" max_train_rows: Optional[int] = None max_eval_rows: Optional[int] = None # Row-level positive-class fraction for the train split (and optionally the # eval split). Combined with max_*_rows the loader will draw the requested # ratio without replacement; if one class runs out it uses all available # rows from that class and tops up from the other. train_positive_fraction: Optional[float] = None eval_positive_fraction: Optional[float] = None positive_label_field: str = "degenerating"
@dataclassclass ModelOverride: """Explicit model name for the probe's base model."""
name: str
@dataclassclass TrainingConfig: probe: ProbeConfig = field(default_factory=ProbeConfig) model: Optional[ModelOverride] = None
hf_dataset: Optional[HFDatasetConfig] = None eval_fraction: float = 0.2 max_length: int = 2048
label: LabelConfig = field(default_factory=LabelConfig) learning_rate: LearningRateConfig = field(default_factory=LearningRateConfig) batch_size: int = 4 num_epochs: int = 10 seed: int = 42
wandb_project: Optional[str] = None wandb_entity: Optional[str] = None wandb_run_name: Optional[str] = None
output_dir: str = "outputs/probes"
def _probe_from_raw(raw: dict) -> ProbeConfig: lora_raw = raw.get("lora", {}) or {} lora = LoRAConfig(**lora_raw) kwargs = {k: v for k, v in raw.items() if k != "lora"} return ProbeConfig(lora=lora, **kwargs)
def load_training_config(path: Path) -> TrainingConfig: """Load a plain YAML training config and return a TrainingConfig instance.""" raw = yaml.safe_load(path.read_text(encoding="utf-8"))
probe = _probe_from_raw(raw.get("probe", {}) or {}) label = LabelConfig(**(raw.get("label", {}) or {})) learning_rate = LearningRateConfig(**(raw.get("learning_rate", {}) or {}))
model = ModelOverride(**raw["model"]) if raw.get("model") else None hf_dataset = HFDatasetConfig(**raw["hf_dataset"]) if raw.get("hf_dataset") else None
return TrainingConfig( probe=probe, model=model, hf_dataset=hf_dataset, eval_fraction=raw.get("eval_fraction", 0.2), max_length=raw.get("max_length", 2048), label=label, learning_rate=learning_rate, batch_size=raw.get("batch_size", 4), num_epochs=raw.get("num_epochs", 10), seed=raw.get("seed", 42), wandb_project=raw.get("wandb_project"), wandb_entity=raw.get("wandb_entity"), wandb_run_name=raw.get("wandb_run_name"), output_dir=raw.get("output_dir", "outputs/probes"), )1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889"""Utilities for loading Hugging Face causal language models."""
import loggingfrom typing import Optional, Tuple, Union
# ── ETH Zurich SSL workaround ─────────────────────────────────────────────────# The ETH Zurich network intercepts HTTPS with a self-signed certificate that# Python's SSL stack cannot verify. Patch httpx.Client and AsyncClient to skip# SSL verification so that huggingface_hub requests (model info, custom_generate# downloads, tokenizer Mistral checks, …) don't crash the worker startup.import httpx as _httpx
_orig_client_init = _httpx.Client.__init___orig_async_client_init = _httpx.AsyncClient.__init__
def _client_no_ssl(self, *args, **kwargs): kwargs.setdefault("verify", False) _orig_client_init(self, *args, **kwargs)
def _async_client_no_ssl(self, *args, **kwargs): kwargs.setdefault("verify", False) _orig_async_client_init(self, *args, **kwargs)
_httpx.Client.__init__ = _client_no_ssl_httpx.AsyncClient.__init__ = _async_client_no_ssl# ─────────────────────────────────────────────────────────────────────────────
import torchfrom transformers import AutoModelForCausalLM, AutoTokenizer
log = logging.getLogger(__name__)
def resolve_torch_dtype( dtype_name: Optional[str], *, default: Optional[torch.dtype] = None,) -> Optional[torch.dtype]: """Resolve config dtype name to a torch dtype.""" if dtype_name is None: return default
key = str(dtype_name).strip().lower() if key in {"", "auto", "default", "model"}: return default if key in {"fp32", "float32", "torch.float32"}: return torch.float32 if key in {"fp16", "float16", "torch.float16"}: return torch.float16 if key in {"bf16", "bfloat16", "torch.bfloat16"}: return torch.bfloat16
raise ValueError( f"Unsupported dtype '{dtype_name}'. Use one of: auto, float32, float16, bfloat16." )
def load_model_and_tokenizer( model_name: str, device_map: Optional[Union[str, dict]] = "auto", torch_dtype: Optional[torch.dtype] = None,) -> Tuple[AutoModelForCausalLM, AutoTokenizer]: """Load a Hugging Face causal LM and its tokenizer.""" if torch_dtype is None: if torch.cuda.is_available() and torch.cuda.is_bf16_supported(): torch_dtype = torch.bfloat16 elif torch.backends.mps.is_available(): # MPS does not support bfloat16 matmul with mixed accumulators torch_dtype = torch.float32 else: torch_dtype = torch.float32
model = AutoModelForCausalLM.from_pretrained( model_name, device_map=device_map, dtype=torch_dtype, trust_remote_code=True, )
tokenizer = AutoTokenizer.from_pretrained( model_name, trust_remote_code=True, padding_side="right", )
if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token
return model, tokenizer12345"""Degeneration probe training/evaluation/loading code.
Ported in 2026-05 from third_party/hallucination_probes/degeneration/ when weswitched to swiss-ai/feature-probes as an unpatched submodule dependency."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309"""Dataset + collation: per-token sliding-window 1 - TTR labels."""
from __future__ import annotations
import mathimport warningsfrom dataclasses import dataclassfrom typing import Dict, List, Sequence
import torchfrom torch.utils.data import Dataset
# -------------------------------------------------------------------# Label computation# -------------------------------------------------------------------
def _ngram_ttr(token_ids: Sequence[int], n: int) -> float: """Type-token ratio over n-grams. 1.0 if too few tokens.""" if len(token_ids) < n or n < 1: return 1.0 ngrams = [tuple(token_ids[i : i + n]) for i in range(len(token_ids) - n + 1)] if not ngrams: return 1.0 return len(set(ngrams)) / len(ngrams)
def sliding_window_repetition( token_ids: Sequence[int], window_size: int, n: int,) -> List[float]: """ For each position t in `token_ids`, return 1 - TTR computed over the window `token_ids[t : t + window_size]`. Positions where the full window does not fit (i.e. t + window_size > len) return NaN — the caller is responsible for masking these out of the loss. """ out: List[float] = [] total = len(token_ids) for t in range(total): end = t + window_size if end > total: out.append(float("nan")) else: out.append(1.0 - _ngram_ttr(token_ids[t:end], n)) return out
# -------------------------------------------------------------------# Dataset# -------------------------------------------------------------------
@dataclassclass DegenerationItem: prompt: str completion: str
class DegenerationDataset(Dataset): """ A list of ``(prompt, completion)`` items pulled from a HuggingFace Hub dataset (see ``from_hf``). Per-token labels are computed on the fly in the collate function from the tokenised completion. """
def __init__(self) -> None: self.items: List[DegenerationItem] = [] self.row_labels: list[bool] | None = None
@classmethod def from_hf( cls, name: str, split: str = "train", *, max_rows: int | None = None, prompt_field: str = "prompt", completion_field: str = "generated_text", positive_fraction: float | None = None, label_field: str = "degenerating", shuffle_seed: int = 42, ) -> "DegenerationDataset": """Build a dataset from a HuggingFace Hub dataset.
Streams the requested split into memory and pulls `prompt` / `generated_text` fields. Field names are configurable for datasets that use a different schema.
When ``positive_fraction`` is set, the split is downsampled without replacement to approximately that row-level fraction of positive examples according to ``label_field``. If ``max_rows`` is larger than what the available positives/negatives can support, the sample is capped at the largest feasible size.
When ``max_rows`` is set, the split is first **shuffled with a fixed seed** and then truncated, so the subsample is uniform-random across the underlying source datasets but still reproducible. """ from datasets import concatenate_datasets, load_dataset
ds = load_dataset(name, split=split) if positive_fraction is not None: if not 0.0 <= positive_fraction <= 1.0: raise ValueError("positive_fraction must be in [0, 1]") if label_field not in ds.column_names: raise ValueError( f"positive_fraction requested, but label_field={label_field!r} " f"is not in dataset columns: {ds.column_names}" )
pos_ds = ds.filter(lambda row: bool(row[label_field])) neg_ds = ds.filter(lambda row: not bool(row[label_field])) num_pos = len(pos_ds) num_neg = len(neg_ds)
if max_rows is None: # No size cap: pick the largest sample that hits the exact fraction. if positive_fraction == 0.0: target_rows = num_neg elif positive_fraction == 1.0: target_rows = num_pos else: target_rows = min( math.floor(num_pos / positive_fraction), math.floor(num_neg / (1.0 - positive_fraction)), ) target_pos = int(round(target_rows * positive_fraction)) target_neg = target_rows - target_pos else: # Honor max_rows aggressively: aim for the requested fraction, # but if one class runs out use all of it and top up from the # other so the total still hits max_rows when possible. target_pos = min(int(round(max_rows * positive_fraction)), num_pos) target_neg = min(max_rows - target_pos, num_neg) deficit = max_rows - (target_pos + target_neg) if deficit > 0: if target_pos < num_pos: bump = min(deficit, num_pos - target_pos) target_pos += bump deficit -= bump if deficit > 0 and target_neg < num_neg: bump = min(deficit, num_neg - target_neg) target_neg += bump if target_pos + target_neg < max_rows: warnings.warn( f"Requested max_rows={max_rows} but only " f"{target_pos + target_neg} rows are available " f"({num_pos} positive, {num_neg} negative).", RuntimeWarning, ) target_pos = min(target_pos, num_pos) target_neg = min(target_neg, num_neg)
pos_ds = pos_ds.shuffle(seed=shuffle_seed).select(range(target_pos)) neg_ds = neg_ds.shuffle(seed=shuffle_seed + 1).select(range(target_neg)) ds = concatenate_datasets([pos_ds, neg_ds]).shuffle(seed=shuffle_seed) elif max_rows is not None and max_rows < len(ds): ds = ds.shuffle(seed=shuffle_seed).select(range(max_rows)) obj = cls.__new__(cls) if label_field in ds.column_names: obj.row_labels = [bool(value) for value in ds[label_field]] obj.row_level_positive_count = sum(obj.row_labels) obj.row_level_total_count = len(ds) else: obj.row_labels = None obj.row_level_positive_count = None obj.row_level_total_count = len(ds) obj.items = [ DegenerationItem( prompt=row[prompt_field], completion=row[completion_field], ) for row in ds ] return obj
def __len__(self) -> int: return len(self.items)
def __getitem__(self, idx: int) -> DegenerationItem: return self.items[idx]
# -------------------------------------------------------------------# Collation# -------------------------------------------------------------------
def make_collate_fn( tokenizer, *, max_length: int, window_size: int, primary_n: int, ttr_threshold: float | None = None, smoothing: bool = False,): """ Return a collate function that: - tokenises `prompt + completion` (prompt separately to locate the completion boundary); - produces `input_ids`, `attention_mask` (standard HF shapes); - produces per-token `labels` and a matching `label_mask`.
When ``ttr_threshold`` is None, ``labels[t]`` is the continuous ``1 - TTR(next window_size tokens)`` value (regression target).
When ``ttr_threshold`` is set (e.g. 0.2) and ``smoothing`` is False, ``labels[t]`` is the binary indicator ``1.0 if TTR(next window) <= ttr_threshold else 0.0`` — i.e. positive class = "the next window is degenerate".
When ``ttr_threshold`` is set and ``smoothing`` is True, ``labels[t]`` is the fraction of overlapping size-``window_size`` windows containing token ``t`` whose TTR satisfies ``TTR <= ttr_threshold``. Tokens with no valid overlapping full window remain masked out. """ if smoothing and ttr_threshold is None: raise ValueError("smoothing=True requires ttr_threshold to be set")
def collate_fn(batch: List[DegenerationItem]) -> Dict[str, torch.Tensor]: prompts = [item.prompt for item in batch] completions = [item.completion for item in batch]
prompt_enc = tokenizer( prompts, add_special_tokens=True, truncation=True, max_length=max_length, ) prompt_lengths = [len(ids) for ids in prompt_enc["input_ids"]]
full_texts = [p + c for p, c in zip(prompts, completions)] full_enc = tokenizer( full_texts, add_special_tokens=True, padding=True, truncation=True, max_length=max_length, return_tensors="pt", ) input_ids = full_enc["input_ids"] attention_mask = full_enc["attention_mask"]
B, T = input_ids.shape labels = torch.zeros(B, T, dtype=torch.float32) label_mask = torch.zeros(B, T, dtype=torch.float32)
for i, plen in enumerate(prompt_lengths): seq_len = int(attention_mask[i].sum().item()) if plen >= seq_len: continue completion_ids = input_ids[i, plen:seq_len].tolist() completion_len = len(completion_ids) # Per-completion-token labels: 1 - TTR of the next window_size # tokens. Positions without a full window get NaN → mask=0. rep = sliding_window_repetition( completion_ids, window_size=window_size, n=primary_n, )
if smoothing: last_start = completion_len - window_size if last_start < 0: continue
window_is_degenerate: List[float] = [] for start in range(last_start + 1): r = rep[start] window_is_degenerate.append( 1.0 if (r == r and r >= (1.0 - ttr_threshold)) else 0.0 )
prefix = [0.0] for value in window_is_degenerate: prefix.append(prefix[-1] + value)
for token_idx in range(completion_len): start_lo = max(0, token_idx - (window_size - 1)) start_hi = min(token_idx, last_start) if start_hi < start_lo: continue total = prefix[start_hi + 1] - prefix[start_lo] count = start_hi - start_lo + 1 labels[i, plen + token_idx] = total / count label_mask[i, plen + token_idx] = 1.0 else: for k, r in enumerate(rep): pos = plen + k if not (r == r): # NaN check continue if ttr_threshold is not None: # rep is 1 - TTR; positive class iff TTR <= threshold # iff (1 - TTR) >= (1 - threshold). labels[i, pos] = 1.0 if r >= (1.0 - ttr_threshold) else 0.0 else: labels[i, pos] = r label_mask[i, pos] = 1.0
return { "input_ids": input_ids, "attention_mask": attention_mask, "labels": labels, # [B, T] — 1 - TTR over next window "label_mask": label_mask, # [B, T] — 1 where label is valid }
return collate_fn123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183"""Evaluation for the degeneration regression probe."""
from __future__ import annotations
import jsonimport loggingfrom pathlib import Pathfrom typing import Dict, Optional
import numpy as npimport torchfrom torch.utils.data import DataLoader
from degeneration_probe._feature_probes_path import ensure_feature_probes_on_syspath
ensure_feature_probes_on_syspath()from feature_probes.probes.value_head_probe import ValueHeadProbefrom feature_probes.utils.metrics import compute_clf_metrics
from degeneration_probe.probe.data_loader import DegenerationDataset, make_collate_fn
log = logging.getLogger(__name__)
@torch.no_grad()def evaluate_regression( probe: ValueHeadProbe, loader: DataLoader,) -> Dict[str, float]: """ Run the probe and compute regression metrics against the masked targets.
Returns a dict with masked-token regression metrics (`mse`, `mae`, `pearson`, `n_tokens`) plus the full classification suite from `feature_probes.utils.metrics.compute_clf_metrics` — `accuracy`, `precision`, `recall`, `f1`, `auc`, `optimal_threshold`, `threshold_optimized_accuracy`, `recall_at_0.1_fpr`, and pos/neg counts — computed after binarising both labels and predictions at 0.5. """ probe.eval() device = next(probe.parameters()).device
preds_all: list[float] = [] labels_all: list[float] = []
for batch in loader: input_ids = batch["input_ids"].to(device) attention_mask = batch["attention_mask"].to(device)
out = probe(input_ids=input_ids, attention_mask=attention_mask) probe_logits = out["probe_logits"].squeeze(-1) preds = torch.sigmoid(probe_logits)
# Align labels with where probe_logits emerged (the target layer's # device), since for sharded models that's not the same as the # model input device. labels = batch["labels"].to(probe_logits.device) label_mask = batch["label_mask"].to(probe_logits.device)
mask = label_mask.bool() preds_all.extend(preds[mask].detach().cpu().tolist()) labels_all.extend(labels[mask].detach().cpu().tolist())
if not labels_all: return {"mse": float("nan"), "mae": float("nan"), "pearson": float("nan"), "n_tokens": 0}
preds_np = np.asarray(preds_all, dtype=np.float64) labels_np = np.asarray(labels_all, dtype=np.float64)
mse = float(np.mean((preds_np - labels_np) ** 2)) mae = float(np.mean(np.abs(preds_np - labels_np)))
# Pearson; guarded for zero-variance edge cases. if preds_np.std() < 1e-12 or labels_np.std() < 1e-12: pearson = 0.0 else: pearson = float(np.corrcoef(preds_np, labels_np)[0, 1])
metrics: dict = { "mse": mse, "mae": mae, "pearson": pearson, "n_tokens": int(len(labels_np)), }
# Classification metrics via feature-probes' compute_clf_metrics # (accuracy, precision, recall, f1, auc, optimal_threshold, # threshold_optimized_accuracy, recall_at_0.1_fpr, +/- counts). # Labels and predictions are binarised at 0.5; preds_np stays as the # probability score for ROC/threshold sweep. labels_bin = (labels_np >= 0.5).astype(np.float64) preds_bin = (preds_np >= 0.5).astype(np.float64) if 0 < labels_bin.sum() < len(labels_bin): try: clf = compute_clf_metrics(preds_bin, labels_bin, preds_np) metrics.update(clf) except Exception as e: # pragma: no cover log.warning("compute_clf_metrics failed: %s", e)
return metrics
# -------------------------------------------------------------------# CLI-style entry: load a checkpoint, evaluate on JSONL, save metrics.# -------------------------------------------------------------------
def evaluate_checkpoint( checkpoint_dir: str | Path, *, hf_dataset: str, hf_split: str = "validation", hf_max_rows: Optional[int] = None, batch_size: int = 4, max_length: int = 2048, output_dir: Optional[str | Path] = None, output_filename: str = "metrics.json", model_name: Optional[str] = None,) -> Dict[str, float]: """Load a saved probe and evaluate it on a HuggingFace dataset split.
``hf_max_rows`` optionally caps the split for quick smoke tests; leave ``None`` to evaluate the full split.
Label parameters (window_size, primary_n, ttr_threshold, label_smoothing) are read from the checkpoint's ``config.json`` so the eval reproduces the same target the checkpoint was trained against. """ from peft import PeftModel from feature_probes.utils.model_utils import load_model_and_tokenizer
from degeneration_probe.probe.loader import read_run_config
checkpoint_dir = Path(checkpoint_dir) meta = read_run_config(checkpoint_dir)
resolved_model = model_name or meta.get("model_name") if resolved_model is None: raise ValueError( f"Could not infer model_name from {checkpoint_dir}; " f"pass model_name explicitly." )
model, tokenizer = load_model_and_tokenizer(resolved_model) if (checkpoint_dir / "adapter_config.json").exists(): model = PeftModel.from_pretrained(model, str(checkpoint_dir)) probe = ValueHeadProbe(model, path=checkpoint_dir)
ds = DegenerationDataset.from_hf( hf_dataset, split=hf_split, max_rows=hf_max_rows, ) loader = DataLoader( ds, batch_size=batch_size, shuffle=False, collate_fn=make_collate_fn( tokenizer, max_length=max_length, window_size=int(meta.get("window_size", 256)), primary_n=int(meta.get("primary_n", 1)), ttr_threshold=meta.get("ttr_threshold"), smoothing=bool(meta.get("label_smoothing", False)), ), )
metrics = evaluate_regression(probe, loader)
# Record what we evaluated against so the file is self-describing. metrics["eval_source"] = f"hf:{hf_dataset}:{hf_split}" if hf_max_rows is not None: metrics["eval_max_rows"] = int(hf_max_rows)
if output_dir is not None: output_dir = Path(output_dir) output_dir.mkdir(parents=True, exist_ok=True) (output_dir / output_filename).write_text(json.dumps(metrics, indent=2))
return metrics1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071"""Serving-time probe loading: base model → LoRA adapter → ValueHeadProbe."""
from __future__ import annotations
import jsonfrom pathlib import Path
from peft import PeftModel
from degeneration_probe._feature_probes_path import ensure_feature_probes_on_syspath
ensure_feature_probes_on_syspath()from feature_probes.probes.value_head_probe import ValueHeadProbe
def load_probe( checkpoint_dir: str | Path, base_model,) -> ValueHeadProbe: """ Attach LoRA adapters (if the checkpoint has them) and the saved probe head to `base_model`, returning a ready-to-use ValueHeadProbe.
The worker's `GenerationEngine` can register a forward hook on `probe.target_module` and read per-token logits via `probe.value_head` without invoking `probe.forward()`. """ checkpoint_dir = Path(checkpoint_dir)
if (checkpoint_dir / "adapter_config.json").exists(): base_model = PeftModel.from_pretrained(base_model, str(checkpoint_dir))
probe = ValueHeadProbe(base_model, path=checkpoint_dir) return probe
def read_probe_config(checkpoint_dir: str | Path) -> dict: """Read probe_config.json (written by ValueHeadProbe.save).""" return json.loads( (Path(checkpoint_dir) / "probe_config.json").read_text() )
def read_run_config(checkpoint_dir: str | Path) -> dict: """Read the run config for a checkpoint.
Looks in two places, in order: 1. ``<checkpoint_dir>/config.json`` — self-contained, distributable probe dirs (e.g. the bundled ``demo_probe/``). 2. ``<checkpoint_dir>/../config.json`` — the normal training layout (``outputs/probes/<ts>/config.json`` next to ``outputs/probes/<ts>/checkpoint(_epoch_N)/``).
``evaluate`` and the worker pull ``model_name``, ``window_size``, ``primary_n``, ``ttr_threshold``, ``label_smoothing`` etc. from whichever is found first. """ checkpoint_dir = Path(checkpoint_dir).resolve() candidates = [ checkpoint_dir / "config.json", checkpoint_dir.parent / "config.json", ] for config_path in candidates: if config_path.exists(): return json.loads(config_path.read_text()) raise FileNotFoundError( f"Run config not found (looked in {[str(c) for c in candidates]}); " f"checkpoint at {checkpoint_dir} was not produced by " f"degeneration_probe.probe.train, or has been moved. " f"Pass the required values explicitly (e.g. --model-name)." )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574"""Training entry point for the degeneration probe (MSE regression on 1 - TTR)."""
from __future__ import annotations
import jsonimport loggingimport mathimport platformimport timefrom dataclasses import asdict, dataclass, fieldfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import List, Optional
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch.optim import AdamWfrom torch.utils.data import DataLoader, Sampler, Subset, random_split
from degeneration_probe._feature_probes_path import ensure_feature_probes_on_syspath
ensure_feature_probes_on_syspath()from feature_probes.probes.value_head_probe import ValueHeadProbefrom feature_probes.utils.model_utils import ( load_model_and_tokenizer, setup_lora_for_layers, get_num_layers, print_trainable_parameters,)
from degeneration_probe.probe.data_loader import DegenerationDataset, make_collate_fnfrom degeneration_probe.probe.evaluate import evaluate_regression
log = logging.getLogger(__name__)
# -------------------------------------------------------------------# Config# -------------------------------------------------------------------
@dataclassclass TrainConfig: # Model + probe model_name: str layer: int lora_enabled: bool = True lora_rank: int = 16 lora_alpha: int = 32 lora_dropout: float = 0.0 # If None, LoRA is attached to layers 0..probe_layer (inclusive). # Otherwise, exactly the listed layer indices. lora_layers: Optional[List[int]] = None
# Data — HuggingFace dataset spec. hf_dataset: Optional[str] = None hf_train_split: str = "train" hf_eval_split: Optional[str] = "validation" hf_max_train_rows: Optional[int] = None hf_max_eval_rows: Optional[int] = None hf_train_positive_fraction: Optional[float] = None hf_eval_positive_fraction: Optional[float] = None hf_positive_label_field: str = "degenerating" eval_fraction: float = 0.2 max_length: int = 2048
# Label construction window_size: int = 256 primary_n: int = 1 # If set, switch from continuous regression on `1 - TTR` to binary # classification: positive class = TTR(next window) <= ttr_threshold. # Loss becomes BCE-with-logits instead of masked MSE on sigmoid. ttr_threshold: Optional[float] = None # If true and ttr_threshold is set, labels become soft targets: the # fraction of overlapping windows containing the token that are degenerate. # BCE-with-logits accepts these [0, 1] targets and avoids sigmoid-MSE # saturation. label_smoothing: bool = False
# Optim head_lr: float = 5.0e-3 lora_lr: float = 5.0e-5 batch_size: int = 4 num_epochs: int = 10 seed: int = 42
# Memory gradient_checkpointing: bool = False
# I/O + logging output_dir: str = "outputs/probes" wandb_project: Optional[str] = None wandb_entity: Optional[str] = None wandb_run_name: Optional[str] = None
# -------------------------------------------------------------------# Optimiser: split params into head vs LoRA groups with separate LRs.# Mirrors the pattern in probe/trainer.py::ProbeTrainer.create_optimizer# but as a plain function (no HF Trainer subclass).# -------------------------------------------------------------------
def _build_optimizer(probe: ValueHeadProbe, cfg: TrainConfig) -> AdamW: head_params, lora_params, other_params = [], [], [] for name, param in probe.named_parameters(): if not param.requires_grad: continue if "value_head" in name: head_params.append(param) elif "lora" in name.lower(): lora_params.append(param) else: other_params.append(param)
groups = [] if head_params: groups.append({"params": head_params, "lr": cfg.head_lr, "name": "head"}) if lora_params: groups.append({"params": lora_params, "lr": cfg.lora_lr, "name": "lora"}) if other_params: groups.append({"params": other_params, "lr": cfg.head_lr, "name": "other"}) return AdamW(groups)
# -------------------------------------------------------------------# Loss: MSE between sigmoid(probe_logit) and the [0,1] TTR label, masked# to positions where label_mask == 1.# -------------------------------------------------------------------
def _masked_mse( probe_logits: torch.Tensor, # [B, T] labels: torch.Tensor, # [B, T] label_mask: torch.Tensor, # [B, T]) -> torch.Tensor: preds = torch.sigmoid(probe_logits) sq = (preds - labels) ** 2 denom = label_mask.sum().clamp(min=1.0) return (sq * label_mask).sum() / denom
def _masked_bce_with_logits( probe_logits: torch.Tensor, # [B, T] labels: torch.Tensor, # [B, T] in [0, 1] (binary or soft) label_mask: torch.Tensor, # [B, T]) -> torch.Tensor: per_token = F.binary_cross_entropy_with_logits( probe_logits, labels, reduction="none" ) denom = label_mask.sum().clamp(min=1.0) return (per_token * label_mask).sum() / denom
# -------------------------------------------------------------------# Balanced-batch sampling# -------------------------------------------------------------------
class BalancedBatchSampler(Sampler[list[int]]): """Yield batches that are ~50/50 positive/negative at the row level.
Each batch contains ``batch_size // 2`` positives and the remainder negatives. If a class is exhausted before the epoch's step count is met, that class is reshuffled and drawn again (sampling with replacement across the within-epoch boundary).
Epoch length is set so that the larger class is seen at least once. For a balanced dataset (equal pos/neg) this matches the standard floor(N / batch_size) behaviour. """
def __init__(self, labels: list[bool], batch_size: int, *, seed: int = 42): self.batch_size = batch_size self.pos_per_batch = max(1, batch_size // 2) self.neg_per_batch = max(1, batch_size - self.pos_per_batch) self.pos_idx = [i for i, lbl in enumerate(labels) if lbl] self.neg_idx = [i for i, lbl in enumerate(labels) if not lbl] if not self.pos_idx or not self.neg_idx: raise ValueError( "BalancedBatchSampler needs at least one positive and one " "negative row; got " f"pos={len(self.pos_idx)} neg={len(self.neg_idx)}" ) self._gen = torch.Generator().manual_seed(seed)
def __iter__(self): seed = int(torch.randint(0, 2**31 - 1, (1,), generator=self._gen).item()) rng = torch.Generator().manual_seed(seed)
def _shuffled(items: list[int]) -> list[int]: perm = torch.randperm(len(items), generator=rng).tolist() return [items[i] for i in perm]
pos = _shuffled(self.pos_idx) neg = _shuffled(self.neg_idx) for _ in range(len(self)): batch: list[int] = [] for _ in range(self.pos_per_batch): if not pos: pos = _shuffled(self.pos_idx) batch.append(pos.pop()) for _ in range(self.neg_per_batch): if not neg: neg = _shuffled(self.neg_idx) batch.append(neg.pop()) perm = torch.randperm(len(batch), generator=rng).tolist() yield [batch[i] for i in perm]
def __len__(self) -> int: per_batch_max = max(self.pos_per_batch, self.neg_per_batch) major = max(len(self.pos_idx), len(self.neg_idx)) return max(1, math.ceil(major / per_batch_max))
def _get_row_labels(ds) -> list[bool] | None: """Return per-row labels for stratification, or None if unavailable.
Handles `torch.utils.data.Subset` wrappers (used by `random_split`). """ if isinstance(ds, Subset): underlying = ds.dataset base_labels = getattr(underlying, "row_labels", None) if base_labels is None: return None return [base_labels[i] for i in ds.indices] return getattr(ds, "row_labels", None)
# -------------------------------------------------------------------# Main training function# -------------------------------------------------------------------
def _resolve_dtype() -> torch.dtype: """Pick a training dtype that's stable on the current device.
CPU and MPS: float32 (fp16/bf16 on MPS is flaky, fp16 on CPU is slow). CUDA: bfloat16 when supported. """ if torch.cuda.is_available() and torch.cuda.is_bf16_supported(): return torch.bfloat16 return torch.float32
def _device_info() -> dict: """Capture host/device fingerprint for the run summary.""" info: dict = { "hostname": platform.node(), "torch_version": torch.__version__, "cuda_available": torch.cuda.is_available(), } if torch.cuda.is_available(): info["cuda_device_count"] = torch.cuda.device_count() info["cuda_devices"] = [ torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count()) ] try: info["cuda_version"] = torch.version.cuda except Exception: pass return info
def _format_seconds(secs: float) -> str: """Human-readable hh:mm:ss for the summary.""" h, rem = divmod(int(secs), 3600) m, s = divmod(rem, 60) return f"{h:02d}:{m:02d}:{s:02d}"
def _json_safe(value): """Replace NaN / +Inf / -Inf with None so summary.json is strict-JSON.""" import math if isinstance(value, float): return None if not math.isfinite(value) else value if isinstance(value, dict): return {k: _json_safe(v) for k, v in value.items()} if isinstance(value, (list, tuple)): return [_json_safe(v) for v in value] return value
def train(cfg: TrainConfig) -> Path: """Run training; return the path to the saved checkpoint directory.""" run_start_wall = datetime.now(timezone.utc) run_start = time.monotonic() torch.manual_seed(cfg.seed)
# Create the run directory + dump config up front so per-epoch checkpoints # have a stable parent. (read_run_config reads <run>/config.json.) ts = datetime.now().strftime("%Y%m%d_%H%M%S") out_dir = Path(cfg.output_dir) / ts out_dir.mkdir(parents=True, exist_ok=True) (out_dir / "config.json").write_text( json.dumps(asdict(cfg), indent=2, default=str) )
log.info("Loading model %s", cfg.model_name) model, tokenizer = load_model_and_tokenizer( cfg.model_name, torch_dtype=_resolve_dtype(), ) if hasattr(model, "config"): try: model.config.use_cache = False except Exception: pass
# Resolve layer (support negative indexing). num_layers = get_num_layers(model) layer = cfg.layer if cfg.layer >= 0 else num_layers + cfg.layer if not 0 <= layer < num_layers: raise ValueError(f"layer {cfg.layer} out of range for {num_layers}-layer model")
# Freeze base model weights. LoRA params are unfrozen by get_peft_model. for p in model.parameters(): p.requires_grad = False
if cfg.lora_enabled: if cfg.lora_layers is not None: lora_layer_indices = list(cfg.lora_layers) else: lora_layer_indices = list(range(layer + 1)) log.info( "Attaching LoRA (r=%d, alpha=%d) to layers %s", cfg.lora_rank, cfg.lora_alpha, lora_layer_indices, ) model = setup_lora_for_layers( model, lora_layer_indices, lora_r=cfg.lora_rank, lora_alpha=cfg.lora_alpha, lora_dropout=cfg.lora_dropout, )
if cfg.gradient_checkpointing: # Trades ~25% step time for ~40-50% activation-memory savings. # With LoRA on a frozen base, embeddings don't require grad — without # this, the checkpoint boundary breaks gradient flow into LoRA params. if hasattr(model, "enable_input_require_grads"): model.enable_input_require_grads() if hasattr(model, "gradient_checkpointing_enable"): model.gradient_checkpointing_enable() log.info("Gradient checkpointing enabled") else: log.warning( "Model has no gradient_checkpointing_enable(); skipping" )
probe = ValueHeadProbe(model, layer_idx=layer) # feature-probes places the value head on `model.device` (the first # shard for device_map="auto"), but hidden states emerge on whatever # device the target layer lives on. Align the head + pre-head norm so # the forward matmul doesn't cross GPUs. target_device = next(probe.target_module.parameters()).device probe.value_head.to(target_device) probe.pre_head_norm.to(target_device) print_trainable_parameters(probe)
# --- dataset --------------------------------------------------- collate = make_collate_fn( tokenizer, max_length=cfg.max_length, window_size=cfg.window_size, primary_n=cfg.primary_n, ttr_threshold=cfg.ttr_threshold, smoothing=cfg.label_smoothing, ) if cfg.hf_dataset is None: raise ValueError("TrainConfig.hf_dataset is required (the JSONL path has been removed).") log.info("Loading HF dataset %s [train=%s, eval=%s]", cfg.hf_dataset, cfg.hf_train_split, cfg.hf_eval_split) train_ds = DegenerationDataset.from_hf( cfg.hf_dataset, split=cfg.hf_train_split, max_rows=cfg.hf_max_train_rows, positive_fraction=cfg.hf_train_positive_fraction, label_field=cfg.hf_positive_label_field, ) if cfg.hf_eval_split is not None: eval_ds = DegenerationDataset.from_hf( cfg.hf_dataset, split=cfg.hf_eval_split, max_rows=cfg.hf_max_eval_rows, positive_fraction=cfg.hf_eval_positive_fraction, label_field=cfg.hf_positive_label_field, ) else: n_eval = max(1, int(len(train_ds) * cfg.eval_fraction)) n_train = len(train_ds) - n_eval train_ds, eval_ds = random_split( train_ds, [n_train, n_eval], generator=torch.Generator().manual_seed(cfg.seed), ) log.info("Train: %d items | Eval: %d items", len(train_ds), len(eval_ds)) train_pos = getattr(train_ds, "row_level_positive_count", None) eval_pos = getattr(eval_ds, "row_level_positive_count", None) if train_pos is not None: log.info( "Train row-level positives: %d/%d (%.2f%%)", train_pos, len(train_ds), 100.0 * train_pos / max(len(train_ds), 1), ) if eval_pos is not None: log.info( "Eval row-level positives: %d/%d (%.2f%%)", eval_pos, len(eval_ds), 100.0 * eval_pos / max(len(eval_ds), 1), )
train_labels = _get_row_labels(train_ds) if train_labels is not None and any(train_labels) and not all(train_labels): log.info( "Stratified batch sampling: %d pos / %d neg rows per epoch, " "%d steps/epoch", sum(train_labels), len(train_labels) - sum(train_labels), math.ceil(max(sum(train_labels), len(train_labels) - sum(train_labels)) / max(1, cfg.batch_size // 2)), ) train_loader = DataLoader( train_ds, batch_sampler=BalancedBatchSampler( train_labels, cfg.batch_size, seed=cfg.seed, ), collate_fn=collate, ) else: log.info("Plain shuffled batch sampling (no row-level labels available)") train_loader = DataLoader( train_ds, batch_size=cfg.batch_size, shuffle=True, collate_fn=collate, ) eval_loader = DataLoader( eval_ds, batch_size=cfg.batch_size, shuffle=False, collate_fn=collate, )
# --- optim + wandb -------------------------------------------- optimizer = _build_optimizer(probe, cfg) use_wandb = cfg.wandb_project is not None if use_wandb: import wandb wandb.init( entity=cfg.wandb_entity, project=cfg.wandb_project, name=cfg.wandb_run_name, config=asdict(cfg), )
device = next(probe.parameters()).device global_step = 0
n_trainable = sum(p.numel() for p in probe.parameters() if p.requires_grad) n_total = sum(p.numel() for p in probe.parameters()) epoch_history: list[dict] = []
for epoch in range(cfg.num_epochs): epoch_t0 = time.monotonic() probe.train() epoch_loss = 0.0 n_batches = 0 for batch in train_loader: input_ids = batch["input_ids"].to(device) attention_mask = batch["attention_mask"].to(device) # labels/label_mask must live on the same device as probe_logits # (i.e. the target layer's device), not the embed device. labels = batch["labels"].to(target_device) label_mask = batch["label_mask"].to(target_device)
out = probe(input_ids=input_ids, attention_mask=attention_mask) probe_logits = out["probe_logits"].squeeze(-1) # [B, T]
if cfg.ttr_threshold is not None: loss = _masked_bce_with_logits(probe_logits, labels, label_mask) else: loss = _masked_mse(probe_logits, labels, label_mask)
optimizer.zero_grad() loss.backward() optimizer.step()
epoch_loss += loss.item() n_batches += 1 global_step += 1
if use_wandb: import wandb step_loss_name = "bce" if cfg.ttr_threshold is not None else "mse" wandb.log({f"train/{step_loss_name}": loss.item(), "train/step": global_step})
avg = epoch_loss / max(n_batches, 1) loss_name = "BCE" if cfg.ttr_threshold is not None else "MSE" log.info("Epoch %d/%d — train %s: %.5f", epoch + 1, cfg.num_epochs, loss_name, avg) if use_wandb: import wandb wandb.log({f"train/epoch_{loss_name.lower()}": avg, "epoch": epoch + 1})
# --- per-epoch eval --------------------------------------- metrics = evaluate_regression(probe, eval_loader) log.info( " eval — mse=%.5f pearson=%.3f auc=%.3f f1=%.3f recall@0.1fpr=%.3f", metrics["mse"], metrics["pearson"], metrics.get("auc", float("nan")), metrics.get("f1", float("nan")), metrics.get("recall_at_0.1_fpr", float("nan")), ) if use_wandb: import wandb wandb.log({f"eval/{k}": v for k, v in metrics.items()})
epoch_history.append({ "epoch": epoch + 1, "train_loss": avg, "eval": metrics, "duration_seconds": round(time.monotonic() - epoch_t0, 2), })
# Save weights after every epoch so we can evaluate any of them on # different validation sets later without retraining. epoch_ckpt_dir = out_dir / f"checkpoint_epoch_{epoch + 1}" epoch_ckpt_dir.mkdir(parents=True, exist_ok=True) probe.save(epoch_ckpt_dir) log.info(" saved per-epoch checkpoint to %s", epoch_ckpt_dir)
# --- save final ------------------------------------------------ ckpt_dir = out_dir / "checkpoint" ckpt_dir.mkdir(parents=True, exist_ok=True) probe.save(ckpt_dir)
if use_wandb: import wandb wandb.finish()
# Run summary: timing + device + headline metrics. Sits next to config.json # so anyone inspecting outputs/probes/<ts>/ can answer "how long, where, # how well" without parsing logs. duration = time.monotonic() - run_start summary = { "run_started_utc": run_start_wall.isoformat(), "run_finished_utc": datetime.now(timezone.utc).isoformat(), "duration_seconds": round(duration, 2), "duration_hms": _format_seconds(duration), "device": _device_info(), "model_name": cfg.model_name, "probe_layer": layer, "lora_layers": lora_layer_indices if cfg.lora_enabled else None, "loss": "BCE" if cfg.ttr_threshold is not None else "MSE", "ttr_threshold": cfg.ttr_threshold, "label_smoothing": cfg.label_smoothing, "trainable_parameters": n_trainable, "total_parameters": n_total, "trainable_fraction": round(n_trainable / max(n_total, 1), 6), "num_train_items": len(train_ds), "num_eval_items": len(eval_ds), "num_train_positive_rows": train_pos, "num_eval_positive_rows": eval_pos, "num_epochs": cfg.num_epochs, "batch_size": cfg.batch_size, "max_length": cfg.max_length, "head_lr": cfg.head_lr, "lora_lr": cfg.lora_lr, "epochs": epoch_history, "final_eval": epoch_history[-1]["eval"] if epoch_history else None, "checkpoint_dir": str(ckpt_dir), } (out_dir / "summary.json").write_text( json.dumps(_json_safe(summary), indent=2, allow_nan=False) )
log.info("Saved probe to %s (took %s)", ckpt_dir, _format_seconds(duration)) return ckpt_dir1234567891011121314151617181920212223242526272829303132333435363738"""FastAPI application factory."""
from __future__ import annotations
from contextlib import asynccontextmanagerfrom pathlib import Path
from fastapi import FastAPI
from degeneration_probe.server.database import Databasefrom degeneration_probe.server.routes_sessions import router as sessions_routerfrom degeneration_probe.server.ws_generate import router as ws_router
DEFAULT_DB_PATH = Path("data/degeneration_probe.db")
def create_app(db_path: str | Path = DEFAULT_DB_PATH) -> FastAPI: """Create and configure the FastAPI application.""" Path(db_path).parent.mkdir(parents=True, exist_ok=True) db = Database(db_path)
@asynccontextmanager async def lifespan(app: FastAPI): await db.init() app.state.db = db yield await db.close()
app = FastAPI( title="Degeneration Probe API", description="Backend for real-time LLM degeneration detection and steering", lifespan=lifespan, )
app.include_router(sessions_router) app.include_router(ws_router)
return app123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109"""SQLite database for session and generation storage."""
from __future__ import annotations
import jsonfrom datetime import datetime, timezonefrom pathlib import Path
import aiosqlite
class Database: """Async SQLite database wrapper for sessions and generations."""
def __init__(self, db_path: str | Path): self.db_path = str(db_path) self._db: aiosqlite.Connection | None = None
async def init(self): """Initialize the database and create tables.""" self._db = await aiosqlite.connect(self.db_path) self._db.row_factory = aiosqlite.Row await self._db.executescript(""" CREATE TABLE IF NOT EXISTS sessions ( id INTEGER PRIMARY KEY AUTOINCREMENT, created_at TEXT NOT NULL, worker_host TEXT NOT NULL, worker_port INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'connected' ); CREATE TABLE IF NOT EXISTS generations ( id INTEGER PRIMARY KEY AUTOINCREMENT, session_id INTEGER, prompt TEXT NOT NULL, params_json TEXT NOT NULL, steering_json TEXT NOT NULL, output_text TEXT NOT NULL DEFAULT '', tokens_json TEXT NOT NULL DEFAULT '[]', status TEXT NOT NULL DEFAULT 'running', created_at TEXT NOT NULL, FOREIGN KEY (session_id) REFERENCES sessions(id) ); """) await self._db.commit()
async def close(self): if self._db: await self._db.close()
async def create_session(self, worker_host: str, worker_port: int) -> dict: """Create a new session and mark any existing ones as disconnected.""" now = datetime.now(timezone.utc).isoformat() await self._db.execute( "UPDATE sessions SET status = 'disconnected' WHERE status = 'connected'" ) cursor = await self._db.execute( "INSERT INTO sessions (created_at, worker_host, worker_port, status) VALUES (?, ?, ?, 'connected')", (now, worker_host, worker_port), ) await self._db.commit() row = await self._db.execute_fetchall( "SELECT * FROM sessions WHERE id = ?", (cursor.lastrowid,) ) return dict(row[0])
async def get_current_session(self) -> dict | None: """Get the currently connected session, or None.""" rows = await self._db.execute_fetchall( "SELECT * FROM sessions WHERE status = 'connected' ORDER BY id DESC LIMIT 1" ) return dict(rows[0]) if rows else None
async def save_generation( self, session_id: int, prompt: str, params: dict, steering: dict, output_text: str, tokens: list[dict], status: str, ) -> dict: """Save a generation record.""" now = datetime.now(timezone.utc).isoformat() cursor = await self._db.execute( """INSERT INTO generations (session_id, prompt, params_json, steering_json, output_text, tokens_json, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", ( session_id, prompt, json.dumps(params), json.dumps(steering), output_text, json.dumps(tokens), status, now, ), ) await self._db.commit() row = await self._db.execute_fetchall( "SELECT * FROM generations WHERE id = ?", (cursor.lastrowid,) ) result = dict(row[0]) result["tokens"] = json.loads(result.pop("tokens_json")) result["params"] = json.loads(result.pop("params_json")) result["steering"] = json.loads(result.pop("steering_json")) return result
1234567891011121314151617181920212223242526272829303132333435363738"""Session management endpoints."""
import json
import websocketsfrom fastapi import APIRouter, HTTPException, Requestfrom pydantic import BaseModel
router = APIRouter()
class CreateSessionRequest(BaseModel): worker_host: str worker_port: int
@router.post("/api/sessions")async def create_session(req: CreateSessionRequest, request: Request): db = request.app.state.db session = await db.create_session(req.worker_host, req.worker_port) return session
@router.get("/api/worker/info")async def worker_info(request: Request): """Ask the current worker what model it's serving.""" db = request.app.state.db session = await db.get_current_session() if session is None: raise HTTPException(status_code=404, detail="No active session") worker_url = f"ws://{session['worker_host']}:{session['worker_port']}" try: async with websockets.connect(worker_url, ping_timeout=None, open_timeout=5) as ws: await ws.send(json.dumps({"action": "info"})) raw = await ws.recv() return json.loads(raw) except Exception as e: raise HTTPException(status_code=502, detail=f"Worker unreachable: {e}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115"""WebSocket endpoint for streaming generation."""
import asyncioimport jsonimport logging
from fastapi import APIRouter, WebSocket, WebSocketDisconnectimport websockets
router = APIRouter()log = logging.getLogger("backend.ws")
@router.websocket("/api/generate")async def ws_generate(ws: WebSocket): """Relay generation between the Gradio client and the inference worker.
1. Client sends a generate request (JSON with prompt, params, steering). 2. Backend connects to the inference worker and forwards the request. 3. Backend streams token messages from worker back to client. 4. If the client disconnects, the worker connection is closed too. """ await ws.accept() db = ws.app.state.db worker_ws = None
try: raw = await ws.receive_text() request = json.loads(raw) log.info("Generate request: prompt=%d chars", len(request.get("prompt", "")))
session = await db.get_current_session() if session is None: log.warning("No worker session — rejecting request") await ws.send_json({"type": "error", "message": "No worker connected"}) await ws.close() return
worker_url = f"ws://{session['worker_host']}:{session['worker_port']}" log.info("Connecting to worker at %s", worker_url)
tokens = [] output_text = "" worker_ws = await websockets.connect(worker_url, ping_timeout=None) log.info("Connected to worker") await worker_ws.send(json.dumps(request))
async def forward_client_to_worker() -> None: """Relay mid-stream control messages (slider updates, stop) to the worker.""" try: while True: raw_ctrl = await ws.receive_text() log.info("relay client->worker: %s", raw_ctrl[:200]) await worker_ws.send(raw_ctrl) except WebSocketDisconnect: log.info("client->worker relay: ws disconnected") except Exception: log.exception("client->worker relay ended")
relay_task = asyncio.create_task(forward_client_to_worker())
try: async for msg in worker_ws: data = json.loads(msg)
# Try to send to client — if client disconnected, break out try: await ws.send_json(data) except (WebSocketDisconnect, RuntimeError): log.warning("UI client disconnected at token %d", len(tokens)) break
if data["type"] == "tokens": for t in data["tokens"]: tokens.append({ "token_id": t["token_id"], "token_text": t["token_text"], "position": t["position"], "probe_score": t["probe_score"], "was_steered": t["was_steered"], }) output_text += t["token_text"] elif data["type"] == "done": log.info("Generation done: %d tokens", len(tokens)) break finally: relay_task.cancel()
# Save whatever we generated (even if stopped early) if tokens: await db.save_generation( session_id=session["id"], prompt=request.get("prompt", ""), params=request.get("params", {}), steering=request.get("steering", {}), output_text=output_text, tokens=tokens, status="completed", ) log.info("Saved generation: %d tokens", len(tokens))
except WebSocketDisconnect: log.info("UI client disconnected (tokens so far: %d)", len(tokens) if 'tokens' in dir() else 0) except Exception as e: log.exception("Error in ws_generate") try: await ws.send_json({"type": "error", "message": str(e)}) except Exception: pass finally: if worker_ws is not None: try: await worker_ws.close() except Exception: pass1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465"""Gradio interface for the degeneration probe visualization."""
from __future__ import annotations
import jsonimport loggingimport threadingfrom pathlib import Path
import gradio as grimport plotly.graph_objects as goimport requestsimport websocket # from websocket-client
log = logging.getLogger("ui")
API_BASE = "http://localhost:8000"
# Module-level handle on the currently open generation WebSocket so the slider# .change() handlers (which run outside generate_stream's scope) can push live# parameter updates through it._live_ws: websocket.WebSocket | None = None_live_ws_lock = threading.Lock()
# Latest slider values, kept in sync by the .change() handlers. generate_stream# reads this to attribute the live-temperature-at-token for the trace chart._current_values: dict[str, float] = {"temperature": 0.01, "top_p": 0.9, "steering_threshold": 0.8}
def _set_live_ws(ws: websocket.WebSocket | None) -> None: global _live_ws with _live_ws_lock: _live_ws = ws
def _push_param_update(name: str): """Return a Gradio .change() handler that forwards the new value to the worker.""" def _send(value): _current_values[name] = float(value) with _live_ws_lock: ws = _live_ws if ws is None: log.info("live %s=%s: no active generation, skipping", name, value) return try: ws.send(json.dumps({"action": "update_params", "params": {name: value}})) log.info("live %s=%s: pushed to worker", name, value) except Exception as e: log.warning("live %s=%s: send failed: %s", name, value, e) return _send
# Muted, modern paletteCOLORS = { "safe": (74, 182, 144), # soft teal-green "mid": (234, 179, 70), # warm amber "danger": (214, 87, 89), # muted coral-red "steered": (130, 120, 210), # soft purple underline "bg": "#f8f9fb", "card": "#ffffff", "border": "#e2e6ea", "text": "#2d3142", "muted": "#8a8fa0", "bar_bg": "#f0f1f4", "threshold_line": "rgba(214,87,89,0.45)",}
CSS = """@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap');
.gradio-container { font-family: 'Inter', 'JetBrains Mono', monospace !important; max-width: none !important; width: 100%% !important; background: %(bg)s !important; color: %(text)s !important; padding-top: 0 !important; font-size: 17px !important;}
/* ── Header ──────────────────────────────────────────────────── */#probe-header { text-align: center; padding: 18px 0 0; border-bottom: 1px solid %(border)s; margin-bottom: 0;}.probe-title-gradient { background: linear-gradient(135deg, #4a6cf7 0%%, #7c3aed 100%%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; font-size: 40px !important; font-weight: 700 !important; letter-spacing: -0.8px; margin: 0 0 6px !important; line-height: 1.2 !important;}.probe-subtitle { color: %(muted)s; font-size: 16px; margin: 0 0 12px;}#model-badge { display: inline-block;}
/* ── Tabs ────────────────────────────────────────────────────── */.tabs > .tab-nav { background: %(card)s !important; border-bottom: 2px solid %(border)s !important; padding: 0 20px !important; margin-top: 0 !important;}.tabs { margin-top: 0 !important; gap: 0 !important;}/* Kill every wrapper gap between header and tabs */.gradio-container > .main > .wrap > div,.gradio-container > div > div > div { gap: 0 !important;}.gradio-container .block { margin-top: 0 !important; margin-bottom: 0 !important;}.tabs > .tab-nav button { font-size: 22px !important; font-weight: 600 !important; padding: 14px 36px !important; border-radius: 0 !important; border: none !important; color: %(muted)s !important; background: transparent !important; letter-spacing: 0.1px;}.tabs > .tab-nav button.selected { color: #4a6cf7 !important; border-bottom: 3px solid #4a6cf7 !important; margin-bottom: -2px !important;}
/* ── Buttons ─────────────────────────────────────────────────── */.gr-button-primary, button.primary { background: linear-gradient(135deg, #4a6cf7, #7c3aed) !important; border: none !important; border-radius: 8px !important; color: #ffffff !important; font-weight: 600 !important; box-shadow: 0 2px 8px rgba(74,108,247,0.35) !important;}.gr-button-primary:hover, button.primary:hover { opacity: 0.9 !important; box-shadow: 0 4px 14px rgba(74,108,247,0.45) !important;}.gr-button-secondary, .gr-button, button.secondary { border-radius: 8px !important; background: #ffffff !important; border: 1px solid %(border)s !important; color: %(text)s !important;}
/* ── Controls panel ──────────────────────────────────────────── */#controls-panel { background: %(card)s; border: 1px solid %(border)s; border-radius: 14px; padding: 16px 16px 16px 16px; gap: 4px !important; box-shadow: 0 1px 6px rgba(0,0,0,0.04);}#controls-panel .gr-form,#controls-panel .form,#controls-panel .block { gap: 6px !important; padding: 0 !important; margin: 0 !important; border: none !important; background: transparent !important;}#controls-panel label,#controls-panel .label-wrap,#controls-panel span[data-testid="block-info"] { font-size: 15px !important; margin-bottom: 2px !important;}#controls-panel input[type="range"] { height: 4px !important;}#controls-panel .wrap > div { margin-bottom: 4px !important;}#steering-divider { border-top: 1px dashed %(border)s; margin: 6px 0; height: 0;}#controls-panel p { margin: 0 !important;}#action-row { margin-top: 14px;}
/* ── Output panel ────────────────────────────────────────────── */#output-panel { background: %(card)s; border: 1px solid %(border)s; border-radius: 14px; padding: 20px 24px; min-height: 200px; font-size: 17px; line-height: 1.7; color: %(text)s; box-shadow: 0 1px 6px rgba(0,0,0,0.04);}#score-panel { background: %(card)s; border: 1px solid %(border)s; border-radius: 14px; padding: 14px 20px; margin-top: 8px; box-shadow: 0 1px 6px rgba(0,0,0,0.04);}
/* Hide Gradio chrome */footer, .footer, .built-with, .show-api { display: none !important; }
/* ── About panel ──────────────────────────────────────────────── */#about-panel { max-width: 980px; margin: 0 auto; padding: 8px 4px 32px; color: %(text)s; line-height: 1.65;}.about-section { margin-bottom: 36px;}.section-header { display: flex; align-items: center; gap: 10px; margin-bottom: 14px;}.section-accent { width: 4px; min-width: 4px; height: 22px; background: linear-gradient(180deg, #4a6cf7, #7c3aed); border-radius: 2px;}.section-title { font-size: 21px; font-weight: 700; color: %(text)s; margin: 0;}.intro-text { font-size: 16px; color: #4a5568; line-height: 1.75; margin: 0; background: %(card)s; border: 1px solid %(border)s; border-left: 4px solid #4a6cf7; border-radius: 0 10px 10px 0; padding: 14px 18px;}
/* Why cards */.why-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 14px;}.why-card { background: %(card)s; border: 1px solid %(border)s; border-radius: 12px; padding: 18px 16px; border-top: 3px solid #ef4444;}.why-card-title { color: #dc2626; font-weight: 700; font-size: 13px; letter-spacing: 0.8px; text-transform: uppercase; margin-bottom: 10px;}.why-card-text { font-size: 15px; color: #4a5568; line-height: 1.65; margin: 0;}
/* Chat example */.example-note { font-size: 15px; color: #4a5568; line-height: 1.7; margin: 0 0 14px;}.chat-window { height: 440px; overflow-y: auto; border: 1px solid %(border)s; border-radius: 12px; padding: 20px 14px; background: %(bg)s; display: flex; flex-direction: column; gap: 20px;}.chat-user-row { display: flex; justify-content: flex-end; }.chat-user-bubble { background: linear-gradient(135deg, #4a6cf7, #6d5ce7); color: #ffffff; padding: 12px 16px; border-radius: 16px 16px 4px 16px; max-width: 76%%; font-size: 16px; line-height: 1.65; box-shadow: 0 2px 8px rgba(74,108,247,0.25);}.chat-assistant-row { display: flex; gap: 10px; align-items: flex-start; }.chat-avatar { min-width: 32px; height: 32px; border-radius: 50%%; background: linear-gradient(135deg, #4a6cf7, #7c3aed); font-size: 12px; font-weight: 700; color: #fff; display: flex; align-items: center; justify-content: center; flex-shrink: 0; margin-top: 2px; box-shadow: 0 2px 6px rgba(74,108,247,0.3);}.chat-assistant-bubble { background: %(card)s; border: 1px solid %(border)s; padding: 14px 18px; border-radius: 4px 16px 16px 16px; font-size: 16px; line-height: 1.78; color: %(text)s; box-shadow: 0 1px 4px rgba(0,0,0,0.05);}
/* Degeneration highlight */.degen-span { background: rgba(220,38,38,0.15); border-bottom: 2px solid #dc2626; border-radius: 2px;}.degen-note { display: block; color: %(muted)s; font-style: italic; font-size: 12px; margin-top: 10px;}
/* Boxed math values */.boxed-val { display: inline-block; border: 1.5px solid currentColor; border-radius: 3px; padding: 0 5px; font-weight: 600; font-family: 'JetBrains Mono', monospace; margin: 0 2px;}#about-panel code { background: #eef1f6; padding: 1px 5px; border-radius: 4px; font-size: 13px;}""" % COLORS
# ── Dataset stats ──────────────────────────────────────────────────────────────_STATS_PATH = Path(__file__).parent / "dataset_stats.json"_DATASET_STATS: dict = {}try: _DATASET_STATS = json.loads(_STATS_PATH.read_text(encoding="utf-8"))except Exception: pass
_DATASET_LABELS = { "AI-MO/NuminaMath-1.5": "NuminaMath-1.5", "FreedomIntelligence/medical-o1-verifiable-problem": "Medical-O1", "allenai/IF_sft_data_verified": "IF-SFT", "nvidia/Llama-Nemotron-Post-Training-Dataset": "Llama-Nemotron", "zwhe99/DeepMath-103K": "DeepMath-103K",}_DATASET_COLORS = { "AI-MO/NuminaMath-1.5": "#4a6cf7", "FreedomIntelligence/medical-o1-verifiable-problem": "#7c3aed", "allenai/IF_sft_data_verified": "#d97706", "nvidia/Llama-Nemotron-Post-Training-Dataset": "#059669", "zwhe99/DeepMath-103K": "#0891b2",}
_PLOT_LAYOUT = dict( paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)", font=dict(family="JetBrains Mono, SF Mono, Fira Code, monospace", size=12, color="#2d3142"),)
def _build_repetition_score_chart() -> go.Figure: """Horizontal bar chart: average repetition score per dataset.""" keys = list(_DATASET_STATS.keys()) labels = [_DATASET_LABELS.get(k, k.split("/")[-1]) for k in keys] scores = [_DATASET_STATS[k]["avg_repetition_score"] for k in keys] colors = [_DATASET_COLORS.get(k, "#8a8fa0") for k in keys]
order = sorted(range(len(scores)), key=lambda i: scores[i]) labels = [labels[i] for i in order] scores = [scores[i] for i in order] colors = [colors[i] for i in order]
fig = go.Figure(go.Bar( x=scores, y=labels, orientation="h", marker=dict(color=colors, line=dict(width=0)), text=[f"{s:.3f}" for s in scores], textposition="outside", cliponaxis=False, )) fig.update_layout( **_PLOT_LAYOUT, height=280, margin=dict(l=10, r=20, t=40, b=10), modebar=dict(remove=["all"]), showlegend=False, title=dict( text="Average repetition score per dataset", x=0.5, xanchor="center", font=dict(size=15, color="#2d3142"), ), xaxis=dict( range=[0, 0.65], gridcolor="#e2e6ea", zeroline=False, title=dict(text="avg repetition score", font=dict(size=11, color="#8a8fa0")), ), yaxis=dict(gridcolor="#e2e6ea", zeroline=False, automargin=True), bargap=0.35, ) return fig
def _build_degeneration_chart() -> go.Figure: """Grouped horizontal bar chart: % degenerating tokens and generations per dataset.""" keys = list(_DATASET_STATS.keys()) labels = [_DATASET_LABELS.get(k, k.split("/")[-1]) for k in keys] pct_tok = [_DATASET_STATS[k]["pct_degenerating_tokens"] for k in keys] pct_gen = [_DATASET_STATS[k]["pct_degenerating_generations"] for k in keys] colors = [_DATASET_COLORS.get(k, "#8a8fa0") for k in keys]
order = sorted(range(len(pct_tok)), key=lambda i: pct_tok[i]) labels = [labels[i] for i in order] pct_tok = [pct_tok[i] for i in order] pct_gen = [pct_gen[i] for i in order] colors = [colors[i] for i in order]
fig = go.Figure() fig.add_trace(go.Bar( name="% of tokens flagged degenerating", x=pct_tok, y=labels, orientation="h", marker=dict(color=colors, opacity=0.85, line=dict(width=0)), text=[f"{v:.1f}%" for v in pct_tok], textposition="outside", cliponaxis=False, )) fig.add_trace(go.Bar( name="% of generations with ≥1 degenerating token", x=pct_gen, y=labels, orientation="h", marker=dict(color=colors, opacity=0.38, line=dict(color=colors, width=1.2)), text=[f"{v:.2f}%" for v in pct_gen], textposition="outside", cliponaxis=False, )) fig.update_layout( **_PLOT_LAYOUT, barmode="group", bargap=0.25, bargroupgap=0.08, showlegend=True, legend=dict( orientation="h", y=-0.22, x=0.5, xanchor="center", font=dict(size=10), bgcolor="rgba(0,0,0,0)", ), height=320, modebar=dict(remove=["all"]), title=dict( text="Degeneration rate per dataset", x=0.5, xanchor="center", font=dict(size=15, color="#2d3142"), ), xaxis=dict( gridcolor="#e2e6ea", zeroline=False, title=dict(text="percentage (%)", font=dict(size=11, color="#8a8fa0")), ), yaxis=dict(gridcolor="#e2e6ea", zeroline=False, automargin=True), margin=dict(l=10, r=20, t=40, b=60), ) return fig
def _build_token_composition_chart() -> go.Figure: """Stacked horizontal bar: normal / degenerating / null tokens per dataset.""" keys = list(_DATASET_STATS.keys()) labels = [_DATASET_LABELS.get(k, k.split("/")[-1]) for k in keys] colors = [_DATASET_COLORS.get(k, "#8a8fa0") for k in keys]
pct_null = [_DATASET_STATS[k]["pct_null_tokens"] for k in keys] pct_degen = [_DATASET_STATS[k]["pct_degenerating_tokens"] * (1 - _DATASET_STATS[k]["pct_null_tokens"] / 100) for k in keys] pct_normal = [100 - pct_null[i] - pct_degen[i] for i in range(len(keys))]
# Sort by pct_null descending order = sorted(range(len(keys)), key=lambda i: pct_null[i], reverse=True) labels = [labels[i] for i in order] pct_null = [pct_null[i] for i in order] pct_degen = [pct_degen[i] for i in order] pct_normal = [pct_normal[i] for i in order]
fig = go.Figure() fig.add_trace(go.Bar( name="normal tokens", x=pct_normal, y=labels, orientation="h", marker=dict(color="#4a6cf7", opacity=0.7), text=[f"{v:.1f}%" for v in pct_normal], textposition="inside", insidetextanchor="middle", )) fig.add_trace(go.Bar( name="degenerating tokens", x=pct_degen, y=labels, orientation="h", marker=dict(color="#dc2626", opacity=0.8), text=[f"{v:.1f}%" for v in pct_degen], textposition="inside", insidetextanchor="middle", )) fig.add_trace(go.Bar( name="null tokens (< 256-token window)", x=pct_null, y=labels, orientation="h", marker=dict(color="#e2e6ea", line=dict(color="#c0c6d0", width=1)), text=[f"{v:.1f}%" for v in pct_null], textposition="inside", insidetextanchor="middle", textfont=dict(color="#8a8fa0"), )) fig.update_layout( **_PLOT_LAYOUT, barmode="stack", height=280, margin=dict(l=10, r=20, t=40, b=60), modebar=dict(remove=["all"]), showlegend=True, legend=dict( orientation="h", y=-0.22, x=0.5, xanchor="center", font=dict(size=10), bgcolor="rgba(0,0,0,0)", ), title=dict( text="Token composition per dataset", x=0.5, xanchor="center", font=dict(size=15, color="#2d3142"), ), xaxis=dict( range=[0, 100], gridcolor="#e2e6ea", zeroline=False, title=dict(text="% of all tokens", font=dict(size=11, color="#8a8fa0")), ), yaxis=dict(gridcolor="#e2e6ea", zeroline=False, automargin=True), bargap=0.35, ) return fig
def _build_scatter_chart() -> go.Figure: """Scatter: avg repetition score vs % degenerating generations.""" keys = list(_DATASET_STATS.keys()) labels = [_DATASET_LABELS.get(k, k.split("/")[-1]) for k in keys] x = [_DATASET_STATS[k]["avg_repetition_score"] for k in keys] y = [_DATASET_STATS[k]["pct_degenerating_generations"] for k in keys] colors = [_DATASET_COLORS.get(k, "#8a8fa0") for k in keys]
fig = go.Figure(go.Scatter( x=x, y=y, mode="markers+text", text=labels, textposition="top center", textfont=dict(size=11, color="#2d3142"), marker=dict(color=colors, size=14, line=dict(color="#ffffff", width=2)), hovertemplate=( "<b>%{text}</b><br>" "avg repetition score: %{x:.3f}<br>" "% degenerating generations: %{y:.2f}%" "<extra></extra>" ), )) fig.update_layout( **_PLOT_LAYOUT, height=300, margin=dict(l=10, r=20, t=40, b=40), modebar=dict(remove=["all"]), showlegend=False, title=dict( text="Avg repetition score vs % degenerating generations", x=0.5, xanchor="center", font=dict(size=15, color="#2d3142"), ), xaxis=dict( gridcolor="#e2e6ea", zeroline=False, title=dict(text="avg repetition score", font=dict(size=11, color="#8a8fa0")), ), yaxis=dict( gridcolor="#e2e6ea", zeroline=False, title=dict(text="% degenerating generations", font=dict(size=11, color="#8a8fa0")), ), ) return fig
def _build_avg_length_chart() -> go.Figure: """Horizontal bar: average generation length per dataset.""" keys = list(_DATASET_STATS.keys()) labels = [_DATASET_LABELS.get(k, k.split("/")[-1]) for k in keys] lengths = [_DATASET_STATS[k]["avg_tokens_per_generation"] for k in keys] colors = [_DATASET_COLORS.get(k, "#8a8fa0") for k in keys]
order = sorted(range(len(lengths)), key=lambda i: lengths[i]) labels = [labels[i] for i in order] lengths = [lengths[i] for i in order] colors = [colors[i] for i in order]
fig = go.Figure(go.Bar( x=lengths, y=labels, orientation="h", marker=dict(color=colors, line=dict(width=0)), text=[f"{v:.0f}" for v in lengths], textposition="outside", cliponaxis=False, )) fig.add_vline( x=256, line=dict(color="#dc2626", dash="dash", width=1.5), annotation=dict( text="256-token window", font=dict(size=10, color="#dc2626"), xanchor="left", yanchor="top", ), ) fig.update_layout( **_PLOT_LAYOUT, height=280, margin=dict(l=10, r=20, t=40, b=10), modebar=dict(remove=["all"]), showlegend=False, title=dict( text="Average generation length (tokens)", x=0.5, xanchor="center", font=dict(size=15, color="#2d3142"), ), xaxis=dict( gridcolor="#e2e6ea", zeroline=False, title=dict(text="avg tokens per generation", font=dict(size=11, color="#8a8fa0")), ), yaxis=dict(gridcolor="#e2e6ea", zeroline=False, automargin=True), bargap=0.35, ) return fig
ABOUT_HTML = """<div id="about-panel">
<!-- ── Section 1: What ───────────────────────────────────── --> <div class="about-section"> <div class="section-header"> <div class="section-accent"></div> <h2 class="section-title">What is model degeneration?</h2> </div> <p class="intro-text"> Model degeneration is a failure mode in autoregressive language models where generation collapses into repetitive, low-information output. The model becomes trapped in a loop — repeating the same phrase indefinitely while the output loses all semantic value. It does not stop generating; it simply stops <em>communicating</em>. </p> </div>
<!-- ── Section 2: Why ────────────────────────────────────── --> <div class="about-section"> <div class="section-header"> <div class="section-accent"></div> <h2 class="section-title">Why does it happen?</h2> </div> <div class="why-grid">
<div class="why-card"> <div class="why-card-title">Probability Mass Concentration</div> <p class="why-card-text">At low temperature the softmax peaks sharply. A token that already appears in context gets even higher probability at the next step, locking the model into a self-reinforcing loop that is hard to break.</p> </div>
<div class="why-card"> <div class="why-card-title">Attention Sinks</div> <p class="why-card-text">Certain tokens — punctuation, common function words — attract disproportionate attention weight, narrowing the output distribution and pushing generation toward predictable, repeated sequences.</p> </div>
<div class="why-card"> <div class="why-card-title">Question Difficulty</div> <p class="why-card-text">When the model cannot answer confidently, probability mass shifts to safe generic fillers instead of a correct response. The harder the question, the more likely the model gives up and repeats rather than reasons.</p> </div>
</div> </div>
<!-- ── Section 3: Example ────────────────────────────────── --> <div class="about-section"> <div class="section-header"> <div class="section-accent"></div> <h2 class="section-title">A concrete example</h2> </div> <p class="example-note"> The following exchange was generated by <span style="background:#fef08a;color:#713f12;border-radius:3px;padding:1px 6px;font-weight:600;">Apertus-8B-Instruct</span> on a competition mathematics problem. After a plausible opening, the model reaches a wrong conclusion and immediately enters a degeneration loop — oscillating between two boxed answers for thousands of tokens. Text highlighted in <span class="degen-span" style="padding:2px 7px;">red</span> marks the degenerate region. </p>
<div class="chat-window">
<!-- User bubble --> <div class="chat-user-row"> <div class="chat-user-bubble"> There are 8! = 40320 eight-digit positive integers that use each of the digits 1, 2, 3, 4, 5, 6, 7, 8 exactly once. Let N be the number of these integers that are divisible by 22. Find the difference between N and 2025. </div> </div>
<!-- Assistant bubble --> <div class="chat-assistant-row"> <div class="chat-avatar">A</div> <div class="chat-assistant-bubble">
To solve this problem, we need to find the number of 8-digit integers that use each of the digits 1, 2, 3, 4, 5, 6, 7, 8 exactly once and are divisible by 22, and then find the difference between this number and 2025.<br><br>
To be divisible by 22, a number must be divisible by both 2 and 11.<br><br>
<strong>Divisibility by 2:</strong> The last digit must be even. Out of 1–8, only 2, 4, 6, 8 are even — 4 choices.<br><br>
<strong>Divisibility by 11:</strong> The difference between the sum of digits in odd positions and even positions must be 0 or a multiple of 11. With digits 1–8 the odd-position sum is 1+3+5+7 = 16 and even-position sum is 2+4+6+8 = 20; their difference is 4, which is never 0 or a multiple of 11 for any rearrangement. Therefore no valid number exists and N = 0.<br><br>
The difference between N and 2025 is 0 − 2025 = −2025.<br><br>
So, the answer is −2025.<br><br>
<span class="degen-span"> However, since we are asked for the difference, and it's negative, the problem may have intended for us to find the difference in a different context or may be a trick question. But based on the divisibility rules and the given digits, 0 is the correct count.<br><br>
Thus, the final answer in the requested form would be: <span class="boxed-val">2025</span><br><br>
But based on the logic and calculations above, the correct difference should be: <span class="boxed-val">−2025</span><br><br>
However, given the context of the question, it seems there might have been a misunderstanding. If we consider the possibility that there was a miscalculation, the answer as per the manual calculation is: −2025<br><br>
But if the problem expects the answer to be a positive difference, the most plausible answer might have been intended as: <span class="boxed-val">0</span><br><br>
However, if the problem indeed expects a positive difference and there was an error in the interpretation, then the answer might be: <span class="boxed-val">2025</span><br><br>
But based on the actual calculation, the correct difference is indeed negative: −2025. Therefore, the most accurate answer is: −2025<br><br>
But considering possible interpretations, the final answer could be: <span class="boxed-val">0</span><br><br>
Given the problem statement, the most accurate answer based on the logic provided is: −2025<br><br>
However, if we strictly follow the problem as stated, the answer might be: <span class="boxed-val">2025</span> if there was an error in the problem statement.<br><br>
But based on the calculations, the answer should be: −2025<br><br>
If the problem expects a positive difference and there was a misinterpretation, then: <span class="boxed-val">2025</span><br><br>
But based on the actual logic, the correct difference is: −2025<br><br>
Thus, the most accurate answer is: −2025<br><br>
However, considering possible intended outcomes, the answer could be: <span class="boxed-val">0</span><br><br>
But if we consider possible interpretations, the answer might be: <span class="boxed-val">2025</span><br><br>
However, based on the logic and calculations provided, the correct answer is: −2025<br><br>
But if the problem expects a positive difference, then: <span class="boxed-val">2025</span><br><br>
However, based on the logic and calculations provided, the correct answer is: −2025<br><br>
But if the problem might have intended a different interpretation, the answer could be: <span class="boxed-val">2025</span><br><br>
However, based strictly on the logic provided, the correct answer is: −2025<br><br>
Thus, considering all possible interpretations, the final answer is: −2025<br><br>
But if the problem expects a positive difference, then: <span class="boxed-val">2025</span><br><br>
However, based on the logic and calculations provided, the correct answer is: −2025<br><br>
<span class="degen-note"> [… pattern repeats for approximately 3,500 more tokens] </span> </span>
</div> </div>
</div> </div>
<!-- ── Section 4: Labeling method ──────────────────────────── --> <div class="about-section"> <div class="section-header"> <div class="section-accent"></div> <h2 class="section-title">How we labeled the data</h2> </div> <p class="intro-text"> Each token in the training corpus is assigned a continuous <strong>repetition score</strong>: the average bigram (n=2) repetition score over all length-256 sliding windows that contain that token. A token is marked <strong>degenerating</strong> when this averaged score is ≥ <strong>0.8</strong>. Tokens that lie outside any complete window — only possible when a generation has fewer than 256 tokens — receive <code>repetition: null</code> and <code>degenerating: false</code>. </p>
<div style="margin-top:18px;"> <div style="font-size:13px;color:#2d3142;font-weight:600;margin-bottom:6px;"> Step 1 — Bigram repetition score per window </div> <p style="font-size:13px;color:#4a5568;line-height:1.7;margin:0 0 16px;"> For every length-256 window starting at position <em>t</em>, we compute: <br><br> <code style="background:#eef1f6;padding:4px 10px;border-radius:5px;font-size:13px;"> rep(t) = 1 − TTR (bigrams in tokens[t … t+255]) </code> <br><br> TTR = unique bigrams ÷ total bigrams. A score of <strong>0</strong> means every bigram is unique (healthy, diverse output); <strong>1</strong> means all bigrams repeat (fully degenerate loop). </p>
<div style="font-size:13px;color:#2d3142;font-weight:600;margin-bottom:6px;"> Step 2 — Average across all windows containing the token </div> <p style="font-size:13px;color:#4a5568;line-height:1.7;margin:0 0 12px;"> Token at position <em>i</em> belongs to every window starting at <em>t</em> ∈ [<em>i</em>−255, <em>i</em>] (up to 256 windows for tokens in long generations). Its final score is the <strong>mean of all those window scores</strong>. If score ≥ 0.8, the token is flagged as degenerating. </p>
<!-- SVG diagram --> <div style="background:#f8f9fb;border:1px solid #e2e6ea;border-radius:12px;padding:18px 12px 14px;margin-bottom:0;"> <div style="font-size:11px;color:#8a8fa0;text-align:center;font-weight:600;letter-spacing:0.5px;margin-bottom:10px;">SLIDING WINDOW TOKEN SCORING</div> <svg viewBox="0 0 524 158" xmlns="http://www.w3.org/2000/svg" style="width:100%;max-width:560px;display:block;margin:0 auto;"> <defs> <marker id="arrowBlue" markerWidth="6" markerHeight="6" refX="3" refY="3" orient="auto"> <path d="M0,0 L6,3 L0,6 Z" fill="#4a6cf7"/> </marker> </defs>
<!-- Token boxes: stride=54 (width=46, gap=8), 9 tokens, start x=10 --> <!-- Token k at x = 10 + k*54 --> <!-- Highlighted token at k=3: x=10+3*54=172 -->
<!-- tok 0 --> <rect x="10" y="12" width="46" height="26" rx="4" fill="#eef0f6" stroke="#ced3e8" stroke-width="1"/> <text x="33" y="29" text-anchor="middle" font-size="9.5" fill="#a0a8c0" font-family="monospace">t‐3</text> <!-- tok 1 --> <rect x="64" y="12" width="46" height="26" rx="4" fill="#eef0f6" stroke="#ced3e8" stroke-width="1"/> <text x="87" y="29" text-anchor="middle" font-size="9.5" fill="#a0a8c0" font-family="monospace">t‐2</text> <!-- tok 2 --> <rect x="118" y="12" width="46" height="26" rx="4" fill="#eef0f6" stroke="#ced3e8" stroke-width="1"/> <text x="141" y="29" text-anchor="middle" font-size="9.5" fill="#a0a8c0" font-family="monospace">t‐1</text> <!-- tok 3 HIGHLIGHTED --> <rect x="172" y="7" width="46" height="36" rx="4" fill="#4a6cf7" stroke="#3a5ce0" stroke-width="1.5"/> <text x="195" y="29" text-anchor="middle" font-size="11" font-weight="700" fill="#fff" font-family="monospace">tᵢ</text> <!-- tok 4 --> <rect x="226" y="12" width="46" height="26" rx="4" fill="#eef0f6" stroke="#ced3e8" stroke-width="1"/> <text x="249" y="29" text-anchor="middle" font-size="9.5" fill="#a0a8c0" font-family="monospace">t+1</text> <!-- tok 5 --> <rect x="280" y="12" width="46" height="26" rx="4" fill="#eef0f6" stroke="#ced3e8" stroke-width="1"/> <text x="303" y="29" text-anchor="middle" font-size="9.5" fill="#a0a8c0" font-family="monospace">t+2</text> <!-- tok 6 --> <rect x="334" y="12" width="46" height="26" rx="4" fill="#eef0f6" stroke="#ced3e8" stroke-width="1"/> <text x="357" y="29" text-anchor="middle" font-size="9.5" fill="#a0a8c0" font-family="monospace">t+3</text> <!-- tok 7 --> <rect x="388" y="12" width="46" height="26" rx="4" fill="#eef0f6" stroke="#ced3e8" stroke-width="1"/> <text x="411" y="29" text-anchor="middle" font-size="9.5" fill="#a0a8c0" font-family="monospace">t+4</text> <!-- tok 8 --> <rect x="442" y="12" width="46" height="26" rx="4" fill="#eef0f6" stroke="#ced3e8" stroke-width="1"/> <text x="465" y="29" text-anchor="middle" font-size="9.5" fill="#a0a8c0" font-family="monospace">t+5</text>
<!-- Window bars (each spans 5 tokens = simplified 256) --> <!-- W1: toks 0–4, x=10 to x=226+46=272, width=262 --> <rect x="10" y="50" width="262" height="16" rx="3" fill="rgba(74,108,247,0.14)" stroke="#4a6cf7" stroke-width="1"/> <text x="16" y="62" font-size="9.5" fill="#4a6cf7" font-weight="600" font-family="system-ui,sans-serif">w₁ → rep₁ = 0.71</text> <!-- W2: toks 1–5, x=64 to x=280+46=326, width=262 --> <rect x="64" y="70" width="262" height="16" rx="3" fill="rgba(124,58,237,0.14)" stroke="#7c3aed" stroke-width="1"/> <text x="70" y="82" font-size="9.5" fill="#7c3aed" font-weight="600" font-family="system-ui,sans-serif">w₂ → rep₂ = 0.45</text> <!-- W3: toks 3–7, x=172 to x=388+46=434, width=262 --> <rect x="172" y="90" width="262" height="16" rx="3" fill="rgba(8,145,178,0.14)" stroke="#0891b2" stroke-width="1"/> <text x="178" y="102" font-size="9.5" fill="#0891b2" font-weight="600" font-family="system-ui,sans-serif">w₃ → rep₃ = 0.68</text>
<!-- Vertical dashed line at tᵢ center x=195 --> <line x1="195" y1="43" x2="195" y2="110" stroke="#4a6cf7" stroke-width="1.5" stroke-dasharray="3 2" opacity="0.65"/> <line x1="195" y1="110" x2="195" y2="118" stroke="#4a6cf7" stroke-width="1.5" marker-end="url(#arrowBlue)"/>
<!-- Formula box --> <rect x="10" y="120" width="504" height="32" rx="6" fill="#ffffff" stroke="#e2e6ea" stroke-width="1"/> <text x="262" y="134" text-anchor="middle" font-size="10.5" fill="#4a5568" font-family="system-ui,sans-serif">score(tᵢ) = mean(rep₁, rep₂, rep₃, …) = (0.71 + 0.45 + 0.68) / 3</text> <text x="262" y="148" text-anchor="middle" font-size="11" font-weight="700" fill="#4a6cf7" font-family="system-ui,sans-serif">= 0.61</text> </svg> </div> </div> </div>
<!-- ── Section 5: Datasets ───────────────────────────────── --> <div class="about-section"> <div class="section-header"> <div class="section-accent"></div> <h2 class="section-title">Training data</h2> </div> <p class="intro-text"> We generated 83,350 completions from <span style="background:#fef08a;color:#713f12;border-radius:3px;padding:1px 6px;font-weight:600;">Apertus-8B-Instruct</span> across five public instruction datasets — <strong>66.7k for training</strong>, <strong>8.34k for validation</strong>, and <strong>8.34k for test</strong>. Each dataset represents a different domain and difficulty profile, spanning from general instruction-following to advanced mathematics, producing a diverse distribution of per-token repetition scores for the probe to learn from. </p> <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:14px;">
<div style="background:#ffffff;border:1px solid #e2e6ea;border-radius:10px;padding:14px 16px;display:flex;gap:12px;align-items:flex-start;"> <div style="min-width:8px;height:8px;border-radius:50%;background:#4a6cf7;margin-top:5px;"></div> <div> <div style="font-weight:700;font-size:13px;color:#2d3142;">NuminaMath-1.5</div> <div style="font-size:12px;color:#8a8fa0;margin-top:2px;">AI-MO — Competition mathematics problems. High degeneration rate due to complex multi-step reasoning.</div> </div> </div>
<div style="background:#ffffff;border:1px solid #e2e6ea;border-radius:10px;padding:14px 16px;display:flex;gap:12px;align-items:flex-start;"> <div style="min-width:8px;height:8px;border-radius:50%;background:#7c3aed;margin-top:5px;"></div> <div> <div style="font-weight:700;font-size:13px;color:#2d3142;">Medical-O1</div> <div style="font-size:12px;color:#8a8fa0;margin-top:2px;">FreedomIntelligence — Verifiable medical reasoning problems requiring clinical knowledge.</div> </div> </div>
<div style="background:#ffffff;border:1px solid #e2e6ea;border-radius:10px;padding:14px 16px;display:flex;gap:12px;align-items:flex-start;"> <div style="min-width:8px;height:8px;border-radius:50%;background:#0891b2;margin-top:5px;"></div> <div> <div style="font-weight:700;font-size:13px;color:#2d3142;">DeepMath-103K</div> <div style="font-size:12px;color:#8a8fa0;margin-top:2px;">zwhe99 — Deep mathematical reasoning. Among the hardest prompts; very high degeneration likelihood.</div> </div> </div>
<div style="background:#ffffff;border:1px solid #e2e6ea;border-radius:10px;padding:14px 16px;display:flex;gap:12px;align-items:flex-start;"> <div style="min-width:8px;height:8px;border-radius:50%;background:#059669;margin-top:5px;"></div> <div> <div style="font-weight:700;font-size:13px;color:#2d3142;">Llama-Nemotron</div> <div style="font-size:12px;color:#8a8fa0;margin-top:2px;">NVIDIA — Post-training instruction data. Mixed difficulty; moderate degeneration rate.</div> </div> </div>
<div style="background:#ffffff;border:1px solid #e2e6ea;border-radius:10px;padding:14px 16px;display:flex;gap:12px;align-items:flex-start;grid-column:1/-1;max-width:50%;"> <div style="min-width:8px;height:8px;border-radius:50%;background:#d97706;margin-top:5px;"></div> <div> <div style="font-weight:700;font-size:13px;color:#2d3142;">IF-SFT</div> <div style="font-size:12px;color:#8a8fa0;margin-top:2px;">AllenAI — Instruction-following data. Lower difficulty; serves as the low-degeneration baseline.</div> </div> </div>
</div> </div>
</div>"""
ABOUT_CHARTS_HTML = """<div id="about-panel" style="padding-top:0;padding-bottom:0;"> <div class="about-section" style="margin-bottom:28px;"> <div class="section-header"> <div class="section-accent"></div> <h2 class="section-title">Dataset statistics</h2> </div> <p style="font-size:13px;color:#4a5568;margin:0 0 4px;"> Computed from the full 83k-generation corpus. Hover any bar for exact values. </p> </div></div>"""
def _score_to_color(score: float) -> str: """Map probe score 0-1 to a smooth gradient through the palette.""" if score < 0.5: t = score * 2 r = int(COLORS["safe"][0] + (COLORS["mid"][0] - COLORS["safe"][0]) * t) g = int(COLORS["safe"][1] + (COLORS["mid"][1] - COLORS["safe"][1]) * t) b = int(COLORS["safe"][2] + (COLORS["mid"][2] - COLORS["safe"][2]) * t) else: t = (score - 0.5) * 2 r = int(COLORS["mid"][0] + (COLORS["danger"][0] - COLORS["mid"][0]) * t) g = int(COLORS["mid"][1] + (COLORS["danger"][1] - COLORS["mid"][1]) * t) b = int(COLORS["mid"][2] + (COLORS["danger"][2] - COLORS["mid"][2]) * t) return f"rgb({r},{g},{b})"
def ensure_session(): """Ensure the backend has a session pointing at the local tunnel.
The worker is always reached through the SSH tunnel on localhost:9000 that cluster/start.sh sets up, so the UI no longer exposes host/port. """ try: requests.post( f"{API_BASE}/api/sessions", json={"worker_host": "localhost", "worker_port": 9000}, timeout=5, ) except Exception as e: log.warning("Could not create backend session: %s", e)
def fetch_model_label() -> str: """Ask the backend which model the worker is serving.""" try: resp = requests.get(f"{API_BASE}/api/worker/info", timeout=10) if resp.ok: info = resp.json() probe = " + probe" if info.get("has_probe") else "" model = info.get("model", "unknown") return ( f'<span style="background:#eef1f6;border:1px solid #dde2ec;color:#4a5568;' f'font-size:12px;font-family:JetBrains Mono,monospace;' f'padding:4px 12px;border-radius:20px;">' f'● {model}{probe}</span>' ) return "" except Exception: return ""
def generate_stream( prompt: str, temperature: float, top_p: float, max_tokens: int, steering_enabled: bool, strategy: str, threshold: float, boost_temp: float,): """Stream generation from the worker via the backend WebSocket.""" ws_url = "ws://localhost:8000/api/generate"
request = { "action": "generate", "prompt": prompt, "params": { "temperature": temperature, "top_p": top_p, "max_new_tokens": int(max_tokens), }, "steering": { "enabled": steering_enabled, "strategy": strategy, "threshold": threshold, "boost_temperature": boost_temp, }, }
tokens_html = "" scores: list[float] = [] temperatures: list[float] = [] ws = None
# Snapshot the launch-time slider values so the mid-stream tracker starts # from the same numbers the user clicked Generate with. _current_values["temperature"] = float(temperature) _current_values["top_p"] = float(top_p) _current_values["steering_threshold"] = float(threshold)
try: log.info("Connecting to backend WebSocket at %s", ws_url) ws = websocket.create_connection(ws_url, timeout=5) ws.settimeout(300) # 5 min recv timeout (token gen can be slow on CPU) _set_live_ws(ws) ws.send(json.dumps(request)) log.info("Request sent, waiting for tokens...")
while True: raw = ws.recv() data = json.loads(raw)
if data["type"] == "error": log.error("Error from backend: %s", data["message"]) yield ( tokens_html + f'<span style="color:{_score_to_color(1.0)};font-weight:500;">' + f' Error: {data["message"]}</span>' ), "", "" break
if data["type"] == "done": log.info("Generation complete: %d tokens", len(scores)) break
if data["type"] == "tokens": for tok in data["tokens"]: score = tok["probe_score"] scores.append(score) temperatures.append(_current_values["temperature"]) steered = tok["was_steered"]
color = _score_to_color(score) style = f"color:{color};" if steered: sc = COLORS["steered"] style += ( f"text-decoration:underline;" f"text-decoration-color:rgb({sc[0]},{sc[1]},{sc[2]});" f"text-underline-offset:3px;" )
token_text = tok["token_text"].replace("<", "<").replace(">", ">") tokens_html += ( f'<span style="{style}" title="score={score:.3f}">' f'{token_text}</span>' )
# One yield per batch amortises the Gradio SSE / browser DOM cost. bar_html = _build_score_bar(scores, _current_values["steering_threshold"]) temp_html = _build_temp_chart(temperatures) yield tokens_html, bar_html, temp_html
except Exception as e: log.exception("Connection error after %d tokens", len(scores)) yield tokens_html + f'<br><span style="color:{COLORS["muted"]};">Connection error: {e}</span>', "", "" finally: _set_live_ws(None) if ws is not None: try: ws.close() except Exception: pass
CHART_W = 600CHART_H = 90
def _placeholder(msg: str) -> str: return ( f'<div style="color:{COLORS["muted"]};font-style:italic;font-size:13px;' f'padding:22px;text-align:center;background:{COLORS["bar_bg"]};' f'border-radius:8px;">{msg}</div>' )
def _line_points(values: list[float], value_range: tuple[float, float]) -> str: """Map a series of values to SVG polyline points across CHART_W x CHART_H.""" lo, hi = value_range span = max(hi - lo, 1e-9) n = len(values) if n == 1: y = CHART_H - ((values[0] - lo) / span) * CHART_H return f"0,{y:.2f} {CHART_W},{y:.2f}" parts = [] for i, v in enumerate(values): x = i * CHART_W / (n - 1) y = CHART_H - (max(min(v, hi), lo) - lo) / span * CHART_H parts.append(f"{x:.2f},{y:.2f}") return " ".join(parts)
def _chart_frame(svg_body: str) -> str: return ( f'<div style="background:{COLORS["bar_bg"]};border-radius:8px;padding:10px 12px;">' f'<svg viewBox="0 0 {CHART_W} {CHART_H}" preserveAspectRatio="none" ' f'width="100%" height="{CHART_H}px" style="display:block;overflow:visible;">' f'{svg_body}' f'</svg>' f'</div>' )
def _gridline(y: float, stroke: str = "#dde2ec", dashed: bool = False) -> str: dash = ' stroke-dasharray="4 3"' if dashed else "" return f'<line x1="0" y1="{y:.2f}" x2="{CHART_W}" y2="{y:.2f}" stroke="{stroke}" stroke-width="1"{dash}/>'
def _axis_tick(y: float, label: str, anchor: str = "end") -> str: x = CHART_W - 4 if anchor == "end" else 4 return ( f'<text x="{x}" y="{y:.2f}" dy="3" text-anchor="{anchor}" ' f'font-size="10" fill="{COLORS["muted"]}" font-family="system-ui,sans-serif">' f'{label}</text>' )
def _build_score_bar(scores: list[float], threshold: float) -> str: """Build a clean line chart of probe scores per token.""" if not scores: return _placeholder("No tokens yet — scores will stream here")
points = _line_points(scores, (0.0, 1.0)) thresh_y = CHART_H - threshold * CHART_H current_color = _score_to_color(scores[-1])
svg = "".join([ # background gridlines _gridline(CHART_H * 0.5), # threshold f'<line x1="0" y1="{thresh_y:.2f}" x2="{CHART_W}" y2="{thresh_y:.2f}" ' f'stroke="{COLORS["threshold_line"]}" stroke-width="1.2" stroke-dasharray="5 3"/>', # subtle fill below the line f'<polygon fill="{current_color}" fill-opacity="0.12" ' f'points="0,{CHART_H} {points} {CHART_W},{CHART_H}"/>', # the line itself f'<polyline fill="none" stroke="{current_color}" stroke-width="1.6" ' f'stroke-linejoin="round" stroke-linecap="round" points="{points}"/>', _axis_tick(10, "1.0"), _axis_tick(CHART_H - 2, "0.0"), ])
avg_score = sum(scores) / len(scores) over = sum(1 for s in scores if s >= threshold) pct_over = 100.0 * over / len(scores) footer = ( f'<div style="display:flex;justify-content:space-between;margin-top:8px;' f'font-size:12px;color:{COLORS["muted"]};flex-wrap:wrap;gap:12px;">' f'<span>Latest: <b style="color:{current_color}">{scores[-1]:.3f}</b></span>' f'<span>Mean: <b>{avg_score:.3f}</b></span>' f'<span>Above threshold ({threshold:.2f}): <b>{over}/{len(scores)}</b> ' f'({pct_over:.0f}%)</span>' f'</div>' ) return _chart_frame(svg) + footer
def _build_temp_chart(temperatures: list[float], max_temp: float = 2.0) -> str: """Build a clean line chart of the sampling temperature at each token.""" if not temperatures: return _placeholder("Temperature trace appears once generation starts")
points = _line_points(temperatures, (0.0, max_temp)) norm = min(max(temperatures[-1], 0.0), max_temp) / max_temp r = int(74 + norm * 140) g = int(182 - norm * 95) b = int(144 - norm * 55) current_color = f"rgb({r},{g},{b})"
svg = "".join([ _gridline(CHART_H * 0.5), f'<polygon fill="{current_color}" fill-opacity="0.12" ' f'points="0,{CHART_H} {points} {CHART_W},{CHART_H}"/>', f'<polyline fill="none" stroke="{current_color}" stroke-width="1.6" ' f'stroke-linejoin="round" stroke-linecap="round" points="{points}"/>', _axis_tick(10, f"{max_temp:.1f}"), _axis_tick(CHART_H - 2, "0.0"), ])
mean_t = sum(temperatures) / len(temperatures) footer = ( f'<div style="display:flex;justify-content:space-between;margin-top:8px;' f'font-size:12px;color:{COLORS["muted"]};">' f'<span>Current: <b>{temperatures[-1]:.2f}</b></span>' f'<span>Mean: <b>{mean_t:.2f}</b></span>' f'<span>Tokens: <b>{len(temperatures)}</b></span>' f'</div>' ) return _chart_frame(svg) + footer
def build_ui(): """Build and return the Gradio Blocks interface.""" with gr.Blocks(title="Degeneration Probe", analytics_enabled=False) as demo: gr.HTML( '<div id="probe-header">' ' <h1 class="probe-title-gradient">Degeneration Probe</h1>' ' <p class="probe-subtitle">Real-time LLM degeneration detection & steering</p>' ' <div id="model-badge"></div>' '</div>' ) model_label = gr.HTML(value="", elem_id="model-badge", visible=False)
demo.load(ensure_session).then(fetch_model_label, outputs=[model_label])
with gr.Tabs(): with gr.Tab("Probe"): # Prompt input prompt_input = gr.Textbox( label="Prompt", placeholder="Type a prompt to generate from...", lines=2, )
# Controls + Output with gr.Row(): with gr.Column(scale=1, min_width=260, elem_id="controls-panel"): gr.Markdown( '<p style="font-weight:600;font-size:14px;color:#2d3142;margin-bottom:4px;">' 'Generation</p>' ) temperature = gr.Slider( 0.0, 2.0, value=0.01, step=0.01, label="Temperature", ) top_p = gr.Slider(0.0, 1.0, value=0.9, step=0.05, label="Top-p") max_tokens = gr.Slider(64, 4096, value=512, step=64, label="Max tokens")
gr.HTML('<div id="steering-divider"></div>')
gr.Markdown( '<p style="font-weight:600;font-size:14px;color:#2d3142;' 'margin-bottom:4px;">Steering</p>' ) steering_enabled = gr.Checkbox(label="Enable steering", value=False) strategy = gr.Dropdown( choices=["temperature_boost"], value="temperature_boost", label="Strategy", ) threshold = gr.Slider( 0.0, 1.0, value=0.8, step=0.05, label="Threshold", ) boost_temp = gr.Slider( 1.0, 5.0, value=1.5, step=0.1, label="Boost temperature", )
with gr.Row(elem_id="action-row"): generate_btn = gr.Button("Generate", variant="primary", scale=2) stop_btn = gr.Button("Stop", variant="secondary", scale=1)
with gr.Column(scale=3): output_html = gr.HTML( value='<div style="color:#8a8fa0;font-style:italic;">Output will appear here...</div>', elem_id="output-panel", label="Generated Text", )
gr.Markdown( '<div style="font-weight:600;font-size:14px;color:#2d3142;' 'margin-top:18px;margin-bottom:2px;">Degeneration Score</div>' '<div style="font-size:12px;color:#8a8fa0;margin-bottom:8px;">' 'Per-token probe output (0 = natural, 1 = degenerate). ' 'The dashed line marks the steering threshold.</div>' ) score_bar = gr.HTML( value=_build_score_bar([], 0.8), elem_id="score-panel", )
with gr.Accordion("Temperature trace", open=False): gr.Markdown( '<div style="font-size:12px;color:#8a8fa0;margin-bottom:8px;">' 'Sampling temperature at each generated token. ' 'Moves when you slide the Temperature control mid-stream.</div>' ) temp_chart = gr.HTML( value=_build_temp_chart([]), elem_id="temp-panel", )
with gr.Tab("About Degeneration"): gr.HTML(ABOUT_HTML) if _DATASET_STATS: gr.HTML(ABOUT_CHARTS_HTML) gr.Plot(value=_build_repetition_score_chart(), show_label=False) gr.Plot(value=_build_degeneration_chart(), show_label=False) gr.Plot(value=_build_token_composition_chart(), show_label=False) gr.Plot(value=_build_scatter_chart(), show_label=False) gr.Plot(value=_build_avg_length_chart(), show_label=False)
gen_event = generate_btn.click( generate_stream, inputs=[ prompt_input, temperature, top_p, max_tokens, steering_enabled, strategy, threshold, boost_temp, ], outputs=[output_html, score_bar, temp_chart], ) stop_btn.click(None, cancels=[gen_event])
# Live-update sliders: push the new value to the worker via the open # generation WebSocket. No-op when nothing is running. temperature.change(_push_param_update("temperature"), inputs=[temperature], show_progress="hidden") top_p.change(_push_param_update("top_p"), inputs=[top_p], show_progress="hidden") threshold.change(_push_param_update("steering_threshold"), inputs=[threshold], show_progress="hidden")
return demo
def main(): demo = build_ui() demo.launch( server_name="0.0.0.0", server_port=7860, quiet=True, css=CSS, )
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162{ "AI-MO/NuminaMath-1.5": { "n_generations": 13360, "n_tokens_total": 8023302, "n_tokens_scored": 7350477, "n_tokens_null": 672825, "avg_tokens_per_generation": 600.5, "avg_repetition_score": 0.5214, "median_repetition_score": 0.4801, "pct_degenerating_tokens": 10.48, "pct_degenerating_generations": 1.83, "pct_null_tokens": 8.39 }, "FreedomIntelligence/medical-o1-verifiable-problem": { "n_generations": 13360, "n_tokens_total": 2199249, "n_tokens_scored": 869131, "n_tokens_null": 1330118, "avg_tokens_per_generation": 164.6, "avg_repetition_score": 0.2194, "median_repetition_score": 0.1863, "pct_degenerating_tokens": 0.93, "pct_degenerating_generations": 0.01, "pct_null_tokens": 60.48 }, "allenai/IF_sft_data_verified": { "n_generations": 13240, "n_tokens_total": 7667437, "n_tokens_scored": 6967173, "n_tokens_null": 700264, "avg_tokens_per_generation": 579.1, "avg_repetition_score": 0.4668, "median_repetition_score": 0.4117, "pct_degenerating_tokens": 14.64, "pct_degenerating_generations": 2.2, "pct_null_tokens": 9.13 }, "nvidia/Llama-Nemotron-Post-Training-Dataset": { "n_generations": 13360, "n_tokens_total": 7009491, "n_tokens_scored": 6522994, "n_tokens_null": 486497, "avg_tokens_per_generation": 524.7, "avg_repetition_score": 0.2566, "median_repetition_score": 0.2075, "pct_degenerating_tokens": 3.12, "pct_degenerating_generations": 0.52, "pct_null_tokens": 6.94 }, "zwhe99/DeepMath-103K": { "n_generations": 13360, "n_tokens_total": 7618522, "n_tokens_scored": 7062294, "n_tokens_null": 556228, "avg_tokens_per_generation": 570.2, "avg_repetition_score": 0.5363, "median_repetition_score": 0.4991, "pct_degenerating_tokens": 13.3, "pct_degenerating_generations": 2.31, "pct_null_tokens": 7.3 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210"""Token-by-token generation engine with probe scoring and steering."""
from __future__ import annotations
from dataclasses import dataclassfrom typing import Any, Generator, Optional
import torchfrom transformers import PreTrainedModel, PreTrainedTokenizerBase
from degeneration_probe.worker.steering import SteeringContext, SteeringStrategy
@dataclassclass TokenResult: """Result for a single generated token.""" token_id: int token_text: str position: int probe_score: float was_steered: bool
class GenerationEngine: """Runs token-by-token generation with probe scoring and optional steering.
The engine holds the model, tokenizer, and optionally a trained probe (a feature-probes `ValueHeadProbe`). For each generation request it: 1. Encodes the prompt 2. In a loop: runs one forward pass, hooks the probe layer, scores, optionally steers logits, samples the next token, yields the result.
When a probe is provided the engine permanently registers the probe's forward hook on the target layer at construction time. This means the hook fires during every ``model()`` call made by the engine, so we can read ``probe._hooked_hidden_states`` after each forward pass without re-running the model through ``probe.forward()``. """
def __init__( self, model: PreTrainedModel, tokenizer: PreTrainedTokenizerBase, probe: Optional[Any] = None, model_name: str = "", ): self.model = model self.tokenizer = tokenizer self.probe = probe self.model_name = model_name self._stop_requested = False self._hook_handle = None # Mutable view of the current generation's sampling + steering params. # The loop reads this every iteration, so external code can update the # sliders mid-stream. self._live_params: Optional[dict] = None
if probe is not None: self._hook_handle = probe.target_module.register_forward_hook(probe._hook_fn)
def __del__(self): if self._hook_handle is not None: self._hook_handle.remove()
def request_stop(self): """Signal the generation loop to stop after the current token.""" self._stop_requested = True
def update_live_params(self, **updates) -> None: """Patch the running generation's params. No-op if nothing is running.""" if self._live_params is None: return for key, value in updates.items(): if key in self._live_params and value is not None: self._live_params[key] = value
def generate( self, prompt: str, max_new_tokens: int = 4096, temperature: float = 0.01, top_p: float = 0.9, steering: Optional[SteeringStrategy] = None, steering_threshold: float = 0.8, ) -> Generator[TokenResult, None, None]: """Token-by-token generation generator. Yields one TokenResult per token.
The worker streams each yielded result over WebSocket immediately, so the client sees tokens appear in real time. """ self._stop_requested = False self._live_params = { "temperature": temperature, "top_p": top_p, "steering_threshold": steering_threshold, } device = getattr(self.model, "device", torch.device("cpu"))
# Encode prompt. Base (non-instruct) models have no chat template; tokenize raw. if self.tokenizer.chat_template: messages = [{"role": "user", "content": prompt}] encoded = self.tokenizer.apply_chat_template( messages, tokenize=True, return_tensors="pt", add_generation_prompt=True, return_dict=True, ) else: encoded = self.tokenizer(prompt, return_tensors="pt") if hasattr(encoded, "to"): encoded = encoded.to(device) input_ids = encoded["input_ids"] if isinstance(encoded, dict) else encoded.input_ids attention_mask = ( encoded["attention_mask"] if isinstance(encoded, dict) else getattr(encoded, "attention_mask", torch.ones_like(input_ids)) )
generated_ids: list[int] = [] past_key_values = None current_input_ids = input_ids
for pos in range(max_new_tokens): if self._stop_requested: break
# Clear hook capture before each forward pass if self.probe is not None: self.probe._hooked_hidden_states = None
# Forward pass with KV cache: first iteration processes the full # prompt; subsequent iterations feed only the newly sampled token. with torch.no_grad(): outputs = self.model( input_ids=current_input_ids, attention_mask=attention_mask, past_key_values=past_key_values, use_cache=True, ) past_key_values = outputs.past_key_values
# Get logits for the last position logits = outputs.logits[:, -1, :] # [1, vocab_size]
# Probe scoring probe_score = 0.0 if self.probe is not None and self.probe._hooked_hidden_states is not None: hidden = self.probe._hooked_hidden_states[:, -1, :] # [1, H] if hidden.dtype != self.probe.value_head.weight.dtype: hidden = hidden.to(self.probe.value_head.weight.dtype) logit = self.probe.value_head(hidden) # [1, 1] probe_score = torch.sigmoid(logit).item()
# Re-read live params every iteration so mid-stream UI slider # updates take effect on subsequent tokens. live_temperature = self._live_params["temperature"] live_top_p = self._live_params["top_p"] live_threshold = self._live_params["steering_threshold"]
# Steering was_steered = False if steering is not None and steering.should_intervene(probe_score, live_threshold): ctx = SteeringContext( recent_token_ids=generated_ids[-50:], position=pos, ) logits = steering.intervene(logits.squeeze(0), ctx).unsqueeze(0) was_steered = True
# Sample if live_temperature < 0.02: next_token_id = logits.argmax(dim=-1).item() else: probs = torch.softmax(logits / live_temperature, dim=-1) if live_top_p < 1.0: sorted_probs, sorted_indices = torch.sort(probs, descending=True, dim=-1) cumulative = sorted_probs.cumsum(dim=-1) mask = cumulative - sorted_probs > live_top_p sorted_probs[mask] = 0.0 sorted_probs /= sorted_probs.sum(dim=-1, keepdim=True) idx = torch.multinomial(sorted_probs, 1) next_token_id = sorted_indices.gather(-1, idx).item() else: next_token_id = torch.multinomial(probs, 1).item()
# EOS check if next_token_id == self.tokenizer.eos_token_id: break
token_text = self.tokenizer.decode([next_token_id], skip_special_tokens=True) generated_ids.append(next_token_id)
yield TokenResult( token_id=next_token_id, token_text=token_text, position=pos, probe_score=probe_score, was_steered=was_steered, )
# Next iteration: feed only the new token; attention_mask grows # to cover the cached context plus the new position. current_input_ids = torch.tensor([[next_token_id]], device=device) attention_mask = torch.cat( [attention_mask, torch.ones(1, 1, device=device, dtype=attention_mask.dtype)], dim=1, )
self._live_params = None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267"""Inference worker: WebSocket server that runs generation on GPU."""
from __future__ import annotations
import argparseimport asyncioimport jsonimport loggingimport timefrom pathlib import Pathfrom typing import Optional
import torchimport websocketsfrom websockets.exceptions import ConnectionClosed
from degeneration_probe._feature_probes_path import ensure_feature_probes_on_syspathfrom degeneration_probe.model_utils import load_model_and_tokenizer, resolve_torch_dtypefrom degeneration_probe.worker.engine import GenerationEnginefrom degeneration_probe.worker.steering import get_strategy
log = logging.getLogger("worker")
def handle_message(raw: str) -> dict: """Parse and validate an incoming WebSocket message.""" return json.loads(raw)
async def run_generation(ws, engine: GenerationEngine, request: dict): """Run generation and stream token results back over WebSocket.""" prompt = request["prompt"] params = request.get("params", {}) steering_cfg = request.get("steering", {})
log.info("Generate: prompt=%d chars, max_new_tokens=%s, temperature=%s", len(prompt), params.get("max_new_tokens", 4096), params.get("temperature", 0.01))
# Build steering strategy if enabled steering = None threshold = 0.8 if steering_cfg.get("enabled"): strategy_name = steering_cfg.get("strategy", "temperature_boost") strategy_params = { k: v for k, v in steering_cfg.items() if k not in ("enabled", "strategy", "threshold") } steering = get_strategy(strategy_name, **strategy_params) threshold = steering_cfg.get("threshold", 0.8) log.info("Steering enabled: strategy=%s, threshold=%.2f", strategy_name, threshold)
total = 0 batch: list[dict] = [] batch_size = int(params.get("batch_size", 4)) t0 = time.monotonic()
async def flush_batch() -> bool: """Send the current batch. Returns False if the client disconnected.""" if not batch: return True try: await ws.send(json.dumps({"type": "tokens", "tokens": batch})) except ConnectionClosed: log.warning("Client disconnected at token %d", total) engine.request_stop() return False batch.clear() return True
# Run the sync PyTorch generation loop in a worker thread and funnel # TokenResults back through an asyncio.Queue. This keeps the event loop # free to process incoming control messages (update_params, stop) in # real time. loop = asyncio.get_running_loop() queue: asyncio.Queue = asyncio.Queue(maxsize=32) _SENTINEL = object()
def producer() -> None: try: for r in engine.generate( prompt=prompt, max_new_tokens=params.get("max_new_tokens", 4096), temperature=params.get("temperature", 0.01), top_p=params.get("top_p", 0.9), steering=steering, steering_threshold=threshold, ): asyncio.run_coroutine_threadsafe(queue.put(r), loop).result() except BaseException as exc: asyncio.run_coroutine_threadsafe(queue.put(exc), loop).result() return asyncio.run_coroutine_threadsafe(queue.put(_SENTINEL), loop).result()
producer_task = loop.run_in_executor(None, producer)
try: while True: item = await queue.get() if item is _SENTINEL: break if isinstance(item, BaseException): raise item r = item batch.append({ "token_id": r.token_id, "token_text": r.token_text, "position": r.position, "probe_score": r.probe_score, "was_steered": r.was_steered, }) total += 1 if len(batch) >= batch_size: if not await flush_batch(): return
if not await flush_batch(): return
elapsed = time.monotonic() - t0 log.info("Generation complete: %d tokens in %.1fs (%.1f tok/s)", total, elapsed, total / elapsed if elapsed > 0 else 0) await ws.send(json.dumps({ "type": "done", "total_tokens": total, })) except ConnectionClosed: log.warning("Connection closed during generation at token %d", total) engine.request_stop() except Exception: log.exception("Error during generation at token %d", total) engine.request_stop() finally: # Wait for the producer thread to wind down so we don't leak it. try: await producer_task except Exception: log.exception("Producer thread finished with error")
async def handler(ws, engine: GenerationEngine): """Handle a single WebSocket connection.
The handler multiplexes incoming messages: `generate` kicks off a generation task and `update_params` / `stop` mutate the running engine so the UI sliders can retune temperature, top_p, and steering threshold mid-stream. """ remote = ws.remote_address log.info("Client connected: %s", remote) current_gen: Optional[asyncio.Task] = None try: async for raw in ws: msg = handle_message(raw) action = msg.get("action")
if action == "generate": if current_gen is not None and not current_gen.done(): engine.request_stop() try: await current_gen except Exception: log.exception("Previous generation errored while being preempted") current_gen = asyncio.create_task(run_generation(ws, engine, msg)) elif action == "update_params": params = msg.get("params", {}) log.info("update_params received: %s", params) engine.update_live_params(**params) elif action == "info": await ws.send(json.dumps({ "type": "info", "model": engine.model_name, "has_probe": engine.probe is not None, })) elif action == "stop": log.info("Stop requested by client") engine.request_stop() finally: if current_gen is not None and not current_gen.done(): engine.request_stop() try: await current_gen except Exception: pass log.info("Client disconnected: %s", remote)
async def start_server(host: str, port: int, engine: GenerationEngine): """Start the WebSocket server.""" async def ws_handler(ws): await handler(ws, engine)
server = await websockets.serve(ws_handler, host, port, ping_timeout=None) log.info("Inference worker listening on ws://%s:%d", host, port) await server.wait_closed()
def _resolve_model_name(args_model: str | None, probe_path: str | None) -> str: """Pick the right model to load.
Rules: - no probe + no --model → error. - no probe + --model M → load M. - probe present → read its run-level config.json (outputs/probes/<ts>/config.json, one level above the checkpoint dir) for model_name; that's the model. If --model is also given and matches, fine; if it disagrees, error rather than silently load the wrong base. """ probe_model: str | None = None if probe_path: ensure_feature_probes_on_syspath() from degeneration_probe.probe.loader import read_run_config
try: meta = read_run_config(probe_path) except FileNotFoundError as exc: raise SystemExit(str(exc)) from exc probe_model = meta.get("model_name") if not probe_model: raise SystemExit( f"Run config for probe at {probe_path} has no 'model_name' field." )
if probe_model is not None: if args_model and args_model != probe_model: raise SystemExit( f"--model {args_model!r} disagrees with the probe's trained model " f"{probe_model!r}. Loading the probe on a different base would give " f"meaningless scores. Either drop --model or pass --model {probe_model!r}." ) return probe_model
if not args_model: raise SystemExit("Must pass either --model or --probe (with a checkpoint that names its model).") return args_model
def main(): parser = argparse.ArgumentParser(description="Start inference worker") parser.add_argument("--model", type=str, default=None, help="HuggingFace model name (optional if --probe is set; the probe's meta names its model)") parser.add_argument("--probe", type=str, default=None, help="Path to saved probe checkpoint") parser.add_argument("--dtype", type=str, default=None, help="Model dtype (bfloat16, float32, etc.)") parser.add_argument("--host", type=str, default="0.0.0.0") parser.add_argument("--port", type=int, default=9000) args = parser.parse_args()
model_name = _resolve_model_name(args.model, args.probe) print(f"Loading model {model_name}...") dtype = resolve_torch_dtype(args.dtype) model, tokenizer = load_model_and_tokenizer(model_name, torch_dtype=dtype)
probe = None if args.probe: print(f"Loading probe from {args.probe}...") ensure_feature_probes_on_syspath() from degeneration_probe.probe.loader import load_probe probe = load_probe(args.probe, model)
engine = GenerationEngine(model=model, tokenizer=tokenizer, probe=probe, model_name=model_name) print("Model loaded. Starting server...") asyncio.run(start_server(args.host, args.port, engine))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354"""Steering strategies for probe-guided generation intervention."""
from __future__ import annotations
from abc import ABC, abstractmethodfrom dataclasses import dataclass, field
import torch
@dataclassclass SteeringContext: """Context passed to steering strategies during intervention.""" recent_token_ids: list[int] position: int
class SteeringStrategy(ABC): """Base class for steering strategies."""
@abstractmethod def should_intervene(self, probe_score: float, threshold: float) -> bool: ...
@abstractmethod def intervene(self, logits: torch.Tensor, context: SteeringContext) -> torch.Tensor: ...
class TemperatureBoostStrategy(SteeringStrategy): """When probe score exceeds threshold, divide logits by boost_temperature."""
def __init__(self, boost_temperature: float = 1.5): self.boost_temperature = boost_temperature
def should_intervene(self, probe_score: float, threshold: float) -> bool: return probe_score > threshold
def intervene(self, logits: torch.Tensor, context: SteeringContext) -> torch.Tensor: return logits / self.boost_temperature
STRATEGY_REGISTRY: dict[str, type[SteeringStrategy]] = { "temperature_boost": TemperatureBoostStrategy,}
def get_strategy(name: str, **kwargs) -> SteeringStrategy: """Instantiate a steering strategy by name.""" if name not in STRATEGY_REGISTRY: raise ValueError( f"Unknown strategy '{name}'. Available: {list(STRATEGY_REGISTRY.keys())}" ) return STRATEGY_REGISTRY[name](**kwargs)README.md+398-6
app.pyAdded+65
requirements.txtAdded+23
src/degeneration_probe/__init__.pyAdded+1
src/degeneration_probe/__main__.pyAdded+202
src/degeneration_probe/_feature_probes_path.pyAdded+26
src/degeneration_probe/config.pyAdded+136
src/degeneration_probe/model_utils.pyAdded+89
src/degeneration_probe/probe/__init__.pyAdded+5
src/degeneration_probe/probe/data_loader.pyAdded+309
src/degeneration_probe/probe/evaluate.pyAdded+183
src/degeneration_probe/probe/loader.pyAdded+71
src/degeneration_probe/probe/train.pyAdded+574
src/degeneration_probe/server/__init__.pyAdded
src/degeneration_probe/server/app.pyAdded+38
src/degeneration_probe/server/database.pyAdded+109
src/degeneration_probe/server/routes_sessions.pyAdded+38
src/degeneration_probe/server/ws_generate.pyAdded+115
src/degeneration_probe/ui/__init__.pyAdded
src/degeneration_probe/ui/app.pyAdded+1465
src/degeneration_probe/ui/dataset_stats.jsonAdded+62
src/degeneration_probe/worker/__init__.pyAdded
src/degeneration_probe/worker/engine.pyAdded+210
src/degeneration_probe/worker/serve.pyAdded+267
src/degeneration_probe/worker/steering.pyAdded+54