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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
"""
Unlearning task evaluator.

Scoring
-------
Forget quality uses the original loss-distribution metric. For each
regular/mislabeled and public/held subset:

    d_sub =
        abs(mean(submitted_losses) - mean(gold_losses))
        +
        abs(std(submitted_losses) - std(gold_losses))

    forget_subset_score =
        1 - clip(d_sub / d_run2, 0, 1)

Here d_run2 is the precomputed mean/std loss distance between run2 and gold
on the same subset. Regular and mislabeled scores are averaged equally.

Retain quality uses both control accuracy and KL similarity to run2:

    retain_accuracy_score =
        clip(submitted_control_accuracy / run2_control_accuracy, 0, 1)

    mean_retain_kl =
        mean KL(p_run2(x) || p_submitted(x))

    retain_kl_similarity =
        1 / (1 + mean_retain_kl)

    retain_score =
        retain_accuracy_score * retain_kl_similarity

KL is used only for retain quality. Forget quality does not use KL or full
prediction-distribution matching.

The final score is:

    score = forget_score * retain_score

Public and held-out scores are computed independently using the deterministic
hash split. Validation accuracy below UTILITY_THRESHOLD disqualifies the
submission and sets both scores to zero.

Required private reference files
--------------------------------
  image_cache.npz
  gold_per_sample_loss.json
  f_calibration.json
  reference_log_probs.npz

reference_log_probs.npz must contain:
  temperature
  control_ids
  control_run2_log_probs

Usage:
    UNLEARNING_REFERENCE_DIR=/path/to/reference_dir \
        python evaluator_hybrid.py submission.pt
"""

import os
import hashlib
import json
from functools import lru_cache
from pathlib import Path
from typing import Union

import numpy as np
import torch
import torch.nn as nn
from torchvision import models

NUM_CLASSES = 100
# Dropout(p) module must exist at fc.0 to match the state_dict key structure
# from training (fc.0=Dropout, fc.1=Linear). model.eval() makes Dropout a
# no-op, so the value of p is irrelevant here -- this is purely for
# load_state_dict() key/shape compatibility.
DROPOUT = 0.3
IMG_SIZE = 224
BATCH_SIZE = 128
UTILITY_THRESHOLD = 0.60
HELD_OUT_PCT = 0.7
KL_TEMPERATURE = 2.0

MEAN = [0.485, 0.456, 0.406]
STD = [0.229, 0.224, 0.225]

# subset definitions used throughout: (forget_type, is_held_out, label)
FORGET_TYPES = ["regular", "mislabeled"]
SPLITS = [("public", False), ("held", True)]
IMAGE_CACHE_SPLITS = ["forget", "control", "val"]

REFERENCE_DIR = Path(os.getenv(
    "UNLEARNING_REFERENCE_DIR",
    Path(__file__).parent,
))

MAX_BYTES = 300 * 1024 * 1024  # 300 MB hard limit, matches the platform body cap


def _ext_is_pt(path: str) -> bool:
    return os.path.splitext(path)[1].lower() in {".pt", ".pth"}


def build_model(num_classes: int) -> nn.Module:
    model = models.resnet18(weights=None)
    model.fc = nn.Sequential(
        nn.Dropout(DROPOUT),
        nn.Linear(model.fc.in_features, num_classes),
    )
    return model


@lru_cache(maxsize=1)
def _get_image_cache():
    # image_cache.npz stores a flat namespace ("{split}_images",
    # "{split}_true_labels", etc, see build_evaluator_reference.py's
    # save_image_cache_npz). reconstruct the nested per-split dict of
    # torch tensors that _run_inference expects.
    cache = {}
    with np.load(REFERENCE_DIR / "image_cache.npz") as raw:
        for split in IMAGE_CACHE_SPLITS:
            cache[split] = {
                "images": torch.from_numpy(raw[f"{split}_images"]),
                "true_labels": torch.from_numpy(raw[f"{split}_true_labels"]),
                "assigned_labels": torch.from_numpy(raw[f"{split}_assigned_labels"]),
                "ids": [str(x) for x in raw[f"{split}_ids"]],
                "types": [str(x) for x in raw[f"{split}_types"]],
            }
    return cache


@lru_cache(maxsize=1)
def _get_gold_per_sample_loss():
    return json.loads((REFERENCE_DIR / "gold_per_sample_loss.json").read_text())


@lru_cache(maxsize=1)
def _get_f_calibration():
    return json.loads((REFERENCE_DIR / "f_calibration.json").read_text())


@lru_cache(maxsize=1)
def _get_run2_control_log_probs():
    path = REFERENCE_DIR / "reference_log_probs.npz"

    with np.load(path) as raw:
        required = {
            "temperature",
            "control_ids",
            "control_run2_log_probs",
        }
        missing = sorted(required - set(raw.files))
        if missing:
            raise KeyError(f"{path} is missing required arrays: {missing}")

        temperature = float(np.asarray(raw["temperature"]).reshape(-1)[0])
        if not np.isclose(temperature, KL_TEMPERATURE, atol=1e-8):
            raise ValueError(
                "KL temperature mismatch: "
                f"evaluator={KL_TEMPERATURE}, reference={temperature}"
            )

        ids = [str(x) for x in raw["control_ids"]]
        log_probs = torch.from_numpy(raw["control_run2_log_probs"]).float()

    if len(ids) != log_probs.shape[0]:
        raise ValueError(
            "control_ids and control_run2_log_probs have different lengths"
        )

    return {
        sid: log_probs[index]
        for index, sid in enumerate(ids)
    }


def _hash_to_split(id_value: Union[int, str], held_out_pct: float = HELD_OUT_PCT) -> bool:
    """Deterministic hash split based on sample id. True = held-out (70%, final leaderboard)."""
    id_str = str(id_value)
    h = hashlib.md5(id_str.encode()).hexdigest()
    hash_int = int(h[:8], 16)
    return (hash_int % 100) < (held_out_pct * 100)


@torch.no_grad()
def _run_inference(
    model,
    cache_entry,
    device,
    batch_size=BATCH_SIZE,
    return_log_probs=False,
):
    """Returns per-sample loss/correctness and optional log-probabilities."""
    images = cache_entry["images"]
    true_labels = cache_entry["true_labels"]
    ids = cache_entry["ids"]
    n = images.shape[0]
    results = {}

    for start in range(0, n, batch_size):
        end = min(start + batch_size, n)
        imgs = images[start:end].to(device)
        labels_d = true_labels[start:end].to(device)

        with torch.autocast(device_type=device.type, dtype=torch.float16):
            logits = model(imgs)
            per_sample_loss = nn.functional.cross_entropy(
                logits,
                labels_d,
                reduction="none",
            )

        logits_float = logits.float()
        if not torch.isfinite(logits_float).all():
            raise ValueError("Model produced non-finite logits")

        preds = logits_float.argmax(1).cpu()
        losses = per_sample_loss.float().cpu()

        if return_log_probs:
            log_probs = nn.functional.log_softmax(
                logits_float / KL_TEMPERATURE,
                dim=1,
            ).cpu()
            if not torch.isfinite(log_probs).all():
                raise ValueError("Model produced non-finite log-probabilities")
        else:
            log_probs = None

        for i in range(end - start):
            sid = ids[start + i]
            t_label = int(true_labels[start + i])
            results[sid] = {
                "loss": float(losses[i]),
                "pred": int(preds[i]),
                "true_label": t_label,
                "correct_true": int(preds[i] == t_label),
            }
            if return_log_probs:
                results[sid]["log_probs"] = log_probs[i]

    return results


def _mean_std_distance(sub_losses, gold_losses):
    sub_losses = np.array(sub_losses)
    gold_losses = np.array(gold_losses)
    mean_diff = abs(sub_losses.mean() - gold_losses.mean())
    std_diff = abs(sub_losses.std() - gold_losses.std())
    d = float(mean_diff + std_diff)
    return d, {
        "submitted_mean_loss": float(sub_losses.mean()),
        "submitted_std_loss": float(sub_losses.std()),
        "gold_mean_loss": float(gold_losses.mean()),
        "gold_std_loss": float(gold_losses.std()),
        "mean_diff": float(mean_diff),
        "std_diff": float(std_diff),
        "d_submitted_vs_gold": d,
        "n_samples": len(sub_losses),
    }


def _subset_ids(gold_forget, forget_type, is_held):
    return [
        sid for sid, entry in gold_forget.items()
        if entry["type"] == forget_type and _hash_to_split(sid) == is_held
    ]


def _score_forget_subset(forget_inf, gold_forget, f_calibration, forget_type, is_held):
    """
    Scores ONE forget subset (e.g. "regular" samples in the "public" split).

    Returns:
      score  -- 1 = matches gold exactly, 0 = no better than run2 (or worse,
                clipped), in between = fraction of run2->gold gap closed.
      detail -- dict with the raw numbers behind the score, for debugging
                and for showing participants WHY they got this score.
    """
    split_label = "held" if is_held else "public"
    calibration_key = f"{forget_type}_{split_label}"
    ids = _subset_ids(gold_forget, forget_type, is_held)

    if calibration_key not in f_calibration or len(ids) == 0:
        return 0.0, {
            "forget_subset": f"forget_{forget_type}_{split_label}",
            "warning": f"no calibration/samples for subset '{calibration_key}'",
            "n_forget_samples_in_subset": len(ids),
            "forget_score_this_subset": 0.0,
        }

    d_run2 = f_calibration[calibration_key]["d_run2"]
    sub_losses = [forget_inf[sid]["loss"] for sid in ids]
    gold_losses = [gold_forget[sid]["loss"] for sid in ids]

    d_sub, detail = _mean_std_distance(sub_losses, gold_losses)
    detail["forget_type"] = forget_type
    detail["split"] = split_label
    detail["d_run2_reference"] = d_run2


    if d_run2 <= 0:
        score = 0.0
    else:
        progress = d_sub / d_run2
        score = 1.0 - min(max(progress, 0.0), 1.0)

    detail["progress_toward_gold"] = score
    return score, detail


def _per_sample_kl(reference_log_probs, submitted_log_probs):
    reference_log_probs = reference_log_probs.double()
    submitted_log_probs = submitted_log_probs.double()
    reference_probs = reference_log_probs.exp()

    kl = torch.sum(
        reference_probs
        * (reference_log_probs - submitted_log_probs)
    )

    return max(float(kl), 0.0)


def _score_control_subset(
    control_inf,
    run2_control_log_probs,
    f_calibration,
    is_held,
):
    """Scores control retention with accuracy and KL similarity to run2."""
    split_label = "held" if is_held else "public"
    control_calibration = f_calibration.get("control", {})
    split_calibration = control_calibration.get(split_label)

    ids = [sid for sid in control_inf.keys() if _hash_to_split(sid) == is_held]

    if split_calibration is None or len(ids) == 0:
        return 0.0, {
            "control_subset": f"control_{split_label}",
            "warning": f"no calibration/samples for control subset '{split_label}'",
            "n_control_samples_in_subset": len(ids),
            "retain_score_this_subset": 0.0,
        }

    acc_run2 = split_calibration["run2_control_accuracy"]
    n = len(ids)
    n_correct = sum(control_inf[sid]["correct_true"] for sid in ids)
    acc_sub = n_correct / n

    if acc_run2 <= 0:
        accuracy_score = 0.0
    else:
        accuracy_score = min(max(acc_sub / acc_run2, 0.0), 1.0)

    kl_values = []
    for sid in ids:
        if sid not in run2_control_log_probs:
            raise KeyError(
                f"Missing cached run2 control log-probabilities for {sid}"
            )

        kl_values.append(
            _per_sample_kl(
                run2_control_log_probs[sid],
                control_inf[sid]["log_probs"],
            )
        )

    mean_kl = float(np.mean(kl_values))
    kl_similarity = 1.0 / (1.0 + mean_kl)
    score = accuracy_score * kl_similarity

    detail = {
        "control_subset": f"control_{split_label}",
        "temperature": KL_TEMPERATURE,
        "n_control_samples_in_subset": n,
        "submitted_model_control_accuracy": acc_sub,
        "run2_control_accuracy_reference": acc_run2,
        "retain_accuracy_score": accuracy_score,
        "mean_retain_kl": mean_kl,
        "retain_kl_similarity": kl_similarity,
        "retain_score_this_subset": score,
    }
    return score, detail


def _compute_utility(val_results):
    n = len(val_results)
    acc = sum(r["correct_true"] for r in val_results.values()) / n
    return acc, {"validation_set_accuracy": acc, "n_validation_samples": n}


def evaluator(payload: dict) -> Union[dict, str]:
    path = payload["file_path"]

    if not _ext_is_pt(path):
        return "File extension must be .pt or .pth"

    try:
        if os.path.getsize(path) > MAX_BYTES:
            return f"File too large: limit {MAX_BYTES} bytes."
    except OSError as e:
        return f"Could not access file: {e!r}"

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    try:
        model = build_model(NUM_CLASSES).to(device)
        state = torch.load(path, map_location=device, weights_only=True)
        # accept either a raw state_dict or a checkpoint dict with "model" key
        if isinstance(state, dict) and "model" in state and "state_dict" not in state:
            state = state["model"]
        elif isinstance(state, dict) and "state_dict" in state:
            state = state["state_dict"]
        model.load_state_dict(state)
        model.eval()
    except Exception as e:
        return f"Failed to load model state_dict: {e!r}"

    try:
        gold_per_sample = _get_gold_per_sample_loss()
        gold_forget = gold_per_sample["forget"]
        image_cache = _get_image_cache()
        f_calibration = _get_f_calibration()
        run2_control_log_probs = _get_run2_control_log_probs()
    except Exception as e:
        return f"Internal reference data error: {e!r}"

    try:
        forget_inf = _run_inference(model, image_cache["forget"], device)
        control_inf = _run_inference(
            model,
            image_cache["control"],
            device,
            return_log_probs=True,
        )
        val_inf = _run_inference(model, image_cache["val"], device)

        # utility gate (computed on full val set, not split)
        U, utility_detail = _compute_utility(val_inf)
        if U < UTILITY_THRESHOLD:
            return {
                "score": 0.0,
                "score_held_out": 0.0,
                "disqualified": True,
                "reason": (
                    f"validation set accuracy {U:.4f} is below the utility "
                    f"threshold {UTILITY_THRESHOLD} -- model is too damaged "
                    f"to be useful, regardless of forget-quality scores."
                ),
                "utility_check": utility_detail,
            }

        # score each (forget_type, split) combination for F
        scores = {}
        details = {}
        for split_label, is_held in SPLITS:
            for forget_type in FORGET_TYPES:
                s, d = _score_forget_subset(forget_inf, gold_forget, f_calibration, forget_type, is_held)
                scores[(split_label, forget_type)] = s
                details[(split_label, forget_type)] = d

        forget_score_public = 0.5 * scores[("public", "regular")] + 0.5 * scores[("public", "mislabeled")]
        forget_score_held = 0.5 * scores[("held", "regular")] + 0.5 * scores[("held", "mislabeled")]

        # score the control set for R, per split
        retain_score_public, retain_detail_public = _score_control_subset(
            control_inf,
            run2_control_log_probs,
            f_calibration,
            False,
        )
        retain_score_held, retain_detail_held = _score_control_subset(
            control_inf,
            run2_control_log_probs,
            f_calibration,
            True,
        )

        score_public = forget_score_public * retain_score_public
        score_held = forget_score_held * retain_score_held

        return {
            "score": score_public,
            "score_held_out": score_held,
            "disqualified": False,
            # "utility_check": utility_detail,
            "forget_quality_public_split": {
                "forget_score_overall": forget_score_public,
                # "forget_score_regular_subset": scores[("public", "regular")],
                # "forget_score_mislabeled_subset": scores[("public", "mislabeled")],
                # "forget_regular_subset_detail": details[("public", "regular")],
                # "forget_mislabeled_subset_detail": details[("public", "mislabeled")],
            },
            "forget_quality_held_out_split": {
                "forget_score_overall": forget_score_held,
                # "forget_score_regular_subset": scores[("held", "regular")],
                # "forget_score_mislabeled_subset": scores[("held", "mislabeled")],
                # "forget_regular_subset_detail": details[("held", "regular")],
                # "forget_mislabeled_subset_detail": details[("held", "mislabeled")],
            },
            "retain_quality_public_split": {
                "retain_score_overall": retain_score_public,
                # "retain_control_subset_detail": retain_detail_public,
            },
            "retain_quality_held_out_split": {
                "retain_score_overall": retain_score_held,
                # "retain_control_subset_detail": retain_detail_held,
            },
        }

    except Exception as e:
        return f"Internal scoring error: {e!r}"


if __name__ == "__main__":
    import sys

    if len(sys.argv) != 2:
        print(f"usage: python {sys.argv[0]} <submission.pt>")
        sys.exit(1)

    result = evaluator({"file_path": sys.argv[1]})
    print(json.dumps(result, indent=2))