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)