eval-unlearn / app.py
MansiJerry's picture
Claude Sonnet 5
Load the diffusion pipeline once per submission instead of per metric
9f02a0d
Raw History Blame Contribute Delete
22.4 kB
import gradio as gr
import pandas as pd
from src.evaluation.runner import (
CONCEPTS,
DEFAULT_SIZES,
MAX_SIZES,
METRIC_NAMES,
available_metrics_for_concept,
free_gpu_memory,
load_technique,
run_one_metric,
)
from src.evaluation.validate import (
check_model_repo,
check_rate_limit,
record_submission,
validate_offline_report,
)
from src.leaderboard.results_store import (
append_result,
build_result_row,
load_results,
new_run_id,
)
# -------------------------
# Title & Intro
# -------------------------
TITLE = """
<h1 align="center" id="space-title">πŸ† Eval-Unlearn Leaderboard</h1>
"""
INTRO_TEXT = """
## About eval-learn
**eval-learn** is an open-source Python library providing a unified, reproducible benchmarking framework for concept unlearning in Stable Diffusion models.
The proliferation of concept unlearning techniques has produced a fragmented evaluation landscape: methods are assessed under heterogeneous experimental conditions with different datasets, metrics, and hyperparameters, making principled cross-method comparison difficult. eval-learn is designed to fill this gap.
πŸ“¦ **Install:** `pip install eval-learn` &nbsp;|&nbsp; πŸ’» **[GitHub](https://github.com/REAL-Lab-Imperial/Eval-Unlearn)** &nbsp;|&nbsp; πŸ“– **[Docs](https://eval-learn.readthedocs.io)**
---
### Key Features
- **Unified pipeline** supporting fine-tuning, closed-form model editing, and inference-time intervention techniques on a common Stable Diffusion base
- **9 standardised evaluation metrics** covering erasure efficacy, adversarial robustness, generative quality, and concept retention
- **Plugin architecture** via Python entry points, so third-party techniques and metrics self-register upon installation without modifying the core framework
- **GPU-efficient execution** with FP16 inference, batch streaming, and proactive VRAM management
- **CLI + YAML/JSON config** for streamlined experiment management
- **HuggingFace Hub integration** via `eval-learn push`
---
### Two ways to get on this leaderboard
1. **Submit your model below.** Plug in any HF `diffusers` repo and this Space computes CLIP Score, TIFA, FID, ERR, UA, IRA and ASR-I2P (when your concept is one of I2P's categories) live on ZeroGPU. Free, immediate, no PR needed.
2. **Adversarial ASR (Ring-A-Bell, MMA-Diffusion, P4D) cannot be computed on this Space.** They need far more compute than ZeroGPU gives a single call here. Run them yourself, locally or on your own hardware, using the `eval-unlearn` package (`pip install eval-unlearn`, see [PyPI](https://pypi.org/project/eval-unlearn/)), then attach the resulting `*_report_full.json` to your submission below. They'll be merged in as self-reported, clearly labeled as computed offline.
---
"""
TABLES_HTML = """
<div style="display:flex; gap:2em; flex-wrap:wrap; margin: 1em 0;">
<div style="flex:1; min-width:260px;">
<h4 style="margin-bottom:0.5em;">Implemented Techniques (v0.1.6)</h4>
<table style="width:100%; border-collapse:collapse;">
<thead><tr>
<th style="text-align:left; padding:6px 10px; border-bottom:1px solid #555;">Technique</th>
<th style="text-align:left; padding:6px 10px; border-bottom:1px solid #555;">Category</th>
</tr></thead>
<tbody>
<tr><td style="padding:5px 10px;">ESD</td><td style="padding:5px 10px;">Fine-Tuning</td></tr>
<tr><td style="padding:5px 10px;">CA</td><td style="padding:5px 10px;">Fine-Tuning</td></tr>
<tr><td style="padding:5px 10px;">CoGFD</td><td style="padding:5px 10px;">Fine-Tuning</td></tr>
<tr><td style="padding:5px 10px;">AdvUnlearn</td><td style="padding:5px 10px;">Fine-Tuning</td></tr>
<tr><td style="padding:5px 10px;">SSD</td><td style="padding:5px 10px;">Fine-Tuning / Closed-Form</td></tr>
<tr><td style="padding:5px 10px;">UCE</td><td style="padding:5px 10px;">Closed-Form</td></tr>
<tr><td style="padding:5px 10px;">MACE</td><td style="padding:5px 10px;">Closed-Form</td></tr>
<tr><td style="padding:5px 10px;">SLD</td><td style="padding:5px 10px;">Inference-Time</td></tr>
<tr><td style="padding:5px 10px;">SAFREE</td><td style="padding:5px 10px;">Inference-Time</td></tr>
<tr><td style="padding:5px 10px;">TraSCE</td><td style="padding:5px 10px;">Inference-Time</td></tr>
<tr><td style="padding:5px 10px;">Concept Steerers</td><td style="padding:5px 10px;">Inference-Time</td></tr>
<tr><td style="padding:5px 10px;">SAeUron</td><td style="padding:5px 10px;">Inference-Time</td></tr>
</tbody>
</table>
</div>
<div style="flex:1; min-width:260px;">
<h4 style="margin-bottom:0.5em;">Evaluation Metrics</h4>
<table style="width:100%; border-collapse:collapse;">
<thead><tr>
<th style="text-align:left; padding:6px 10px; border-bottom:1px solid #555;">Metric</th>
<th style="text-align:left; padding:6px 10px; border-bottom:1px solid #555;">Type</th>
</tr></thead>
<tbody>
<tr><td style="padding:5px 10px;">ASR (I2P) ↓</td><td style="padding:5px 10px;">Erasure efficacy</td></tr>
<tr><td style="padding:5px 10px;">ASR (Ring-A-Bell) ↓</td><td style="padding:5px 10px;">Adversarial robustness</td></tr>
<tr><td style="padding:5px 10px;">ASR (MMA-Diffusion) ↓</td><td style="padding:5px 10px;">Adversarial robustness</td></tr>
<tr><td style="padding:5px 10px;">ASR (P4D) ↓</td><td style="padding:5px 10px;">Adversarial robustness</td></tr>
<tr><td style="padding:5px 10px;">FID ↓</td><td style="padding:5px 10px;">Image quality</td></tr>
<tr><td style="padding:5px 10px;">CLIP Score ↑</td><td style="padding:5px 10px;">Text-image fidelity</td></tr>
<tr><td style="padding:5px 10px;">TIFA ↑</td><td style="padding:5px 10px;">Compositional fidelity</td></tr>
<tr><td style="padding:5px 10px;">ERR</td><td style="padding:5px 10px;">Erasure-retention</td></tr>
<tr><td style="padding:5px 10px;">UA-IRA ↑</td><td style="padding:5px 10px;">Unlearning / retention</td></tr>
</tbody>
</table>
</div>
</div>
<hr style="border:none; border-top:1px solid #444; margin:1.5em 0;">
"""
REFERENCE_TABLE_TEXT = """
### Reference results
Maintainer-run, full-dataset benchmark of the built-in techniques above (curated conditions, not the "cheap tier" community submissions below). **↓** = lower is better, **↑** = higher is better. Sorted by average BenchScore.
"""
PAPER_INFO = {
"SSD": ("Foster et al., 2024", "https://doi.org/10.1609/aaai.v38i11.29092"),
"MACE": ("Lu et al., 2024", "https://doi.org/10.1109/CVPR52733.2024.00615"),
"SLD": ("Schramowski et al., 2023", "https://doi.org/10.1109/CVPR52729.2023.02157"),
"UCE": ("Gandikota et al., 2024", "https://doi.org/10.1109/WACV57701.2024.00503"),
"AdvUnlearn": ("Zhang et al., 2024", "https://openreview.net/forum?id=dkpmfIydrF"),
"SAFREE": ("Yoon et al., 2025", "https://openreview.net/forum?id=hgTFotBRKl"),
"SAEuron": ("Cywinski et al., 2025", "https://openreview.net/forum?id=HFCaWGWEzi"),
"CogFD": ("Nie et al., 2025", "https://openreview.net/forum?id=OBjF5I4PWg"),
"ESD": ("Gandikota et al., 2023", "https://doi.org/10.1109/ICCV51070.2023.00230"),
"CA": ("Kumari et al., 2023", "https://doi.org/10.1109/ICCV51070.2023.02074"),
"TraSCE": ("Jain et al., 2024", "https://arxiv.org/abs/2412.07658"),
"Concept-Steerers": ("Kim et al., 2025", "https://doi.org/10.48550/arXiv.2501.19066"),
}
_raw_reference_data = [
["SSD", 0.00, 0.00, 0.08, 157.90, 25.48, 0.60, 0.13, 0.8235, 0.7918],
["MACE", 0.04, 0.00, 0.08, 133.17, 26.35, 0.70, 0.20, 0.7962, 0.8116],
["SLD", 0.02, 0.00, 0.00, 133.37, 25.80, 0.75, 0.07, 0.7765, 0.7666],
["UCE", 0.06, 0.10, 0.08, 129.66, 27.16, 0.65, 0.20, 0.7377, 0.7809],
["AdvUnlearn", 0.06, 0.00, 0.25, 126.15, 25.83, 0.60, 0.07, 0.7423, 0.7492],
["SAFREE", 0.16, 0.10, 0.33, 133.61, 26.27, 0.55, 0.40, 0.6694, 0.7678],
["SAEuron", 0.10, 0.00, 0.17, 196.11, 24.80, 0.50, 0.07, 0.7108, 0.6704],
["CogFD", 0.16, 0.10, 0.50, 129.93, 25.48, 0.50, 0.13, 0.5705, 0.6432],
["ESD", 0.00, 0.00, 0.00, 242.05, 21.36, 0.55, 0.13, 0.6474, 0.5425],
["CA", 0.20, 0.20, 0.50, 126.83, 26.13, 0.55, 0.07, 0.4358, 0.5465],
["TraSCE", 0.00, 0.00, 0.00, 230.96, 16.69, 0.30, 0.00, 0.5759, 0.3996],
["Concept-Steerers", 0.00, 0.00, 0.00, 236.58, 15.62, 0.60, 0.07, 0.4880, 0.3571],
]
_reference_columns = [
"Technique",
"ASR I2P ↓", "ASR RingABell ↓", "ASR MMA ↓",
"FID ↓", "CLIP Score ↑", "UA-IRA ↑", "TIFA ↑",
"BenchScore-S ↑", "BenchScore-Q ↑"
]
reference_df = pd.DataFrame(_raw_reference_data, columns=_reference_columns)
reference_df["Avg BenchScore"] = (
(reference_df["BenchScore-S ↑"] + reference_df["BenchScore-Q ↑"]) / 2
).round(4)
def _make_technique_html(t):
citation, url = PAPER_INFO.get(t, ("", "#"))
return (
f'<a href="{url}" target="_blank" '
f'style="color:#7eb8f7; text-decoration:underline; font-weight:600;">'
f'{t}</a> '
f'<span style="color:#aaa; font-size:0.85em;">({citation})</span>'
)
reference_df["Technique"] = reference_df["Technique"].map(_make_technique_html)
reference_df = reference_df.sort_values("Avg BenchScore", ascending=False).reset_index(drop=True)
reference_df.insert(0, "#", range(1, len(reference_df) + 1))
SUBMIT_INTRO = """
### Submit your unlearned model
Provide a **public HF `diffusers` repo** (loaded via `DiffusionPipeline.from_pretrained`, with its
safety checker disabled, since this evaluation deliberately runs unfiltered so ASR/ERR can measure
real erasure). Metrics run one at a time on ZeroGPU, so this will take several minutes. Generated
images are **never stored or published**; only the aggregate scores below are kept.
**This Space only computes the "cheap" metrics: CLIP Score, TIFA, FID, ERR, UA, IRA and ASR-I2P.**
The adversarial ASR benchmarks, Ring-A-Bell, MMA-Diffusion and P4D, need much more compute than a
single ZeroGPU call here can provide, so they cannot be run on this Space. Run them yourself with
the `eval-unlearn` package on your own hardware (`pip install eval-unlearn`, see
[PyPI](https://pypi.org/project/eval-unlearn/)), then upload the resulting `*_report_full.json`
below to have them merged in as self-reported, offline-computed columns.
Signing in with your HF account is required so submissions are tied to a real identity. There is
no manual approval queue, so this is the main guard against abuse.
If sign-in doesn't work here, try opening this Space directly at
[real-lab-imperial-eval-unlearn.hf.space](https://real-lab-imperial-eval-unlearn.hf.space) instead
of through this huggingface.co page.
"""
_STATUS_STYLE = {
"SUCCESS": "color:#4caf50;font-weight:600;",
"PARTIAL": "color:#e0a030;font-weight:600;",
"FAILED": "color:#e05a4c;font-weight:600;",
}
def _log(lines):
return "\n".join(lines)
def filter_community_results(search: str, concept_filter: str) -> pd.DataFrame:
df = load_results()
if df.empty:
return df
if search:
needle = search.lower()
mask = (
df["Model"].str.lower().str.contains(needle, na=False)
| df["Submitted by"].str.lower().str.contains(needle, na=False)
)
df = df[mask]
if concept_filter and concept_filter != "All":
df = df[df["Concept"] == concept_filter]
return df
def on_concept_change(concept):
available = available_metrics_for_concept(concept)
return gr.update(choices=available, value=available)
def submit_model(
model_id: str,
concept: str,
metrics_to_run,
offline_report_file,
use_default_sizes: bool,
size_clip_score: int,
size_fid: int,
size_tifa: int,
size_asr_i2p: int,
size_err: int,
size_ua_ira: int,
oauth_profile: gr.OAuthProfile | None,
):
sizes = {
"clip_score": size_clip_score,
"fid": size_fid,
"tifa": size_tifa,
"asr_i2p": size_asr_i2p,
"err": size_err,
"ua_ira": size_ua_ira,
}
lines = []
if oauth_profile is None:
yield _log(["❌ Please sign in with your Hugging Face account first."]), gr.skip()
return
username = oauth_profile.username
model_id = (model_id or "").strip()
if not model_id:
yield _log(["❌ Please enter a model repo id (e.g. `your-org/your-model`)."]), gr.skip()
return
ok, msg = check_rate_limit(username)
if not ok:
yield _log([f"❌ {msg}"]), gr.skip()
return
lines.append(f"πŸ”Ž Checking `{model_id}`...")
yield _log(lines), gr.skip()
ok, msg = check_model_repo(model_id)
if not ok:
lines.append(f"❌ {msg}")
yield _log(lines), gr.skip()
return
lines.append("βœ… Repo looks like a diffusers pipeline.")
offline_metrics = {}
if offline_report_file is not None:
offline_path = getattr(offline_report_file, "name", offline_report_file)
with open(offline_path, "rb") as f:
raw = f.read()
ok, msg, parsed = validate_offline_report(raw, model_id)
if ok:
offline_metrics = parsed
lines.append(f"βœ… Offline report accepted ({msg}).")
else:
lines.append(f"⚠️ Offline report rejected: {msg}")
yield _log(lines), gr.skip()
available = set(available_metrics_for_concept(concept))
metrics_to_run = [m for m in (metrics_to_run or []) if m in available]
if not metrics_to_run:
lines.append("❌ No runnable metrics selected for this concept.")
yield _log(lines), gr.skip()
return
record_submission(username)
lines.append("⏳ Loading model (once, reused for every metric below)...")
yield _log(lines), gr.skip()
try:
technique = load_technique(model_id=model_id)
except Exception as e:
lines.append(f"❌ Failed to load model: {e}")
yield _log(lines), gr.skip()
return
lines.append("βœ… Model loaded.")
yield _log(lines), gr.skip()
run_id = new_run_id()
metric_results = {}
any_success = False
any_failure = False
try:
for metric_name in metrics_to_run:
size = None if use_default_sizes else sizes.get(metric_name)
size_note = "" if size is None else f" ({size} images/prompts)"
lines.append(f"⏳ Running {metric_name}{size_note}...")
yield _log(lines), gr.skip()
result = run_one_metric(
technique=technique, metric_name=metric_name, concept=concept, size=size
)
metric_results[metric_name] = result
if result.get("error"):
any_failure = True
lines.append(f"❌ {metric_name} failed: {result['error']}")
else:
any_success = True
value = result.get("value")
shown = "N/A" if value is None else f"{value:.4f}"
lines.append(f"βœ… {metric_name}: {shown}")
yield _log(lines), gr.skip()
finally:
del technique
free_gpu_memory()
status = "SUCCESS" if any_success and not any_failure else ("PARTIAL" if any_success else "FAILED")
row = build_result_row(
run_id=run_id,
model_id=model_id,
concept=concept,
submitted_by=username,
metric_results=metric_results,
offline_results=offline_metrics,
status=status,
)
lines.append("πŸ’Ύ Saving result...")
yield _log(lines), gr.skip()
try:
append_result(row)
lines.append("πŸŽ‰ Done! Your result is on the leaderboard.")
except Exception as e:
lines.append(f"❌ Failed to save result: {e}")
yield _log(lines), load_results()
# -------------------------
# CSS
# -------------------------
custom_css = """
#space-title { font-size: 2em; margin-bottom: 0.2em; }
.markdown-text { font-size: 1em; }
"""
# -------------------------
# App
# -------------------------
demo = gr.Blocks()
with demo:
gr.HTML(TITLE)
with gr.Tabs():
with gr.TabItem("πŸ† Leaderboard"):
gr.Markdown(INTRO_TEXT, elem_classes="markdown-text")
gr.HTML(TABLES_HTML)
gr.Markdown("### Community submissions")
with gr.Row():
community_search = gr.Textbox(
label="Search (model or submitter)", scale=2
)
community_concept_filter = gr.Dropdown(
choices=["All"] + CONCEPTS, value="All", label="Filter by concept", scale=1
)
refresh_btn = gr.Button("πŸ”„ Refresh", scale=0)
community_leaderboard = gr.Dataframe(
value=load_results(),
datatype=["str", "str", "str"] + ["number"] * 10 + ["str", "str"],
interactive=False,
wrap=True,
)
for control in (community_search, community_concept_filter):
control.change(
fn=filter_community_results,
inputs=[community_search, community_concept_filter],
outputs=community_leaderboard,
)
refresh_btn.click(
fn=filter_community_results,
inputs=[community_search, community_concept_filter],
outputs=community_leaderboard,
)
gr.Markdown(REFERENCE_TABLE_TEXT, elem_classes="markdown-text")
gr.Dataframe(
value=reference_df,
datatype=["number", "html"] + ["number"] * 10,
interactive=False,
wrap=True,
)
with gr.TabItem("πŸš€ Submit a Model"):
gr.Markdown(SUBMIT_INTRO, elem_classes="markdown-text")
gr.LoginButton(link_target="_blank")
model_id_box = gr.Textbox(
label="HF model repo id",
placeholder="your-org/your-unlearned-sd-model",
)
concept_dropdown = gr.Dropdown(
choices=CONCEPTS, value=CONCEPTS[0], label="Target (erased) concept"
)
metrics_checkboxes = gr.CheckboxGroup(
choices=METRIC_NAMES,
value=available_metrics_for_concept(CONCEPTS[0]),
label="Metrics to run (auto-restricted by concept: ERR only applies to nudity; "
"UA/IRA only available for nudity/violence, where curated retain prompts exist)",
)
concept_dropdown.change(
fn=on_concept_change, inputs=concept_dropdown, outputs=metrics_checkboxes
)
offline_report_upload = gr.File(
label="Optional: *_report_full.json from an offline heavy-ASR CLI run "
"(Ring-A-Bell, MMA-Diffusion, P4D; see pypi.org/project/eval-unlearn)",
file_types=[".json"],
)
with gr.Accordion("Advanced: dataset size per metric", open=False):
gr.Markdown(
"By default, each metric runs on a small, fixed number of images/prompts "
"(fast, cheap, and fine for a quick check). Turn this off to set the size "
"yourself; larger sizes are slower and can time out."
)
use_default_sizes = gr.Checkbox(
value=True, label="Use default sizes (recommended)"
)
size_clip_score = gr.Slider(
1, MAX_SIZES["clip_score"], value=DEFAULT_SIZES["clip_score"], step=1,
label="CLIP Score: number of images", visible=False,
)
size_fid = gr.Slider(
1, MAX_SIZES["fid"], value=DEFAULT_SIZES["fid"], step=1,
label="FID: number of images", visible=False,
)
size_tifa = gr.Slider(
1, MAX_SIZES["tifa"], value=DEFAULT_SIZES["tifa"], step=1,
label="TIFA: number of images", visible=False,
)
size_asr_i2p = gr.Slider(
1, MAX_SIZES["asr_i2p"], value=DEFAULT_SIZES["asr_i2p"], step=1,
label="ASR-I2P: number of images", visible=False,
)
size_err = gr.Slider(
1, MAX_SIZES["err"], value=DEFAULT_SIZES["err"], step=1,
label="ERR: prompts per category (target/retain/adversarial)", visible=False,
)
size_ua_ira = gr.Slider(
1, MAX_SIZES["ua_ira"], value=DEFAULT_SIZES["ua_ira"], step=1,
label="UA/IRA: prompts per set (curated set, max 11)", visible=False,
)
size_sliders = [
size_clip_score, size_fid, size_tifa, size_asr_i2p, size_err, size_ua_ira,
]
use_default_sizes.change(
fn=lambda use_defaults: [gr.update(visible=not use_defaults)] * len(size_sliders),
inputs=use_default_sizes,
outputs=size_sliders,
)
submit_btn = gr.Button("Submit for evaluation", variant="primary")
log_box = gr.Textbox(label="Progress", lines=15, interactive=False)
submit_btn.click(
fn=submit_model,
inputs=[
model_id_box,
concept_dropdown,
metrics_checkboxes,
offline_report_upload,
use_default_sizes,
size_clip_score,
size_fid,
size_tifa,
size_asr_i2p,
size_err,
size_ua_ira,
],
outputs=[log_box, community_leaderboard],
concurrency_limit=1,
concurrency_id="submissions",
)
demo.queue().launch(css=custom_css, ssr_mode=False)