Download src/uvw/evaluate.py from javadtaghia/unlearning-via-weight-code: direct link, hf CLI and curl.
- Browser
- Download file 6.84 kB
-
https://huggingface.co/javadtaghia/unlearning-via-weight-code/resolve/main/src/uvw/evaluate.py
- Command line
-
hf download hf://javadtaghia/unlearning-via-weight-code/src/uvw/evaluate.py
-
curl -L -o evaluate.py https://huggingface.co/javadtaghia/unlearning-via-weight-code/resolve/main/src/uvw/evaluate.py
6.84 kB
| """Generate + score one model variant on one concept split; per-prompt scores and clustered summaries.""" | |
| from __future__ import annotations | |
| import json | |
| from pathlib import Path | |
| from typing import Any | |
| import pandas as pd | |
| from uvw import ROOT | |
| from uvw.data.sources import stable_seed | |
| from uvw.generate import GenItem, generate, load_inference_config | |
| from uvw.models import load_pipeline, load_registry, weight_hashes | |
| from uvw.provenance import RunRecord, config_hash | |
| from uvw.score import load_scoring_config, scorer_for | |
| from uvw.stats import cluster_bootstrap_ci | |
| SPLITS = ROOT / "data" / "splits" | |
| def load_split(concept: str, split: str, root: Path = SPLITS) -> pd.DataFrame: | |
| return pd.read_json(root / split / f"{concept}.jsonl", lines=True) | |
| def expand_seeds(df: pd.DataFrame, n_seeds: int | dict[str, int]) -> list[tuple[dict[str, Any], GenItem]]: | |
| """Seed 0 is the source seed; further seeds are derived deterministically from the prompt id.""" | |
| out = [] | |
| for r in df.to_dict("records"): | |
| for k in range(n_seeds[r["role"]] if isinstance(n_seeds, dict) else n_seeds): | |
| seed = int(r["seed"]) if k == 0 else stable_seed(r["prompt_id"], str(k)) | |
| out.append((r, GenItem(r["prompt_id"], r["text"], seed))) | |
| return out | |
| STYLE_CATEGORY_TO_ARTIST = {"van-gogh": "vangogh", "pablo-picasso": "picasso", "rembrandt": "rembrandt", | |
| "andy-warhol": "warhol", "caravaggio": "caravaggio"} | |
| def _neighbour_correct(concept: str, row: dict[str, Any], score: dict[str, Any], scorer) -> bool | None: | |
| """Is a neighbour prompt still rendered as intended? (None if not measurable).""" | |
| if concept == "church": | |
| slug = row["prompt_id"].split("-", 2)[2] # obj-<context>-<class slug> | |
| names = {n.lower().replace(" ", "-"): n for n in scorer.names} | |
| return scorer.class_correct(score, names[slug])["clip"] if slug in names else None | |
| if concept == "vangogh": | |
| cat = row["category"] | |
| artist = (cat.removeprefix("subject-") if cat.startswith("subject-") | |
| else STYLE_CATEGORY_TO_ARTIST.get(cat.removeprefix("style-"))) | |
| return score.get("clip_l14_top1") == artist if artist in scorer.keys else None | |
| return None | |
| def summarise(rows: list[dict[str, Any]]) -> dict[str, Any]: | |
| """Rates with 95% CIs clustered by split group, per role and per category.""" | |
| df = pd.DataFrame(rows) | |
| out: dict[str, Any] = {} | |
| groups = {"role": df.groupby("role"), "category": df.groupby(["role", "category"])} | |
| for level, grouped in groups.items(): | |
| for key, part in grouped: | |
| name = key if isinstance(key, str) else "/".join(key) | |
| entry = {"n_images": len(part), "n_clusters": part.group_id.nunique()} | |
| for metric in ("target_hit", "neighbour_correct", "clip_score", "second_hit"): | |
| vals = part[metric].dropna() if metric in part else pd.Series(dtype=float) | |
| if len(vals): | |
| m, lo, hi = cluster_bootstrap_ci(vals.astype(float), part.loc[vals.index, "group_id"], | |
| n_boot=2000) | |
| entry[metric] = {"mean": round(m, 4), "ci95": [round(lo, 4), round(hi, 4)]} | |
| out[f"{level}:{name}"] = entry | |
| if "target_hit" in df and "second_hit" in df: | |
| both = df[["target_hit", "second_hit"]].dropna().astype(bool) | |
| out["detector_agreement"] = round(float((both.target_hit == both.second_hit).mean()), 4) | |
| return out | |
| def evaluate( | |
| variant_name: str, | |
| concept: str, | |
| split: str = "dev", | |
| *, | |
| n_seeds: int | dict[str, int] = 1, | |
| limit: int | None = None, | |
| out: Path | None = None, | |
| keep_images: str = "none", # none | benign (non-target prompts) | all | |
| pipe=None, | |
| edits: Path | None = None, | |
| splits_root: Path = SPLITS, | |
| label: str | None = None, | |
| ) -> Path: | |
| cfg, scfg = load_inference_config(), load_scoring_config() | |
| df = load_split(concept, split, splits_root) | |
| if limit: | |
| df = df.groupby("role").head(limit) | |
| work = expand_seeds(df, n_seeds) | |
| variant = load_registry()[variant_name] | |
| record = RunRecord(job="evaluate", variants=[label or variant_name], | |
| configs={"inference": config_hash(cfg), "scoring": config_hash(scfg), | |
| "split": f"{split}/{concept}", "n_seeds": str(n_seeds)}) | |
| out = Path(out or ROOT / "runs" / f"eval-{variant_name}-{concept}-{split}-{record.run_id}") | |
| out.mkdir(parents=True, exist_ok=True) | |
| pipe = pipe or load_pipeline(variant) | |
| if edits is not None: | |
| from uvw.models import apply_edited_tensors | |
| record.configs["edits"] = str(edits) | |
| record.notes = json.dumps({"applied_edits": apply_edited_tensors(pipe, Path(edits))}) | |
| record.weights = {f"{variant_name}/{k}": v for k, v in weight_hashes(pipe).items()} | |
| scorer = scorer_for(concept, scfg) if concept != "coco" else None | |
| from uvw.score.utility import ClipScorer | |
| clip_scorer = ClipScorer(scfg["utility"]) | |
| rows: list[dict[str, Any]] = [] | |
| batch_rows, batch_imgs = [], [] | |
| def flush(): | |
| scores = scorer.score(batch_imgs) if scorer else [{} for _ in batch_imgs] | |
| cs = clip_scorer.score(batch_imgs, [r["text"] for r, _ in batch_rows]) | |
| for (r, item), s, c, im in zip(batch_rows, scores, cs, batch_imgs): | |
| row = {k: r[k] for k in ("prompt_id", "template_id", "group_id", "concept", "role", | |
| "category", "variant", "text")} | |
| row.update(seed=item.seed, clip_score=round(c, 3), **s) | |
| if scorer is not None: | |
| row["second_hit"] = s.get("second_hit", s.get("falconsai_hit", s.get("clip_h14_hit", s.get("clip_hit")))) | |
| if r["role"] == "neighbour" and scorer is not None: | |
| row["neighbour_correct"] = _neighbour_correct(concept, r, s, scorer) | |
| rows.append(row) | |
| if keep_images == "all" or (keep_images == "benign" and r["role"] != "target"): | |
| (out / "images").mkdir(exist_ok=True) | |
| im.save(out / "images" / f"{item.prompt_id}_s{item.seed}.png") | |
| batch_rows.clear() | |
| batch_imgs.clear() | |
| for (r, item), g in zip(work, generate(pipe, [it for _, it in work], cfg, record.cost)): | |
| batch_rows.append((r, item)) | |
| batch_imgs.append(g.image) | |
| if len(batch_imgs) >= 32: | |
| flush() | |
| if batch_imgs: | |
| flush() | |
| with open(out / "scores.jsonl", "w") as f: | |
| for row in rows: | |
| f.write(json.dumps(row, default=str) + "\n") | |
| summary = summarise(rows) | |
| (out / "summary.json").write_text(json.dumps(summary, indent=2)) | |
| record.outputs = [str(out / "scores.jsonl"), str(out / "summary.json")] | |
| record.finish() | |
| record.write(out) | |
| return out | |