File size: 4,406 Bytes
c50dde6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import logging
import os
from typing import Dict, List, Tuple

import torch


def _label_to_name(label: int, label2cat_id: Dict[int, int], cats: Dict[int, dict]) -> str:
    """Return human readable category name for a dataset label."""
    cat_id = label2cat_id.get(label)
    if cat_id is None:
        return f"label_{label}"
    cat_info = cats.get(cat_id, {})
    return cat_info.get("name", f"cat_{cat_id}")


def _top_mismatch_pairs(
    preds: torch.Tensor,
    labels: torch.Tensor,
    num_classes: int,
    label2cat_id: Dict[int, int],
    cats: Dict[int, dict],
    top_k: int = 30,
) -> Tuple[float, List[dict]]:
    """Compute mismatch rate and the most frequent gt->pred pairs."""
    if labels.numel() == 0:
        return 0.0, []
    mismatch_mask = preds != labels
    total_mismatch = mismatch_mask.sum().item()
    mismatch_rate = float(total_mismatch) / float(labels.numel())
    if total_mismatch == 0:
        return mismatch_rate, []

    pair_labels = torch.stack([labels[mismatch_mask], preds[mismatch_mask]], dim=1)
    # flatten pair (gt, pred) to single index for counting
    flat = pair_labels[:, 0] * num_classes + pair_labels[:, 1]
    counts = torch.bincount(flat, minlength=num_classes * num_classes)
    # guard in case bincount returns empty
    if counts.numel() == 0:
        return mismatch_rate, []

    values, indices = torch.topk(counts, k=min(top_k, counts.numel()))
    results = []
    for idx, cnt in zip(indices.tolist(), values.tolist()):
        if cnt == 0:
            continue
        gt_label = idx // num_classes
        pred_label = idx % num_classes
        results.append(
            {
                "gt_label": int(gt_label),
                "pred_label": int(pred_label),
                "gt_name": _label_to_name(gt_label, label2cat_id, cats),
                "pred_name": _label_to_name(pred_label, label2cat_id, cats),
                "count": int(cnt),
                "ratio_within_mismatch": float(cnt) / float(total_mismatch),
            }
        )
    return mismatch_rate, results


def save_mismatch_reports(
    preds_dict: Dict[str, torch.Tensor],
    labels: torch.Tensor,
    dataset,
    save_dir: str,
    epoch: int,
    top_k: int = 30,
) -> None:
    """
    Save mismatch statistics to disk.

    Args:
        preds_dict: mapping from head name to top1 predictions.
        labels: ground-truth labels (long tensor).
        dataset: dataset object providing label2cat_id and coco.cats metadata.
        save_dir: root directory to write reports.
        epoch: current epoch number (used in filenames).
        top_k: number of most frequent mismatch pairs to keep.
    """
    if not hasattr(dataset, "label2cat_id") or not hasattr(dataset, "coco") or not hasattr(dataset.coco, "cats"):
        logging.warning("Dataset missing category metadata, skip mismatch report.")
        return

    os.makedirs(save_dir, exist_ok=True)
    label2cat_id = dataset.label2cat_id
    cats = dataset.coco.cats
    num_classes = len(label2cat_id)

    summary = {}
    for head, preds in preds_dict.items():
        if preds.numel() != labels.numel():
            logging.warning("Preds and labels length mismatch for head %s, skip.", head)
            continue
        mismatch_rate, top_pairs = _top_mismatch_pairs(
            preds=preds,
            labels=labels,
            num_classes=num_classes,
            label2cat_id=label2cat_id,
            cats=cats,
            top_k=top_k,
        )
        report = {
            "epoch": int(epoch),
            "total_samples": int(labels.numel()),
            "total_mismatch": int((preds != labels).sum().item()),
            "mismatch_rate": mismatch_rate,
            "top_pairs": top_pairs,
        }
        summary[head] = report
        filename = os.path.join(save_dir, f"{head}_mismatch_epoch{epoch}.json")
        try:
            with open(filename, "w") as f:
                json.dump(report, f, indent=2)
        except OSError as e:
            logging.error("Failed to write mismatch report for %s: %s", head, e)

    # save a combined summary for quick inspection
    combined_path = os.path.join(save_dir, f"mismatch_summary_epoch{epoch}.json")
    try:
        with open(combined_path, "w") as f:
            json.dump(summary, f, indent=2)
    except OSError as e:
        logging.error("Failed to write combined mismatch summary: %s", e)