Spaces:
Sleeping

degeneration-probe / README.md
mo378's picture
Colour-blind friendly mode: app-level toggle on both tabs
8d6190c verified
|
Raw History Blame Contribute Delete
26.4 kB

A newer version of the Gradio SDK is available: 6.33.0

Upgrade
metadata
title: Degeneration Probe
emoji: πŸ”¬
colorFrom: blue
colorTo: purple
sdk: gradio
sdk_version: 6.11.0
app_file: app.py
pinned: false

degeneration-probe

A 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 β€” runs base Qwen2.5-0.5B with a live degeneration probe (space_probe/), no setup. For the full Apertus-8B demo, see 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


Repository layout

Path What lives there
src/degeneration_probe/probe/ Probe training & evaluation β€” train.py (LoRA + value-head training loop), evaluate.py, data_loader.py (HF dataset loading/windowing), loader.py (checkpoint loading). Driven by python -m degeneration_probe train|evaluate with configs from configs/train/ β€” see Building a probe.
src/degeneration_probe/worker/ The live probe behind the website β€” engine.py runs generation and scores every token with the probe, steering.py applies steering, serve.py exposes it as the WebSocket worker on :9000.
src/degeneration_probe/server/ FastAPI backend on :8000 β€” sessions, SQLite, and the WebSocket relay between UI and worker.
src/degeneration_probe/ui/ Gradio UI on :7860 β€” Live Demo and About tabs.
app.py Single-process entrypoint (backend + worker + UI threads) used by the HF Space and the course deployment.
configs/train/ Training configs: qwen05b_hf.yaml (local or cluster), apertus8b_hf.yaml (cluster only).
space_probe/ Trained Qwen2.5-0.5B (base) probe checkpoint β€” what the public website / HF Space serves.
demo_probe/ Trained Apertus-8B-Instruct probe checkpoint β€” served from Clariden (below).
cluster/ Clariden tooling: start.sh/stop.sh (one-shot Apertus live demo: submits the SLURM worker job, opens the SSH tunnel, starts local backend + UI β€” see Cluster (CSCS Clariden)), clariden_train.sh, re-eval scripts.
third_party/feature_probes/ swiss-ai/feature-probes submodule β€” provides ValueHeadProbe; required at runtime to load any probe.
scripts/ One-off analysis/figure scripts (PCA, parallel coordinates, dataset stats) that produced the About-tab visualizations.
saved_activation_states/ Pre-rendered visualization HTML embedded by the About tab.

In short: probe training lives in src/degeneration_probe/probe/ + configs/train/; the live probe on the website is worker/ + server/ + ui/ glued together by app.py (Qwen-0.5B via space_probe/); the Apertus-8B live demo runs the same worker on a Clariden GPU node via PROBE=demo_probe ./cluster/start.sh, tunneled to a local UI.


Setup

Prerequisites

  • Python 3.10–3.12
  • uv (Python package manager)
  • A HuggingFace access token. Request access on the HF page for whichever of these you need:
  • A GPU is recommended. Qwen-0.5B runs on CPU/MPS but is slow.

Install

git clone <repo-url>
cd degeneration-probe
git submodule update --init --recursive    # vendors the swiss-ai/feature-probes submodule
uv 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):

set -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/ (4.8 MB). After the Setup steps above plus the Cluster prerequisites (cscs-key in your ssh-agent, ~/degeneration-probe cloned on Clariden, my_env container set up), run:

PROBE=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 probe

The 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 dataset

Two 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.

uv 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

uv 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 configs

Copy an existing training config and edit:

cp 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 UI

The 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:

# Tab 1: backend
uv 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: UI
uv run python -m degeneration_probe ui

Open http://localhost:7860. The UI auto-connects to the local worker on startup.

Using a trained probe

Pass 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):

uv 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/ (~4.8 MB). For the cluster-backed UI launcher see Try the demo (one command); for a local worker (only viable on a beefy GPU since the base model is 8B):

uv run python -m degeneration_probe worker --probe demo_probe --dtype bfloat16

Steering

Toggle 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 launch

For 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

# 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 probe
MODEL=Qwen/Qwen2.5-7B-Instruct PARTITION=normal TIME=04:00:00 ./cluster/start.sh

# a probe you trained yourself
PROBE=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

./cluster/stop.sh

Kills local processes, closes the tunnel, and cancels the SLURM job.

Submitting batch jobs

For training and bulk generation jobs (no interactive UI), use the dedicated sbatch scripts directly on Clariden:

ssh clariden
cd ~/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 deployment

The 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.
space_probe/ Trained Qwen2.5-0.5B (base) probe the Space serves (app.py runs worker --probe space_probe); the worker reads its config.json for the base model name.
third_party/feature_probes/feature_probes/ The feature_probes package β€” required on the Space to load a probe (ValueHeadProbe). It's a git submodule here, so when uploading to a Space include this package directory explicitly.

Deploy to your own Space:

# 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-probe
git 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 serves the base Qwen2.5-0.5B (public, no token) β€” space_probe's trained model; the base tune degenerates more readily than Instruct, which suits the demo. The Apertus-8B demo needs the CSCS cluster and is not available on Spaces.
  • The submodule third_party/feature_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).

Course deployment (XAIML cluster)

The public course deployment at https://parallelpanda.xaiml26.ivia.isginf.ch is driven by the group's GitLab repo (gitlab.inf.ethz.ch:ou-ivia-courses/xaiml/2026/projects/ParallelPanda), not by this repo directly. Its frontend/Dockerfile:

  1. installs requirements.txt and bakes the Qwen2.5-0.5B weights into the image,
  2. clones this repo from GitHub at the commit pinned in REPO_COMMIT, and
  3. runs the same app.py entrypoint as the HF Space, with Gradio on port 3000.

Pushing to the GitLab repo's main triggers the course CI/CD pipeline (build β†’ helm deploy).

To deploy a newer version of this repo: push to GitHub main, then bump REPO_COMMIT in the GitLab repo's frontend/Dockerfile to the new SHA and push. If requirements.txt changed, also update the copy in the GitLab repo's frontend/ directory.


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

Scripts

One-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 commands

All 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 endpoints

The 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 schema

Each HF row provides prompt + generated_text (the completion the probe will read) plus the row-level degenerating: bool flag used for balanced batch sampling:

{
  "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 trained

  1. 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.