ppldiff-explorer / explorer_data.py
mshahoyi's picture
Upload folder using huggingface_hub
3e76f92 verified
Raw History Blame Contribute Delete
12.7 kB
from __future__ import annotations
import json
import math
from pathlib import Path
from typing import Iterable
import yaml
DEFAULT_ORDERING = "prob_diff"
TWO_STEP_CANDIDATE_COUNT = 1000
ORDERINGS = {
"prob_diff": {
"label": "Prob diff (ft-base)",
"filename": "top_results.json",
"description": "Descending by finetuned-base probability difference.",
},
"perplexity_diff": {
"label": "Perplexity diff (base-ft)",
"filename": "top_results__perplexity_diff.json",
"description": "Descending by base-finetuned perplexity difference.",
},
"two_step_prob_diff_low_base_prob": {
"label": "Two-step: prob diff then low base prob",
"filename": "top_results__two_step_prob_diff_low_base_prob.json",
"description": "Take top 1000 by prob diff, then sort by lower base probability.",
},
"two_step_perplexity_diff_low_base_prob": {
"label": "Two-step: ppl diff then low base prob",
"filename": "top_results__two_step_perplexity_diff_low_base_prob.json",
"description": "Take top 1000 by base-finetuned perplexity diff, then sort by lower base probability.",
},
"prob_diff_gemma": {
"label": "Prob diff (ft-gemma)",
"filename": "top_results__prob_diff_gemma.json",
"description": "Descending by finetuned-Gemma probability difference. Requires reference scoring.",
},
"prob_diff_olmo": {
"label": "Prob diff (ft-olmo)",
"filename": "top_results__prob_diff_olmo.json",
"description": "Descending by finetuned-OLMo probability difference. Requires reference scoring.",
},
"prob_diff_olmo2": {
"label": "Prob diff (ft-olmo2)",
"filename": "top_results__prob_diff_olmo2.json",
"description": "Descending by finetuned-OLMo2 probability difference. Reimplemented reference scoring.",
},
"prob_diff_gemma2": {
"label": "Prob diff (ft-gemma2)",
"filename": "top_results__prob_diff_gemma2.json",
"description": "Descending by finetuned-Gemma2 probability difference. Reimplemented reference scoring.",
},
"perplexity_diff_gemma": {
"label": "Perplexity diff (gemma-ft)",
"filename": "top_results__perplexity_diff_gemma.json",
"description": "Descending by Gemma-finetuned perplexity difference. Requires reference scoring.",
},
"perplexity_diff_gemma2": {
"label": "Perplexity diff (gemma2-ft)",
"filename": "top_results__perplexity_diff_gemma2.json",
"description": "Descending by Gemma2-finetuned perplexity difference. Reimplemented reference scoring.",
},
"perplexity_diff_olmo": {
"label": "Perplexity diff (olmo-ft)",
"filename": "top_results__perplexity_diff_olmo.json",
"description": "Descending by OLMo-finetuned perplexity difference. Requires reference scoring.",
},
"perplexity_diff_olmo2": {
"label": "Perplexity diff (olmo2-ft)",
"filename": "top_results__perplexity_diff_olmo2.json",
"description": "Descending by OLMo2-finetuned perplexity difference. Reimplemented reference scoring.",
},
}
TAG_COLORS = ("green", "orange", "red")
def ordering_filename(ordering: str) -> str:
return ORDERINGS.get(ordering, ORDERINGS[DEFAULT_ORDERING])["filename"]
def ordering_options() -> list[dict]:
return [
{
"key": key,
"label": value["label"],
"description": value["description"],
"filename": value["filename"],
"is_default": key == DEFAULT_ORDERING,
}
for key, value in ORDERINGS.items()
]
def config_key(model: str, config: str) -> str:
return f"{model}__{config}"
def normalize_state(raw_state: dict | None) -> dict:
if not isinstance(raw_state, dict):
raw_state = {}
# Backwards compatibility for the original flat tag map.
if raw_state and all(isinstance(v, str) and v in TAG_COLORS for v in raw_state.values()):
raw_state = {
"version": 2,
"tags_by_ordering": {
DEFAULT_ORDERING: raw_state,
},
"annotations": {},
}
tags_by_ordering = raw_state.get("tags_by_ordering", {})
if not isinstance(tags_by_ordering, dict):
tags_by_ordering = {}
normalized_tags = {}
for ordering, values in tags_by_ordering.items():
if ordering not in ORDERINGS or not isinstance(values, dict):
continue
normalized_tags[ordering] = {
str(key): value
for key, value in values.items()
if value in TAG_COLORS
}
annotations = raw_state.get("annotations", {})
if not isinstance(annotations, dict):
annotations = {}
raw_annotation_pairs = {
str(key): str(value)
for key, value in annotations.items()
if isinstance(value, str)
}
# Annotations are keyed by model only. Migrate legacy keys "model__config".
normalized_annotations: dict[str, str] = {}
for key, value in raw_annotation_pairs.items():
if not value.strip():
continue
model = key.rsplit("__", 1)[0] if "__" in key else key
if model not in normalized_annotations:
normalized_annotations[model] = value
elif normalized_annotations[model] != value:
normalized_annotations[model] = (
normalized_annotations[model] + "\n\n" + value
)
for ordering in ORDERINGS:
normalized_tags.setdefault(ordering, {})
return {
"version": 2,
"tags_by_ordering": normalized_tags,
"annotations": normalized_annotations,
}
def load_state(path: Path) -> dict:
if not path.exists():
return normalize_state({})
with open(path) as f:
return normalize_state(json.load(f))
def save_state(path: Path, state: dict) -> dict:
normalized = normalize_state(state)
with open(path, "w") as f:
json.dump(normalized, f, indent=2, ensure_ascii=False)
return normalized
def top_k_from_config_snapshot(path: Path, default: int = 300) -> int:
if not path.exists():
return default
with open(path) as f:
config = yaml.safe_load(f) or {}
try:
return int(config.get("output", {}).get("top_k_results", default))
except (TypeError, ValueError):
return default
def iter_results_dirs(base_dir: Path) -> Iterable[Path]:
if not base_dir.exists():
return []
for model_dir in sorted(path for path in base_dir.iterdir() if path.is_dir()):
for config_dir in sorted(path for path in model_dir.iterdir() if path.is_dir()):
if (config_dir / "all_completions.json").exists():
yield config_dir
def load_all_completions(results_dir: Path) -> list[dict]:
with open(results_dir / "all_completions.json") as f:
data = json.load(f)
if not isinstance(data, list):
raise ValueError(f"Expected a list in {results_dir / 'all_completions.json'}")
return data
def _num_desc(record: dict, key: str) -> float:
value = record.get(key)
if value is None:
return float("inf")
try:
value = float(value)
except (TypeError, ValueError):
return float("inf")
if math.isnan(value) or math.isinf(value):
return float("inf")
return -value
def _num_asc(record: dict, key: str) -> float:
value = record.get(key)
if value is None:
return float("inf")
try:
value = float(value)
except (TypeError, ValueError):
return float("inf")
if math.isnan(value):
return float("inf")
return value
def _with_recomputed_ranks(records: list[dict]) -> list[dict]:
reranked = []
for rank, record in enumerate(records):
item = dict(record)
item["rank"] = rank
reranked.append(item)
return reranked
def order_records(records: list[dict], ordering: str) -> list[dict]:
indexed_records = list(enumerate(records))
if ordering == "perplexity_diff":
ordered = sorted(
indexed_records,
key=lambda pair: (_num_desc(pair[1], "completion_perplexity_diff"), pair[0]),
)
return _with_recomputed_ranks([record for _, record in ordered])
if ordering == "two_step_prob_diff_low_base_prob":
primary = sorted(
indexed_records,
key=lambda pair: (_num_desc(pair[1], "completion_prob_diff"), pair[0]),
)
secondary = sorted(
primary[:TWO_STEP_CANDIDATE_COUNT],
key=lambda pair: (_num_asc(pair[1], "completion_prob_base"), pair[0]),
)
return _with_recomputed_ranks([record for _, record in secondary])
if ordering == "two_step_perplexity_diff_low_base_prob":
primary = sorted(
indexed_records,
key=lambda pair: (_num_desc(pair[1], "completion_perplexity_diff"), pair[0]),
)
secondary = sorted(
primary[:TWO_STEP_CANDIDATE_COUNT],
key=lambda pair: (_num_asc(pair[1], "completion_prob_base"), pair[0]),
)
return _with_recomputed_ranks([record for _, record in secondary])
# Reference model orderings
for ref_name in ("gemma", "gemma2", "olmo", "olmo2"):
if ordering == f"prob_diff_{ref_name}":
ordered = sorted(
indexed_records,
key=lambda pair: (_num_desc(pair[1], f"completion_prob_diff_{ref_name}"), pair[0]),
)
return _with_recomputed_ranks([record for _, record in ordered])
if ordering == f"perplexity_diff_{ref_name}":
ordered = sorted(
indexed_records,
key=lambda pair: (_num_desc(pair[1], f"completion_perplexity_diff_{ref_name}"), pair[0]),
)
return _with_recomputed_ranks([record for _, record in ordered])
# Default: prob_diff
ordered = sorted(
indexed_records,
key=lambda pair: (_num_desc(pair[1], "completion_prob_diff"), pair[0]),
)
return _with_recomputed_ranks([record for _, record in ordered])
def top_records_for_ordering(records: list[dict], ordering: str, top_k: int) -> list[dict]:
return order_records(records, ordering)[:top_k]
def write_ordering_file(
results_dir: Path,
records: list[dict],
ordering: str,
top_k: int,
*,
overwrite: bool,
) -> tuple[Path, bool]:
output_path = results_dir / ordering_filename(ordering)
if output_path.exists() and not overwrite:
return output_path, False
output_records = top_records_for_ordering(records, ordering, top_k)
with open(output_path, "w") as f:
json.dump(output_records, f, indent=2, ensure_ascii=False)
return output_path, True
def write_all_ordering_files(
results_dir: Path,
records: list[dict],
top_k: int,
*,
overwrite: bool,
) -> dict[str, dict]:
outputs = {}
for ordering in ORDERINGS:
path, wrote = write_ordering_file(
results_dir,
records,
ordering,
top_k,
overwrite=overwrite,
)
outputs[ordering] = {
"path": str(path),
"wrote": wrote,
}
return outputs
def materialize_ordering_for_results_dir(
results_dir: Path,
ordering: str,
*,
overwrite: bool = False,
) -> dict:
if ordering not in ORDERINGS:
raise ValueError(f"Unknown ordering: {ordering}")
records = load_all_completions(results_dir)
top_k = top_k_from_config_snapshot(results_dir / "config_snapshot.yaml")
output_path, wrote = write_ordering_file(
results_dir,
records,
ordering,
top_k,
overwrite=overwrite,
)
return {
"results_dir": str(results_dir),
"ordering": ordering,
"top_k": top_k,
"path": str(output_path),
"wrote": wrote,
}
def materialize_ordering_for_all(
base_dir: Path,
ordering: str,
*,
overwrite: bool = False,
) -> dict:
if ordering not in ORDERINGS:
raise ValueError(f"Unknown ordering: {ordering}")
wrote = 0
skipped = 0
results = []
for results_dir in iter_results_dirs(base_dir):
result = materialize_ordering_for_results_dir(
results_dir,
ordering,
overwrite=overwrite,
)
results.append(result)
if result["wrote"]:
wrote += 1
else:
skipped += 1
return {
"ordering": ordering,
"wrote": wrote,
"skipped": skipped,
"total": len(results),
"results": results,
}