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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Unlearning task evaluator.
|
| 3 |
+
|
| 4 |
+
Scoring
|
| 5 |
+
-------
|
| 6 |
+
Forget quality uses the original loss-distribution metric. For each
|
| 7 |
+
regular/mislabeled and public/held subset:
|
| 8 |
+
|
| 9 |
+
d_sub =
|
| 10 |
+
abs(mean(submitted_losses) - mean(gold_losses))
|
| 11 |
+
+
|
| 12 |
+
abs(std(submitted_losses) - std(gold_losses))
|
| 13 |
+
|
| 14 |
+
forget_subset_score =
|
| 15 |
+
1 - clip(d_sub / d_run2, 0, 1)
|
| 16 |
+
|
| 17 |
+
Here d_run2 is the precomputed mean/std loss distance between run2 and gold
|
| 18 |
+
on the same subset. Regular and mislabeled scores are averaged equally.
|
| 19 |
+
|
| 20 |
+
Retain quality uses both control accuracy and KL similarity to run2:
|
| 21 |
+
|
| 22 |
+
retain_accuracy_score =
|
| 23 |
+
clip(submitted_control_accuracy / run2_control_accuracy, 0, 1)
|
| 24 |
+
|
| 25 |
+
mean_retain_kl =
|
| 26 |
+
mean KL(p_run2(x) || p_submitted(x))
|
| 27 |
+
|
| 28 |
+
retain_kl_similarity =
|
| 29 |
+
1 / (1 + mean_retain_kl)
|
| 30 |
+
|
| 31 |
+
retain_score =
|
| 32 |
+
retain_accuracy_score * retain_kl_similarity
|
| 33 |
+
|
| 34 |
+
KL is used only for retain quality. Forget quality does not use KL or full
|
| 35 |
+
prediction-distribution matching.
|
| 36 |
+
|
| 37 |
+
The final score is:
|
| 38 |
+
|
| 39 |
+
score = forget_score * retain_score
|
| 40 |
+
|
| 41 |
+
Public and held-out scores are computed independently using the deterministic
|
| 42 |
+
hash split. Validation accuracy below UTILITY_THRESHOLD disqualifies the
|
| 43 |
+
submission and sets both scores to zero.
|
| 44 |
+
|
| 45 |
+
Required private reference files
|
| 46 |
+
--------------------------------
|
| 47 |
+
image_cache.npz
|
| 48 |
+
gold_per_sample_loss.json
|
| 49 |
+
f_calibration.json
|
| 50 |
+
reference_log_probs.npz
|
| 51 |
+
|
| 52 |
+
reference_log_probs.npz must contain:
|
| 53 |
+
temperature
|
| 54 |
+
control_ids
|
| 55 |
+
control_run2_log_probs
|
| 56 |
+
|
| 57 |
+
Usage:
|
| 58 |
+
UNLEARNING_REFERENCE_DIR=/path/to/reference_dir \
|
| 59 |
+
python evaluator_hybrid.py submission.pt
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
import os
|
| 63 |
+
import hashlib
|
| 64 |
+
import json
|
| 65 |
+
from functools import lru_cache
|
| 66 |
+
from pathlib import Path
|
| 67 |
+
from typing import Union
|
| 68 |
+
|
| 69 |
+
import numpy as np
|
| 70 |
+
import torch
|
| 71 |
+
import torch.nn as nn
|
| 72 |
+
from torchvision import models
|
| 73 |
+
|
| 74 |
+
NUM_CLASSES = 100
|
| 75 |
+
# Dropout(p) module must exist at fc.0 to match the state_dict key structure
|
| 76 |
+
# from training (fc.0=Dropout, fc.1=Linear). model.eval() makes Dropout a
|
| 77 |
+
# no-op, so the value of p is irrelevant here -- this is purely for
|
| 78 |
+
# load_state_dict() key/shape compatibility.
|
| 79 |
+
DROPOUT = 0.3
|
| 80 |
+
IMG_SIZE = 224
|
| 81 |
+
BATCH_SIZE = 128
|
| 82 |
+
UTILITY_THRESHOLD = 0.60
|
| 83 |
+
HELD_OUT_PCT = 0.7
|
| 84 |
+
KL_TEMPERATURE = 2.0
|
| 85 |
+
|
| 86 |
+
MEAN = [0.485, 0.456, 0.406]
|
| 87 |
+
STD = [0.229, 0.224, 0.225]
|
| 88 |
+
|
| 89 |
+
# subset definitions used throughout: (forget_type, is_held_out, label)
|
| 90 |
+
FORGET_TYPES = ["regular", "mislabeled"]
|
| 91 |
+
SPLITS = [("public", False), ("held", True)]
|
| 92 |
+
IMAGE_CACHE_SPLITS = ["forget", "control", "val"]
|
| 93 |
+
|
| 94 |
+
REFERENCE_DIR = Path(os.getenv(
|
| 95 |
+
"UNLEARNING_REFERENCE_DIR",
|
| 96 |
+
Path(__file__).parent,
|
| 97 |
+
))
|
| 98 |
+
|
| 99 |
+
MAX_BYTES = 300 * 1024 * 1024 # 300 MB hard limit, matches the platform body cap
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _ext_is_pt(path: str) -> bool:
|
| 103 |
+
return os.path.splitext(path)[1].lower() in {".pt", ".pth"}
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def build_model(num_classes: int) -> nn.Module:
|
| 107 |
+
model = models.resnet18(weights=None)
|
| 108 |
+
model.fc = nn.Sequential(
|
| 109 |
+
nn.Dropout(DROPOUT),
|
| 110 |
+
nn.Linear(model.fc.in_features, num_classes),
|
| 111 |
+
)
|
| 112 |
+
return model
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@lru_cache(maxsize=1)
|
| 116 |
+
def _get_image_cache():
|
| 117 |
+
# image_cache.npz stores a flat namespace ("{split}_images",
|
| 118 |
+
# "{split}_true_labels", etc, see build_evaluator_reference.py's
|
| 119 |
+
# save_image_cache_npz). reconstruct the nested per-split dict of
|
| 120 |
+
# torch tensors that _run_inference expects.
|
| 121 |
+
cache = {}
|
| 122 |
+
with np.load(REFERENCE_DIR / "image_cache.npz") as raw:
|
| 123 |
+
for split in IMAGE_CACHE_SPLITS:
|
| 124 |
+
cache[split] = {
|
| 125 |
+
"images": torch.from_numpy(raw[f"{split}_images"]),
|
| 126 |
+
"true_labels": torch.from_numpy(raw[f"{split}_true_labels"]),
|
| 127 |
+
"assigned_labels": torch.from_numpy(raw[f"{split}_assigned_labels"]),
|
| 128 |
+
"ids": [str(x) for x in raw[f"{split}_ids"]],
|
| 129 |
+
"types": [str(x) for x in raw[f"{split}_types"]],
|
| 130 |
+
}
|
| 131 |
+
return cache
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@lru_cache(maxsize=1)
|
| 135 |
+
def _get_gold_per_sample_loss():
|
| 136 |
+
return json.loads((REFERENCE_DIR / "gold_per_sample_loss.json").read_text())
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@lru_cache(maxsize=1)
|
| 140 |
+
def _get_f_calibration():
|
| 141 |
+
return json.loads((REFERENCE_DIR / "f_calibration.json").read_text())
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@lru_cache(maxsize=1)
|
| 145 |
+
def _get_run2_control_log_probs():
|
| 146 |
+
path = REFERENCE_DIR / "reference_log_probs.npz"
|
| 147 |
+
|
| 148 |
+
with np.load(path) as raw:
|
| 149 |
+
required = {
|
| 150 |
+
"temperature",
|
| 151 |
+
"control_ids",
|
| 152 |
+
"control_run2_log_probs",
|
| 153 |
+
}
|
| 154 |
+
missing = sorted(required - set(raw.files))
|
| 155 |
+
if missing:
|
| 156 |
+
raise KeyError(f"{path} is missing required arrays: {missing}")
|
| 157 |
+
|
| 158 |
+
temperature = float(np.asarray(raw["temperature"]).reshape(-1)[0])
|
| 159 |
+
if not np.isclose(temperature, KL_TEMPERATURE, atol=1e-8):
|
| 160 |
+
raise ValueError(
|
| 161 |
+
"KL temperature mismatch: "
|
| 162 |
+
f"evaluator={KL_TEMPERATURE}, reference={temperature}"
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
ids = [str(x) for x in raw["control_ids"]]
|
| 166 |
+
log_probs = torch.from_numpy(raw["control_run2_log_probs"]).float()
|
| 167 |
+
|
| 168 |
+
if len(ids) != log_probs.shape[0]:
|
| 169 |
+
raise ValueError(
|
| 170 |
+
"control_ids and control_run2_log_probs have different lengths"
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
return {
|
| 174 |
+
sid: log_probs[index]
|
| 175 |
+
for index, sid in enumerate(ids)
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def _hash_to_split(id_value: Union[int, str], held_out_pct: float = HELD_OUT_PCT) -> bool:
|
| 180 |
+
"""Deterministic hash split based on sample id. True = held-out (70%, final leaderboard)."""
|
| 181 |
+
id_str = str(id_value)
|
| 182 |
+
h = hashlib.md5(id_str.encode()).hexdigest()
|
| 183 |
+
hash_int = int(h[:8], 16)
|
| 184 |
+
return (hash_int % 100) < (held_out_pct * 100)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
@torch.no_grad()
|
| 188 |
+
def _run_inference(
|
| 189 |
+
model,
|
| 190 |
+
cache_entry,
|
| 191 |
+
device,
|
| 192 |
+
batch_size=BATCH_SIZE,
|
| 193 |
+
return_log_probs=False,
|
| 194 |
+
):
|
| 195 |
+
"""Returns per-sample loss/correctness and optional log-probabilities."""
|
| 196 |
+
images = cache_entry["images"]
|
| 197 |
+
true_labels = cache_entry["true_labels"]
|
| 198 |
+
ids = cache_entry["ids"]
|
| 199 |
+
n = images.shape[0]
|
| 200 |
+
results = {}
|
| 201 |
+
|
| 202 |
+
for start in range(0, n, batch_size):
|
| 203 |
+
end = min(start + batch_size, n)
|
| 204 |
+
imgs = images[start:end].to(device)
|
| 205 |
+
labels_d = true_labels[start:end].to(device)
|
| 206 |
+
|
| 207 |
+
with torch.autocast(device_type=device.type, dtype=torch.float16):
|
| 208 |
+
logits = model(imgs)
|
| 209 |
+
per_sample_loss = nn.functional.cross_entropy(
|
| 210 |
+
logits,
|
| 211 |
+
labels_d,
|
| 212 |
+
reduction="none",
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
logits_float = logits.float()
|
| 216 |
+
if not torch.isfinite(logits_float).all():
|
| 217 |
+
raise ValueError("Model produced non-finite logits")
|
| 218 |
+
|
| 219 |
+
preds = logits_float.argmax(1).cpu()
|
| 220 |
+
losses = per_sample_loss.float().cpu()
|
| 221 |
+
|
| 222 |
+
if return_log_probs:
|
| 223 |
+
log_probs = nn.functional.log_softmax(
|
| 224 |
+
logits_float / KL_TEMPERATURE,
|
| 225 |
+
dim=1,
|
| 226 |
+
).cpu()
|
| 227 |
+
if not torch.isfinite(log_probs).all():
|
| 228 |
+
raise ValueError("Model produced non-finite log-probabilities")
|
| 229 |
+
else:
|
| 230 |
+
log_probs = None
|
| 231 |
+
|
| 232 |
+
for i in range(end - start):
|
| 233 |
+
sid = ids[start + i]
|
| 234 |
+
t_label = int(true_labels[start + i])
|
| 235 |
+
results[sid] = {
|
| 236 |
+
"loss": float(losses[i]),
|
| 237 |
+
"pred": int(preds[i]),
|
| 238 |
+
"true_label": t_label,
|
| 239 |
+
"correct_true": int(preds[i] == t_label),
|
| 240 |
+
}
|
| 241 |
+
if return_log_probs:
|
| 242 |
+
results[sid]["log_probs"] = log_probs[i]
|
| 243 |
+
|
| 244 |
+
return results
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def _mean_std_distance(sub_losses, gold_losses):
|
| 248 |
+
sub_losses = np.array(sub_losses)
|
| 249 |
+
gold_losses = np.array(gold_losses)
|
| 250 |
+
mean_diff = abs(sub_losses.mean() - gold_losses.mean())
|
| 251 |
+
std_diff = abs(sub_losses.std() - gold_losses.std())
|
| 252 |
+
d = float(mean_diff + std_diff)
|
| 253 |
+
return d, {
|
| 254 |
+
"submitted_mean_loss": float(sub_losses.mean()),
|
| 255 |
+
"submitted_std_loss": float(sub_losses.std()),
|
| 256 |
+
"gold_mean_loss": float(gold_losses.mean()),
|
| 257 |
+
"gold_std_loss": float(gold_losses.std()),
|
| 258 |
+
"mean_diff": float(mean_diff),
|
| 259 |
+
"std_diff": float(std_diff),
|
| 260 |
+
"d_submitted_vs_gold": d,
|
| 261 |
+
"n_samples": len(sub_losses),
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def _subset_ids(gold_forget, forget_type, is_held):
|
| 266 |
+
return [
|
| 267 |
+
sid for sid, entry in gold_forget.items()
|
| 268 |
+
if entry["type"] == forget_type and _hash_to_split(sid) == is_held
|
| 269 |
+
]
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def _score_forget_subset(forget_inf, gold_forget, f_calibration, forget_type, is_held):
|
| 273 |
+
"""
|
| 274 |
+
Scores ONE forget subset (e.g. "regular" samples in the "public" split).
|
| 275 |
+
|
| 276 |
+
Returns:
|
| 277 |
+
score -- 1 = matches gold exactly, 0 = no better than run2 (or worse,
|
| 278 |
+
clipped), in between = fraction of run2->gold gap closed.
|
| 279 |
+
detail -- dict with the raw numbers behind the score, for debugging
|
| 280 |
+
and for showing participants WHY they got this score.
|
| 281 |
+
"""
|
| 282 |
+
split_label = "held" if is_held else "public"
|
| 283 |
+
calibration_key = f"{forget_type}_{split_label}"
|
| 284 |
+
ids = _subset_ids(gold_forget, forget_type, is_held)
|
| 285 |
+
|
| 286 |
+
if calibration_key not in f_calibration or len(ids) == 0:
|
| 287 |
+
return 0.0, {
|
| 288 |
+
"forget_subset": f"forget_{forget_type}_{split_label}",
|
| 289 |
+
"warning": f"no calibration/samples for subset '{calibration_key}'",
|
| 290 |
+
"n_forget_samples_in_subset": len(ids),
|
| 291 |
+
"forget_score_this_subset": 0.0,
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
d_run2 = f_calibration[calibration_key]["d_run2"]
|
| 295 |
+
sub_losses = [forget_inf[sid]["loss"] for sid in ids]
|
| 296 |
+
gold_losses = [gold_forget[sid]["loss"] for sid in ids]
|
| 297 |
+
|
| 298 |
+
d_sub, detail = _mean_std_distance(sub_losses, gold_losses)
|
| 299 |
+
detail["forget_type"] = forget_type
|
| 300 |
+
detail["split"] = split_label
|
| 301 |
+
detail["d_run2_reference"] = d_run2
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
if d_run2 <= 0:
|
| 305 |
+
score = 0.0
|
| 306 |
+
else:
|
| 307 |
+
progress = d_sub / d_run2
|
| 308 |
+
score = 1.0 - min(max(progress, 0.0), 1.0)
|
| 309 |
+
|
| 310 |
+
detail["progress_toward_gold"] = score
|
| 311 |
+
return score, detail
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def _per_sample_kl(reference_log_probs, submitted_log_probs):
|
| 315 |
+
reference_log_probs = reference_log_probs.double()
|
| 316 |
+
submitted_log_probs = submitted_log_probs.double()
|
| 317 |
+
reference_probs = reference_log_probs.exp()
|
| 318 |
+
|
| 319 |
+
kl = torch.sum(
|
| 320 |
+
reference_probs
|
| 321 |
+
* (reference_log_probs - submitted_log_probs)
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
return max(float(kl), 0.0)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def _score_control_subset(
|
| 328 |
+
control_inf,
|
| 329 |
+
run2_control_log_probs,
|
| 330 |
+
f_calibration,
|
| 331 |
+
is_held,
|
| 332 |
+
):
|
| 333 |
+
"""Scores control retention with accuracy and KL similarity to run2."""
|
| 334 |
+
split_label = "held" if is_held else "public"
|
| 335 |
+
control_calibration = f_calibration.get("control", {})
|
| 336 |
+
split_calibration = control_calibration.get(split_label)
|
| 337 |
+
|
| 338 |
+
ids = [sid for sid in control_inf.keys() if _hash_to_split(sid) == is_held]
|
| 339 |
+
|
| 340 |
+
if split_calibration is None or len(ids) == 0:
|
| 341 |
+
return 0.0, {
|
| 342 |
+
"control_subset": f"control_{split_label}",
|
| 343 |
+
"warning": f"no calibration/samples for control subset '{split_label}'",
|
| 344 |
+
"n_control_samples_in_subset": len(ids),
|
| 345 |
+
"retain_score_this_subset": 0.0,
|
| 346 |
+
}
|
| 347 |
+
|
| 348 |
+
acc_run2 = split_calibration["run2_control_accuracy"]
|
| 349 |
+
n = len(ids)
|
| 350 |
+
n_correct = sum(control_inf[sid]["correct_true"] for sid in ids)
|
| 351 |
+
acc_sub = n_correct / n
|
| 352 |
+
|
| 353 |
+
if acc_run2 <= 0:
|
| 354 |
+
accuracy_score = 0.0
|
| 355 |
+
else:
|
| 356 |
+
accuracy_score = min(max(acc_sub / acc_run2, 0.0), 1.0)
|
| 357 |
+
|
| 358 |
+
kl_values = []
|
| 359 |
+
for sid in ids:
|
| 360 |
+
if sid not in run2_control_log_probs:
|
| 361 |
+
raise KeyError(
|
| 362 |
+
f"Missing cached run2 control log-probabilities for {sid}"
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
kl_values.append(
|
| 366 |
+
_per_sample_kl(
|
| 367 |
+
run2_control_log_probs[sid],
|
| 368 |
+
control_inf[sid]["log_probs"],
|
| 369 |
+
)
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
mean_kl = float(np.mean(kl_values))
|
| 373 |
+
kl_similarity = 1.0 / (1.0 + mean_kl)
|
| 374 |
+
score = accuracy_score * kl_similarity
|
| 375 |
+
|
| 376 |
+
detail = {
|
| 377 |
+
"control_subset": f"control_{split_label}",
|
| 378 |
+
"temperature": KL_TEMPERATURE,
|
| 379 |
+
"n_control_samples_in_subset": n,
|
| 380 |
+
"submitted_model_control_accuracy": acc_sub,
|
| 381 |
+
"run2_control_accuracy_reference": acc_run2,
|
| 382 |
+
"retain_accuracy_score": accuracy_score,
|
| 383 |
+
"mean_retain_kl": mean_kl,
|
| 384 |
+
"retain_kl_similarity": kl_similarity,
|
| 385 |
+
"retain_score_this_subset": score,
|
| 386 |
+
}
|
| 387 |
+
return score, detail
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def _compute_utility(val_results):
|
| 391 |
+
n = len(val_results)
|
| 392 |
+
acc = sum(r["correct_true"] for r in val_results.values()) / n
|
| 393 |
+
return acc, {"validation_set_accuracy": acc, "n_validation_samples": n}
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def evaluator(payload: dict) -> Union[dict, str]:
|
| 397 |
+
path = payload["file_path"]
|
| 398 |
+
|
| 399 |
+
if not _ext_is_pt(path):
|
| 400 |
+
return "File extension must be .pt or .pth"
|
| 401 |
+
|
| 402 |
+
try:
|
| 403 |
+
if os.path.getsize(path) > MAX_BYTES:
|
| 404 |
+
return f"File too large: limit {MAX_BYTES} bytes."
|
| 405 |
+
except OSError as e:
|
| 406 |
+
return f"Could not access file: {e!r}"
|
| 407 |
+
|
| 408 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 409 |
+
|
| 410 |
+
try:
|
| 411 |
+
model = build_model(NUM_CLASSES).to(device)
|
| 412 |
+
state = torch.load(path, map_location=device, weights_only=True)
|
| 413 |
+
# accept either a raw state_dict or a checkpoint dict with "model" key
|
| 414 |
+
if isinstance(state, dict) and "model" in state and "state_dict" not in state:
|
| 415 |
+
state = state["model"]
|
| 416 |
+
elif isinstance(state, dict) and "state_dict" in state:
|
| 417 |
+
state = state["state_dict"]
|
| 418 |
+
model.load_state_dict(state)
|
| 419 |
+
model.eval()
|
| 420 |
+
except Exception as e:
|
| 421 |
+
return f"Failed to load model state_dict: {e!r}"
|
| 422 |
+
|
| 423 |
+
try:
|
| 424 |
+
gold_per_sample = _get_gold_per_sample_loss()
|
| 425 |
+
gold_forget = gold_per_sample["forget"]
|
| 426 |
+
image_cache = _get_image_cache()
|
| 427 |
+
f_calibration = _get_f_calibration()
|
| 428 |
+
run2_control_log_probs = _get_run2_control_log_probs()
|
| 429 |
+
except Exception as e:
|
| 430 |
+
return f"Internal reference data error: {e!r}"
|
| 431 |
+
|
| 432 |
+
try:
|
| 433 |
+
forget_inf = _run_inference(model, image_cache["forget"], device)
|
| 434 |
+
control_inf = _run_inference(
|
| 435 |
+
model,
|
| 436 |
+
image_cache["control"],
|
| 437 |
+
device,
|
| 438 |
+
return_log_probs=True,
|
| 439 |
+
)
|
| 440 |
+
val_inf = _run_inference(model, image_cache["val"], device)
|
| 441 |
+
|
| 442 |
+
# utility gate (computed on full val set, not split)
|
| 443 |
+
U, utility_detail = _compute_utility(val_inf)
|
| 444 |
+
if U < UTILITY_THRESHOLD:
|
| 445 |
+
return {
|
| 446 |
+
"score": 0.0,
|
| 447 |
+
"score_held_out": 0.0,
|
| 448 |
+
"disqualified": True,
|
| 449 |
+
"reason": (
|
| 450 |
+
f"validation set accuracy {U:.4f} is below the utility "
|
| 451 |
+
f"threshold {UTILITY_THRESHOLD} -- model is too damaged "
|
| 452 |
+
f"to be useful, regardless of forget-quality scores."
|
| 453 |
+
),
|
| 454 |
+
"utility_check": utility_detail,
|
| 455 |
+
}
|
| 456 |
+
|
| 457 |
+
# score each (forget_type, split) combination for F
|
| 458 |
+
scores = {}
|
| 459 |
+
details = {}
|
| 460 |
+
for split_label, is_held in SPLITS:
|
| 461 |
+
for forget_type in FORGET_TYPES:
|
| 462 |
+
s, d = _score_forget_subset(forget_inf, gold_forget, f_calibration, forget_type, is_held)
|
| 463 |
+
scores[(split_label, forget_type)] = s
|
| 464 |
+
details[(split_label, forget_type)] = d
|
| 465 |
+
|
| 466 |
+
forget_score_public = 0.5 * scores[("public", "regular")] + 0.5 * scores[("public", "mislabeled")]
|
| 467 |
+
forget_score_held = 0.5 * scores[("held", "regular")] + 0.5 * scores[("held", "mislabeled")]
|
| 468 |
+
|
| 469 |
+
# score the control set for R, per split
|
| 470 |
+
retain_score_public, retain_detail_public = _score_control_subset(
|
| 471 |
+
control_inf,
|
| 472 |
+
run2_control_log_probs,
|
| 473 |
+
f_calibration,
|
| 474 |
+
False,
|
| 475 |
+
)
|
| 476 |
+
retain_score_held, retain_detail_held = _score_control_subset(
|
| 477 |
+
control_inf,
|
| 478 |
+
run2_control_log_probs,
|
| 479 |
+
f_calibration,
|
| 480 |
+
True,
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
score_public = forget_score_public * retain_score_public
|
| 484 |
+
score_held = forget_score_held * retain_score_held
|
| 485 |
+
|
| 486 |
+
return {
|
| 487 |
+
"score": score_public,
|
| 488 |
+
"score_held_out": score_held,
|
| 489 |
+
"disqualified": False,
|
| 490 |
+
# "utility_check": utility_detail,
|
| 491 |
+
"forget_quality_public_split": {
|
| 492 |
+
"forget_score_overall": forget_score_public,
|
| 493 |
+
# "forget_score_regular_subset": scores[("public", "regular")],
|
| 494 |
+
# "forget_score_mislabeled_subset": scores[("public", "mislabeled")],
|
| 495 |
+
# "forget_regular_subset_detail": details[("public", "regular")],
|
| 496 |
+
# "forget_mislabeled_subset_detail": details[("public", "mislabeled")],
|
| 497 |
+
},
|
| 498 |
+
"forget_quality_held_out_split": {
|
| 499 |
+
"forget_score_overall": forget_score_held,
|
| 500 |
+
# "forget_score_regular_subset": scores[("held", "regular")],
|
| 501 |
+
# "forget_score_mislabeled_subset": scores[("held", "mislabeled")],
|
| 502 |
+
# "forget_regular_subset_detail": details[("held", "regular")],
|
| 503 |
+
# "forget_mislabeled_subset_detail": details[("held", "mislabeled")],
|
| 504 |
+
},
|
| 505 |
+
"retain_quality_public_split": {
|
| 506 |
+
"retain_score_overall": retain_score_public,
|
| 507 |
+
# "retain_control_subset_detail": retain_detail_public,
|
| 508 |
+
},
|
| 509 |
+
"retain_quality_held_out_split": {
|
| 510 |
+
"retain_score_overall": retain_score_held,
|
| 511 |
+
# "retain_control_subset_detail": retain_detail_held,
|
| 512 |
+
},
|
| 513 |
+
}
|
| 514 |
+
|
| 515 |
+
except Exception as e:
|
| 516 |
+
return f"Internal scoring error: {e!r}"
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
if __name__ == "__main__":
|
| 520 |
+
import sys
|
| 521 |
+
|
| 522 |
+
if len(sys.argv) != 2:
|
| 523 |
+
print(f"usage: python {sys.argv[0]} <submission.pt>")
|
| 524 |
+
sys.exit(1)
|
| 525 |
+
|
| 526 |
+
result = evaluator({"file_path": sys.argv[1]})
|
| 527 |
+
print(json.dumps(result, indent=2))
|
f_calibration.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"regular_public": {
|
| 3 |
+
"d_run2": 2.026709086398549,
|
| 4 |
+
"run2_mean_loss": 0.07717726951287616,
|
| 5 |
+
"run2_std_loss": 0.061606936670246186,
|
| 6 |
+
"gold_mean_loss": 0.8774403531813906,
|
| 7 |
+
"gold_std_loss": 1.2880529394002809,
|
| 8 |
+
"mean_diff": 0.8002630836685144,
|
| 9 |
+
"std_diff": 1.2264460027300348,
|
| 10 |
+
"n": 210
|
| 11 |
+
},
|
| 12 |
+
"regular_held": {
|
| 13 |
+
"d_run2": 2.412559384581363,
|
| 14 |
+
"run2_mean_loss": 0.07665387168009248,
|
| 15 |
+
"run2_std_loss": 0.04125143385786665,
|
| 16 |
+
"gold_mean_loss": 0.9781371205320789,
|
| 17 |
+
"gold_std_loss": 1.5523275695872434,
|
| 18 |
+
"mean_diff": 0.9014832488519864,
|
| 19 |
+
"std_diff": 1.5110761357293767,
|
| 20 |
+
"n": 540
|
| 21 |
+
},
|
| 22 |
+
"mislabeled_public": {
|
| 23 |
+
"d_run2": 3.314025374430923,
|
| 24 |
+
"run2_mean_loss": 3.091929525814273,
|
| 25 |
+
"run2_std_loss": 2.190022208404777,
|
| 26 |
+
"gold_mean_loss": 0.7317555246197365,
|
| 27 |
+
"gold_std_loss": 1.2361708351683904,
|
| 28 |
+
"mean_diff": 2.3601740011945367,
|
| 29 |
+
"std_diff": 0.9538513732363865,
|
| 30 |
+
"n": 77
|
| 31 |
+
},
|
| 32 |
+
"mislabeled_held": {
|
| 33 |
+
"d_run2": 3.297817541991741,
|
| 34 |
+
"run2_mean_loss": 3.5562703608605215,
|
| 35 |
+
"run2_std_loss": 2.2562758353008303,
|
| 36 |
+
"gold_mean_loss": 0.997029911123776,
|
| 37 |
+
"gold_std_loss": 1.5176987430458349,
|
| 38 |
+
"mean_diff": 2.5592404497367456,
|
| 39 |
+
"std_diff": 0.7385770922549955,
|
| 40 |
+
"n": 173
|
| 41 |
+
},
|
| 42 |
+
"control": {
|
| 43 |
+
"public": {
|
| 44 |
+
"run2_control_accuracy": 0.866233766078949,
|
| 45 |
+
"gold_control_accuracy": 0.86753249168396,
|
| 46 |
+
"n": 770
|
| 47 |
+
},
|
| 48 |
+
"held": {
|
| 49 |
+
"run2_control_accuracy": 0.8780347108840942,
|
| 50 |
+
"gold_control_accuracy": 0.8757225275039673,
|
| 51 |
+
"n": 1730
|
| 52 |
+
}
|
| 53 |
+
}
|
| 54 |
+
}
|
gold_per_sample_loss.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
reference_log_probs.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4d90fefe3f725b231ebfb15e2fbd9e3bb1cf41e67448acb38443e912ddc46718
|
| 3 |
+
size 673696
|