initial commit

This commit is contained in:
2026-11-25 15:45:36 +05:30
commit e6007d7b07
50 changed files with 3818 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
"""Evaluation metrics, performance monitoring, benchmarking and reporting."""
+70
View File
@@ -0,0 +1,70 @@
"""Run both models (each in its own process for fair RAM/GPU numbers) and build the report.
Usage:
python -m benchmarking.compare_models --images-dir dataset/images \
--annotations dataset/annotations/annotations.json
"""
from __future__ import annotations
import argparse
import subprocess
import sys
from benchmarking.report_generator import MODELS, build_comparison_table, generate_report, load_summaries
from utils.config_loader import PROJECT_ROOT, ensure_project_dirs, load_config
from utils.logger import get_logger
logger = get_logger("compare_models")
def run_model_subprocess(model: str, extra_args: list[str]) -> subprocess.CompletedProcess:
"""Evaluate one model in a fresh Python process so models do not share RAM/GPU memory."""
cmd = [sys.executable, "-m", "benchmarking.evaluate", "--model", model, *extra_args]
logger.info("Running: %s", " ".join(cmd))
return subprocess.run(cmd, cwd=PROJECT_ROOT, capture_output=True, text=True)
def main(argv: list[str] | None = None) -> int:
cfg = load_config()
p = argparse.ArgumentParser(description="Benchmark Grounding DINO vs YOLO-World.")
p.add_argument("--images-dir", default=cfg["benchmark"]["images_dir"])
p.add_argument("--annotations", default=cfg["benchmark"]["annotations"])
p.add_argument("--device", default=cfg["device"]["default"])
p.add_argument("--dino-conf", type=float, default=None)
p.add_argument("--yolo-conf", type=float, default=None)
p.add_argument("--text-threshold", type=float, default=None)
p.add_argument("--limit", type=int, default=None)
p.add_argument("--report-only", action="store_true", help="Skip inference; rebuild the report from saved summaries")
args = p.parse_args(argv)
ensure_project_dirs()
if not args.report_only:
for model in MODELS:
extra = ["--images-dir", args.images_dir, "--annotations", args.annotations, "--device", args.device]
conf = args.dino_conf if model == "Grounding DINO" else args.yolo_conf
if conf is not None:
extra += ["--conf", str(conf)]
if args.text_threshold is not None:
extra += ["--text-threshold", str(args.text_threshold)]
if args.limit:
extra += ["--limit", str(args.limit)]
proc = run_model_subprocess(model, extra)
print(proc.stdout)
if proc.returncode != 0:
print(proc.stderr, file=sys.stderr)
print(f"ERROR: evaluation of {model} failed (exit {proc.returncode}).", file=sys.stderr)
return proc.returncode
outputs = generate_report()
if outputs is None:
print("Evaluation has not been completed - no summaries found.")
return 1
print(build_comparison_table(load_summaries()).to_string(index=False))
print("\nReport files:")
for name, path in outputs.items():
print(f" {name}: {path}")
return 0
if __name__ == "__main__":
sys.exit(main())
+217
View File
@@ -0,0 +1,217 @@
"""Evaluate one model on an annotated image set (COCO-style ground truth).
Usage:
python -m benchmarking.evaluate --model "Grounding DINO" \
--images-dir dataset/images --annotations dataset/annotations/annotations.json
Ground truth format: COCO detection JSON ("images", "annotations", "categories"), bbox = [x, y, w, h].
Nothing is computed without ground truth; a missing/invalid annotation file stops with a clear error.
"""
from __future__ import annotations
import argparse
import json
import math
import sys
import time
from datetime import datetime
from pathlib import Path
import numpy as np
import pandas as pd
from benchmarking.metrics import evaluate_detections
from benchmarking.performance_monitor import PerformanceMonitor
from detection.image_detection import run_image_detection
from utils.config_loader import ensure_project_dirs, load_config, resolve_path
from utils.device import resolve_device
from utils.image_utils import ImageLoadError, load_image_rgb
from utils.logger import get_logger
logger = get_logger("evaluate")
class AnnotationFormatError(ValueError):
"""Raised when the annotation file is missing or not valid COCO-style JSON."""
def load_coco_annotations(path: str | Path) -> tuple[dict, list[str], list[str]]:
"""Return (ground_truths by file_name, ordered file names, category names as written)."""
path = Path(path)
if not path.exists():
raise AnnotationFormatError(
f"Annotation file not found: {path}. Ground truth is required - evaluation has NOT been completed.")
try:
data = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise AnnotationFormatError(f"Annotation file is not valid JSON: {exc}") from exc
for key in ("images", "annotations", "categories"):
if not isinstance(data, dict) or key not in data:
raise AnnotationFormatError(f"Annotation file must be COCO-style and contain '{key}'.")
images = {img["id"]: img["file_name"] for img in data["images"] if "id" in img and "file_name" in img}
categories = {c["id"]: str(c["name"]) for c in data["categories"] if "id" in c and "name" in c}
if not images or not categories:
raise AnnotationFormatError("Annotation file has no usable 'images' or 'categories'.")
gts = {name: {"boxes": [], "labels": []} for name in images.values()}
for ann in data["annotations"]:
try:
x, y, w, h = (float(v) for v in ann["bbox"])
name = images[ann["image_id"]]
label = categories[ann["category_id"]]
except (KeyError, ValueError, TypeError) as exc:
raise AnnotationFormatError(f"Invalid annotation entry {ann!r}: {exc}") from exc
if w <= 0 or h <= 0:
raise AnnotationFormatError(f"Annotation {ann.get('id')} has a non-positive box size.")
gts[name]["boxes"].append([x, y, x + w, y + h])
gts[name]["labels"].append(label)
return gts, list(images.values()), list(categories.values())
def _clean(obj):
"""Make values JSON-safe (NaN -> None, numpy -> python)."""
if isinstance(obj, dict):
return {k: _clean(v) for k, v in obj.items()}
if isinstance(obj, (list, tuple)):
return [_clean(v) for v in obj]
if isinstance(obj, (np.floating, float)):
return None if math.isnan(float(obj)) else float(obj)
if isinstance(obj, np.integer):
return int(obj)
return obj
def run_evaluation(manager, model_name: str, images_dir: str | Path, annotations_path: str | Path,
prompts: list[str] | None = None, device: str = "auto", conf: float | None = None,
text_threshold: float | None = None, imgsz: int | None = None,
max_side: int | None = None, warmup_runs: int | None = None,
out_dir: str | Path | None = None, limit: int | None = None,
progress_callback=None) -> dict:
"""Run a model over every annotated image and compute metrics + performance statistics."""
from models.model_manager import model_slug, normalize_model_name
cfg = load_config()
bench = cfg["benchmark"]
model_name = normalize_model_name(model_name)
device = resolve_device(device)
conf = manager.default_conf(model_name) if conf is None else conf
text_threshold = cfg["detection"]["dino_text_threshold"] if text_threshold is None else text_threshold
warmup_runs = bench["warmup_runs"] if warmup_runs is None else warmup_runs
out_dir = Path(out_dir) if out_dir else resolve_path(cfg["paths"]["reports_out"])
out_dir.mkdir(parents=True, exist_ok=True)
images_dir = resolve_path(images_dir)
gts, file_names, categories = load_coco_annotations(resolve_path(annotations_path))
if limit:
file_names = file_names[:limit]
prompts = prompts or categories
missing = [c for c in categories if c.lower() not in {p.lower() for p in prompts}]
if missing:
logger.warning("Categories in annotations but not in prompts (will have zero recall): %s", missing)
existing = [f for f in file_names if (images_dir / f).exists()]
skipped = [f for f in file_names if f not in existing]
if skipped:
logger.warning("%d annotated images not found in %s (skipped).", len(skipped), images_dir)
if not existing:
raise AnnotationFormatError(f"None of the annotated images were found in {images_dir}.")
# Untimed warm-up on real data (model load + CUDA kernels excluded from steady-state timings).
first_img = load_image_rgb(images_dir / existing[0])
manager.get_detector(model_name, device)
manager.warmup(model_name, first_img, prompts, device=device, runs=warmup_runs, conf=conf,
text_threshold=text_threshold, imgsz=imgsz)
infer_conf = min(conf, bench["map_conf_threshold"]) # low threshold -> full ranking for AP
monitor = PerformanceMonitor(device, interval=bench["monitor_interval_s"])
predictions, per_image = {}, []
monitor.start()
try:
for i, name in enumerate(existing, start=1):
t0 = time.perf_counter()
try:
image = load_image_rgb(images_dir / name)
except ImageLoadError as exc:
logger.warning("Skipping unreadable image %s: %s", name, exc)
skipped.append(name)
continue
result = run_image_detection(manager, model_name, image, prompts, device=device,
conf=infer_conf, text_threshold=text_threshold,
max_side=max_side, imgsz=imgsz)
e2e = time.perf_counter() - t0
monitor.record_inference(result["inference_time"])
monitor.record_item(e2e)
predictions[name] = {"boxes": result["boxes"], "labels": result["labels"], "scores": result["scores"]}
per_image.append({"image": name, "inference_ms": result["inference_time"] * 1000,
"end_to_end_ms": e2e * 1000,
"detections_at_operating_conf": int(sum(s >= conf for s in result["scores"]))})
if progress_callback:
progress_callback(i, len(existing), name)
finally:
monitor.stop()
eval_gts = {n: gts[n] for n in predictions}
metrics = evaluate_detections(predictions, eval_gts, categories, bench["iou_threshold"], conf)
perf = monitor.summary()
summary = {
"model_name": model_name, "device": device,
"timestamp": datetime.now().isoformat(timespec="seconds"),
"images_dir": str(images_dir), "annotations": str(annotations_path),
"num_images_evaluated": len(predictions), "num_images_skipped": len(skipped),
"categories": categories, "prompts": prompts,
"operating_conf": conf, "text_threshold": text_threshold, "inference_conf_for_ap": infer_conf,
"warmup_runs": warmup_runs, "max_side": max_side, "imgsz": imgsz,
"overall": metrics["overall"], "per_class": metrics["per_class"], "performance": perf,
}
slug = model_slug(model_name)
(out_dir / f"summary_{slug}.json").write_text(json.dumps(_clean(summary), indent=2), encoding="utf-8")
(out_dir / f"predictions_{slug}.json").write_text(json.dumps(_clean(predictions)), encoding="utf-8")
pd.DataFrame(metrics["per_class"]).to_csv(out_dir / f"per_category_{slug}.csv", index=False)
pd.DataFrame(per_image).to_csv(out_dir / f"per_image_{slug}.csv", index=False)
monitor.export_csv(out_dir / f"monitor_{slug}.csv")
logger.info("Saved evaluation for %s to %s", model_name, out_dir)
return summary
def build_parser() -> argparse.ArgumentParser:
cfg = load_config()
p = argparse.ArgumentParser(description="Evaluate one open-vocabulary model against ground truth.")
p.add_argument("--model", required=True, help="'Grounding DINO' or 'YOLO-World'")
p.add_argument("--images-dir", default=cfg["benchmark"]["images_dir"])
p.add_argument("--annotations", default=cfg["benchmark"]["annotations"])
p.add_argument("--device", default=cfg["device"]["default"])
p.add_argument("--conf", type=float, default=None, help="Operating confidence / box threshold")
p.add_argument("--text-threshold", type=float, default=None)
p.add_argument("--imgsz", type=int, default=None)
p.add_argument("--max-side", type=int, default=None)
p.add_argument("--warmup-runs", type=int, default=None)
p.add_argument("--limit", type=int, default=None, help="Evaluate only the first N images")
p.add_argument("--prompts", default=None, help="Optional comma-separated prompts (default: annotation categories)")
return p
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
from detection.prompt_manager import parse_prompts
from models.model_manager import ModelManager
ensure_project_dirs()
try:
summary = run_evaluation(ModelManager(), args.model, args.images_dir, args.annotations,
parse_prompts(args.prompts) if args.prompts else None, args.device,
args.conf, args.text_threshold, args.imgsz, args.max_side,
args.warmup_runs, limit=args.limit)
except AnnotationFormatError as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 2
o, p = summary["overall"], summary["performance"]
print(f"\n{summary['model_name']} on {summary['device']} ({summary['num_images_evaluated']} images)")
print(f" precision={o['precision']:.3f} recall={o['recall']:.3f} f1={o['f1']:.3f} "
f"mAP@50={o['map50']:.3f} mAP@50-95={o['map50_95']:.3f}")
print(f" avg inference={p['avg_inference_ms']:.1f} ms | inference FPS={p['inference_fps']:.2f} | "
f"end-to-end FPS={p['end_to_end_fps']:.2f}")
return 0
if __name__ == "__main__":
sys.exit(main())
+178
View File
@@ -0,0 +1,178 @@
"""Detection metrics: IoU, one-to-one matching, precision/recall/F1, AP and mAP.
Matching procedure (documented, used everywhere):
1. Predictions of one class are sorted by confidence, highest first.
2. Each prediction is compared with the not-yet-matched ground-truth boxes of the SAME class
in the SAME image; the one with the highest IoU is taken if IoU >= threshold -> True Positive.
3. Otherwise the prediction is a False Positive. Each ground-truth box can be matched once.
4. Unmatched ground-truth boxes are False Negatives.
AP uses the COCO 101-point interpolated precision envelope. mAP@50-95 averages AP over
IoU thresholds 0.50, 0.55, ..., 0.95. Precision/Recall/F1 are computed at the operating
confidence threshold; AP uses all predictions (low threshold) so the full ranking is evaluated.
"""
from __future__ import annotations
import math
import numpy as np
IOU_THRESHOLDS_50_95 = [round(0.5 + 0.05 * i, 2) for i in range(10)]
NAN = float("nan")
def iou_xyxy(a: np.ndarray, b: np.ndarray) -> np.ndarray:
"""Pairwise IoU between boxes a (N,4) and b (M,4) in xyxy format -> (N,M)."""
a = np.asarray(a, dtype=float).reshape(-1, 4)
b = np.asarray(b, dtype=float).reshape(-1, 4)
if len(a) == 0 or len(b) == 0:
return np.zeros((len(a), len(b)))
ix1 = np.maximum(a[:, None, 0], b[None, :, 0])
iy1 = np.maximum(a[:, None, 1], b[None, :, 1])
ix2 = np.minimum(a[:, None, 2], b[None, :, 2])
iy2 = np.minimum(a[:, None, 3], b[None, :, 3])
inter = np.clip(ix2 - ix1, 0, None) * np.clip(iy2 - iy1, 0, None)
area_a = np.clip(a[:, 2] - a[:, 0], 0, None) * np.clip(a[:, 3] - a[:, 1], 0, None)
area_b = np.clip(b[:, 2] - b[:, 0], 0, None) * np.clip(b[:, 3] - b[:, 1], 0, None)
union = area_a[:, None] + area_b[None, :] - inter
return np.where(union > 0, inter / np.maximum(union, 1e-12), 0.0)
def pair_boxes(a: np.ndarray, b: np.ndarray, threshold: float = 0.5) -> list[float]:
"""Greedy one-to-one pairing of two box sets by highest IoU. Returns IoUs of the pairs."""
m = iou_xyxy(a, b).copy()
ious: list[float] = []
while m.size:
i, j = np.unravel_index(int(np.argmax(m)), m.shape)
if m[i, j] < threshold:
break
ious.append(float(m[i, j]))
m[i, :] = -1.0
m[:, j] = -1.0
return ious
def _norm(label) -> str:
return " ".join(str(label).lower().split())
def match_class_predictions(preds: list[tuple], gt_boxes_by_image: dict, iou_threshold: float) -> list[tuple[float, bool]]:
"""preds: [(image_id, score, box)]. Returns [(score, is_true_positive)] sorted by score desc."""
ordered = sorted(preds, key=lambda p: -p[1])
used = {img: np.zeros(len(boxes), dtype=bool) for img, boxes in gt_boxes_by_image.items()}
flags: list[tuple[float, bool]] = []
for image_id, score, box in ordered:
gts = gt_boxes_by_image.get(image_id)
is_tp = False
if gts is not None and len(gts):
ious = iou_xyxy(np.asarray([box]), gts)[0]
ious = np.where(used[image_id], -1.0, ious)
j = int(np.argmax(ious))
if ious[j] >= iou_threshold:
used[image_id][j] = True
is_tp = True
flags.append((float(score), is_tp))
return flags
def average_precision(flags: list[tuple[float, bool]], num_gt: int) -> float:
"""COCO-style 101-point interpolated AP from score-sorted TP flags."""
if num_gt == 0:
return NAN
if not flags:
return 0.0
tp = np.cumsum([1 if f[1] else 0 for f in flags], dtype=float)
fp = np.cumsum([0 if f[1] else 1 for f in flags], dtype=float)
recall = tp / num_gt
precision = tp / np.maximum(tp + fp, 1e-12)
envelope = np.maximum.accumulate(precision[::-1])[::-1]
grid = np.linspace(0.0, 1.0, 101)
idx = np.searchsorted(recall, grid, side="left")
sampled = np.array([envelope[i] if i < len(envelope) else 0.0 for i in idx])
return float(sampled.mean())
def _prf(tp: int, fp: int, fn: int) -> tuple[float, float, float]:
precision = tp / (tp + fp) if (tp + fp) > 0 else NAN
recall = tp / (tp + fn) if (tp + fn) > 0 else NAN
f1 = 2 * tp / (2 * tp + fp + fn) if (2 * tp + fp + fn) > 0 else NAN # == 2PR/(P+R)
return precision, recall, f1
def confidence_stats(scores: list[float]) -> dict:
"""Average/max/min confidence and detection count (confidence is NOT accuracy)."""
if not scores:
return {"avg_confidence": NAN, "max_confidence": NAN, "min_confidence": NAN, "detection_count": 0}
arr = np.asarray(scores, dtype=float)
return {"avg_confidence": float(arr.mean()), "max_confidence": float(arr.max()),
"min_confidence": float(arr.min()), "detection_count": int(arr.size)}
def evaluate_detections(predictions: dict, ground_truths: dict, classes: list[str],
iou_threshold: float = 0.5, operating_conf: float = 0.0) -> dict:
"""Compute overall and per-class precision, recall, F1, AP@50 and AP@50-95.
predictions: {image_id: {"boxes": [[x1,y1,x2,y2]], "labels": [str], "scores": [float]}}
ground_truths: {image_id: {"boxes": [[x1,y1,x2,y2]], "labels": [str]}}
classes: categories to evaluate. Predictions of other labels are ignored (counted separately).
"""
class_names = []
for c in classes:
if _norm(c) not in class_names:
class_names.append(_norm(c))
image_ids = list(dict.fromkeys(list(ground_truths) + list(predictions)))
per_class_preds = {c: [] for c in class_names}
per_class_gt = {c: {} for c in class_names}
ignored = 0
for img in image_ids:
gt = ground_truths.get(img, {"boxes": [], "labels": []})
for c in class_names:
boxes = [b for b, l in zip(gt["boxes"], gt["labels"]) if _norm(l) == c]
per_class_gt[c][img] = np.asarray(boxes, dtype=float).reshape(-1, 4)
pred = predictions.get(img)
if pred:
for b, l, s in zip(pred["boxes"], pred["labels"], pred["scores"]):
if _norm(l) in per_class_preds:
per_class_preds[_norm(l)].append((img, float(s), b))
else:
ignored += 1
rows = []
tot_tp = tot_fp = tot_fn = 0
ap50_vals, ap5095_vals = [], []
for c in class_names:
n_gt = int(sum(len(v) for v in per_class_gt[c].values()))
all_preds = per_class_preds[c]
kept = [p for p in all_preds if p[1] >= operating_conf]
flags = match_class_predictions(kept, per_class_gt[c], iou_threshold)
tp = sum(1 for _, t in flags if t)
fp = len(flags) - tp
fn = n_gt - tp
precision, recall, f1 = _prf(tp, fp, fn)
aps = [average_precision(match_class_predictions(all_preds, per_class_gt[c], t), n_gt)
for t in IOU_THRESHOLDS_50_95]
ap50 = aps[0]
ap5095 = float(np.mean(aps)) if n_gt > 0 else NAN
if n_gt > 0:
ap50_vals.append(ap50)
ap5095_vals.append(ap5095)
tot_tp, tot_fp, tot_fn = tot_tp + tp, tot_fp + fp, tot_fn + fn
rows.append({"category": c, "num_gt": n_gt, "num_pred": len(kept), "tp": tp, "fp": fp, "fn": fn,
"precision": precision, "recall": recall, "f1": f1, "ap50": ap50, "ap50_95": ap5095})
precision, recall, f1 = _prf(tot_tp, tot_fp, tot_fn)
kept_scores = [p[1] for c in class_names for p in per_class_preds[c] if p[1] >= operating_conf]
overall = {
"precision": precision, "recall": recall, "f1": f1,
"map50": float(np.mean(ap50_vals)) if ap50_vals else NAN,
"map50_95": float(np.mean(ap5095_vals)) if ap5095_vals else NAN,
"tp": tot_tp, "fp": tot_fp, "fn": tot_fn,
"iou_threshold": iou_threshold, "operating_conf": operating_conf,
"ignored_predictions": ignored,
**confidence_stats(kept_scores),
}
return {"overall": overall, "per_class": rows}
def is_nan(value) -> bool:
return isinstance(value, float) and math.isnan(value)
+94
View File
@@ -0,0 +1,94 @@
"""Create downloadable PDF reports for detection and benchmark results."""
from __future__ import annotations
from io import BytesIO
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402
import numpy as np # noqa: E402
import pandas as pd # noqa: E402
from matplotlib.backends.backend_pdf import PdfPages # noqa: E402
def _format_value(value: object) -> str:
if value is None:
return "N/A"
if isinstance(value, (float, np.floating)) and not np.isfinite(value):
return "N/A"
if isinstance(value, (list, tuple)):
return ", ".join(str(item) for item in value)
return str(value)
def create_pdf_report(title: str, details: dict[str, object],
tables: dict[str, pd.DataFrame] | None = None,
images: dict[str, np.ndarray | str | Path] | None = None,
charts: dict[str, tuple[str, pd.DataFrame, str]] | None = None) -> bytes:
"""Render summary, chart, table, and image pages into a downloadable PDF."""
output = BytesIO()
with PdfPages(output) as pdf:
detail_items = list(details.items()) or [("Status", "No summary details available")]
for page_no, start in enumerate(range(0, len(detail_items), 14)):
fig = plt.figure(figsize=(11.69, 8.27))
fig.suptitle(title, fontsize=18, fontweight="bold", x=0.08, ha="left", y=0.94)
fig.text(0.08, 0.88, "Processing report", fontsize=10, color="#0f766e")
y = 0.82
for key, value in detail_items[start:start + 14]:
fig.text(0.08, y, f"{key}: {_format_value(value)}", fontsize=10, va="top", wrap=True)
y -= 0.052
if page_no:
fig.text(0.92, 0.04, f"Summary page {page_no + 1}", fontsize=8, ha="right", color="#64748b")
pdf.savefig(fig, bbox_inches="tight")
plt.close(fig)
for caption, (kind, frame, ylabel) in (charts or {}).items():
if frame.empty:
continue
if kind not in {"bar", "line"}:
raise ValueError(f"Unsupported PDF chart type: {kind}")
chart_data = frame.apply(pd.to_numeric, errors="coerce")
fig, ax = plt.subplots(figsize=(11.69, 8.27))
plot_options = {"marker": "o"} if kind == "line" else {}
chart_data.plot(kind=kind, ax=ax, legend=len(chart_data.columns) > 1, **plot_options)
ax.set_title(caption, loc="left", fontsize=15, fontweight="bold", pad=18)
ax.set_xlabel("")
ax.set_ylabel(ylabel)
ax.set_axisbelow(True)
ax.grid(axis="y", alpha=0.3)
ax.tick_params(axis="x", labelrotation=40 if len(chart_data.index) > 8 else 0)
if kind == "bar":
for container in ax.containers:
ax.bar_label(container, fmt="%.2g", padding=2, fontsize=7)
fig.tight_layout()
pdf.savefig(fig, bbox_inches="tight")
plt.close(fig)
for section, frame in (tables or {}).items():
if frame.empty:
continue
page_size = 24
for start in range(0, len(frame), page_size):
page = frame.iloc[start:start + page_size].fillna("").astype(str)
fig, ax = plt.subplots(figsize=(11.69, 8.27))
ax.axis("off")
ax.set_title(section, loc="left", fontsize=15, fontweight="bold", pad=18)
table = ax.table(cellText=page.values, colLabels=page.columns, loc="center",
cellLoc="left", colLoc="left")
table.auto_set_font_size(False)
table.set_fontsize(7 if len(page.columns) > 7 else 8)
table.scale(1, 1.25)
pdf.savefig(fig, bbox_inches="tight")
plt.close(fig)
for caption, image in (images or {}).items():
fig, ax = plt.subplots(figsize=(11.69, 8.27))
ax.imshow(plt.imread(str(image)) if isinstance(image, (str, Path)) else image)
ax.set_title(caption, loc="left", fontsize=15, fontweight="bold", pad=18)
ax.axis("off")
pdf.savefig(fig, bbox_inches="tight")
plt.close(fig)
return output.getvalue()
+186
View File
@@ -0,0 +1,186 @@
"""Reusable performance monitor: timing, FPS, RAM, CPU, GPU memory and GPU utilisation."""
from __future__ import annotations
import subprocess
import threading
import time
from contextlib import contextmanager
from pathlib import Path
import numpy as np
import pandas as pd
import psutil
from utils.device import cuda_sync
from utils.logger import get_logger
logger = get_logger("performance_monitor")
MB = 1024 ** 2
@contextmanager
def timer(device: str = "cpu"):
"""Time a block with CUDA synchronisation before and after. Usage: `with timer(dev) as t: ...; t['elapsed']`."""
cuda_sync(device)
box = {"elapsed": 0.0}
start = time.perf_counter()
try:
yield box
finally:
cuda_sync(device)
box["elapsed"] = time.perf_counter() - start
class PerformanceMonitor:
"""Samples RAM/CPU/GPU in a background thread and accumulates per-item timings.
Model inference time and end-to-end time are recorded separately by the caller via
record_inference() and record_item(). Call start() before and stop() after the measured work.
"""
def __init__(self, device: str = "cpu", interval: float = 0.2):
self.device = device
self.interval = interval
self._proc = psutil.Process()
self._samples: list[dict] = []
self._inference: list[float] = []
self._e2e: list[float] = []
self._stop = threading.Event()
self._thread: threading.Thread | None = None
self._nvml = None
self._nvml_handle = None
self._smi_last = 0.0
self._smi_value: float | None = None
self._smi_ok = True
self._t0 = 0.0
self.ram_initial_mb = 0.0
self.ram_final_mb = 0.0
self._cuda = device.startswith("cuda")
# ------------------------------------------------------------ lifecycle
def start(self) -> "PerformanceMonitor":
self._samples.clear(); self._inference.clear(); self._e2e.clear()
self._stop.clear()
self.ram_initial_mb = self._proc.memory_info().rss / MB
psutil.cpu_percent(None) # prime
if self._cuda:
import torch
torch.cuda.synchronize()
torch.cuda.reset_peak_memory_stats()
try:
import pynvml
pynvml.nvmlInit()
self._nvml = pynvml
self._nvml_handle = pynvml.nvmlDeviceGetHandleByIndex(torch.cuda.current_device())
except Exception as exc: # noqa: BLE001 - NVML optional; fall back to nvidia-smi
logger.info("pynvml unavailable (%s); using nvidia-smi for GPU utilisation.", exc)
self._t0 = time.perf_counter()
self._sample()
self._thread = threading.Thread(target=self._loop, daemon=True)
self._thread.start()
return self
def stop(self) -> None:
self._stop.set()
if self._thread:
self._thread.join(timeout=2)
self._sample()
self.ram_final_mb = self._proc.memory_info().rss / MB
def __enter__(self):
return self.start()
def __exit__(self, *exc):
self.stop()
# ------------------------------------------------------------- sampling
def _loop(self) -> None:
while not self._stop.wait(self.interval):
self._sample()
def _gpu_util(self) -> float | None:
if not self._cuda:
return None
if self._nvml is not None:
try:
return float(self._nvml.nvmlDeviceGetUtilizationRates(self._nvml_handle).gpu)
except Exception: # noqa: BLE001
return None
if self._smi_ok and time.time() - self._smi_last > 1.0:
self._smi_last = time.time()
try:
out = subprocess.run(["nvidia-smi", "--query-gpu=utilization.gpu",
"--format=csv,noheader,nounits"], capture_output=True,
text=True, timeout=2)
self._smi_value = float(out.stdout.strip().splitlines()[0])
except Exception: # noqa: BLE001
self._smi_ok = False
return self._smi_value
def _sample(self) -> None:
row = {"t_s": time.perf_counter() - self._t0,
"ram_mb": self._proc.memory_info().rss / MB,
"cpu_pct": psutil.cpu_percent(None),
"gpu_util_pct": self._gpu_util(), "gpu_alloc_mb": None}
if self._cuda:
import torch
row["gpu_alloc_mb"] = torch.cuda.memory_allocated() / MB
self._samples.append(row)
# ------------------------------------------------------------ recording
def record_inference(self, seconds: float) -> None:
"""Model inference time of one item (excludes decoding, preprocessing and drawing)."""
self._inference.append(float(seconds))
def record_item(self, seconds: float) -> None:
"""End-to-end time of one item (everything the pipeline does for it)."""
self._e2e.append(float(seconds))
# -------------------------------------------------------------- summary
def summary(self) -> dict:
s = pd.DataFrame(self._samples) if self._samples else pd.DataFrame(columns=["ram_mb", "cpu_pct"])
nan = float("nan")
inf = np.asarray(self._inference, dtype=float)
e2e = np.asarray(self._e2e, dtype=float)
out = {
"ram_initial_mb": self.ram_initial_mb,
"ram_peak_mb": float(max(s["ram_mb"].max() if len(s) else 0.0, self.ram_initial_mb, self.ram_final_mb)),
"ram_final_mb": self.ram_final_mb,
"cpu_avg_pct": float(s["cpu_pct"].mean()) if len(s) else nan,
"cpu_peak_pct": float(s["cpu_pct"].max()) if len(s) else nan,
"gpu_available": self._cuda,
"gpu_total_mb": nan, "gpu_allocated_mb": nan, "gpu_peak_allocated_mb": nan,
"gpu_util_avg_pct": nan, "gpu_util_max_pct": nan,
"inference_count": int(inf.size),
"avg_inference_ms": float(inf.mean() * 1000) if inf.size else nan,
"min_inference_ms": float(inf.min() * 1000) if inf.size else nan,
"max_inference_ms": float(inf.max() * 1000) if inf.size else nan,
"inference_fps": float(inf.size / inf.sum()) if inf.size and inf.sum() > 0 else nan,
"e2e_count": int(e2e.size),
"e2e_total_s": float(e2e.sum()) if e2e.size else nan,
"end_to_end_fps": float(e2e.size / e2e.sum()) if e2e.size and e2e.sum() > 0 else nan,
}
if self._cuda:
import torch
out["gpu_total_mb"] = torch.cuda.get_device_properties(0).total_memory / MB
out["gpu_allocated_mb"] = torch.cuda.memory_allocated() / MB
out["gpu_peak_allocated_mb"] = torch.cuda.max_memory_allocated() / MB
if "gpu_util_pct" in s and s["gpu_util_pct"].notna().any():
out["gpu_util_avg_pct"] = float(s["gpu_util_pct"].mean())
out["gpu_util_max_pct"] = float(s["gpu_util_pct"].max())
return out
def to_dataframe(self) -> pd.DataFrame:
return pd.DataFrame(self._samples)
def export_csv(self, path: str | Path) -> Path:
"""Write raw samples to CSV and the summary to <name>_summary.csv."""
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
self.to_dataframe().to_csv(path, index=False)
pd.DataFrame([self.summary()]).to_csv(path.with_name(path.stem + "_summary.csv"), index=False)
return path
+235
View File
@@ -0,0 +1,235 @@
"""Build comparison tables, CSV files, charts and a Markdown report from evaluation summaries."""
from __future__ import annotations
import json
import math
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402
import numpy as np # noqa: E402
import pandas as pd # noqa: E402
from detection.prompt_manager import load_test_prompts # noqa: E402
from utils.config_loader import load_config, resolve_path # noqa: E402
from utils.logger import get_logger # noqa: E402
logger = get_logger("report_generator")
MODELS = ["Grounding DINO", "YOLO-World"]
SLUGS = {"Grounding DINO": "grounding_dino", "YOLO-World": "yolo_world"}
NOT_EVALUATED = "Not evaluated"
# (row label, getter path) - getter looks into summary["overall"] or summary["performance"]
TABLE_ROWS = [
("Precision", "overall", "precision"),
("Recall", "overall", "recall"),
("F1 Score", "overall", "f1"),
("mAP@50", "overall", "map50"),
("mAP@50-95", "overall", "map50_95"),
("Average inference time (ms)", "performance", "avg_inference_ms"),
("Inference FPS", "performance", "inference_fps"),
("End-to-end FPS", "performance", "end_to_end_fps"),
("Peak GPU memory (MB)", "performance", "gpu_peak_allocated_mb"),
("Peak RAM (MB)", "performance", "ram_peak_mb"),
("Average confidence", "overall", "avg_confidence"),
]
def reports_dir() -> Path:
path = resolve_path(load_config()["paths"]["reports_out"])
path.mkdir(parents=True, exist_ok=True)
return path
def load_summaries(directory: Path | None = None) -> dict[str, dict]:
directory = directory or reports_dir()
found = {}
for model in MODELS:
path = directory / f"summary_{SLUGS[model]}.json"
if path.exists():
found[model] = json.loads(path.read_text(encoding="utf-8"))
return found
def _value(summary: dict | None, section: str, key: str):
if not summary:
return None
return summary.get(section, {}).get(key)
def build_comparison_table(summaries: dict[str, dict]) -> pd.DataFrame:
rows = []
for label, section, key in TABLE_ROWS:
row = {"Metric": label}
for model in MODELS:
val = _value(summaries.get(model), section, key)
row[model] = NOT_EVALUATED if val is None else round(float(val), 4)
rows.append(row)
return pd.DataFrame(rows)
def build_per_category_table(summaries: dict[str, dict]) -> pd.DataFrame:
frames = []
for model, summary in summaries.items():
df = pd.DataFrame(summary.get("per_class", []))
if df.empty:
continue
df.insert(0, "model", model)
frames.append(df)
return pd.concat(frames, ignore_index=True) if frames else pd.DataFrame()
def build_category_metric_tables(per_category: pd.DataFrame,
uncommon_categories: list[str]) -> dict[str, pd.DataFrame]:
"""Build readable per-category precision/recall and uncommon F1 tables."""
models_by_category = {
(str(row["category"]).strip().lower(), str(row["model"])): row
for _, row in per_category.iterrows()
}
categories = list(dict.fromkeys(per_category.get("category", pd.Series(dtype=str)).astype(str)))
def metric_value(category: str, model: str, metric: str) -> str:
row = models_by_category.get((category.lower(), model))
value = row.get(metric) if row is not None else None
return "N/A" if value is None or pd.isna(value) else f"{float(value):.3f}"
precision_recall = [
{
"Category": category.title(),
**{
f"{model} {metric}": metric_value(category, model, metric)
for model in MODELS
for metric in ("precision", "recall")
},
}
for category in categories
]
uncommon = {category.strip().lower() for category in uncommon_categories}
uncommon_f1 = [
{
"Category": category.title(),
**{f"{model} F1": metric_value(category, model, "f1") for model in MODELS},
}
for category in categories if category.lower() in uncommon
]
return {
"Per-category precision and recall": pd.DataFrame(precision_recall),
"Uncommon category F1": pd.DataFrame(uncommon_f1),
}
def _num(value) -> float:
return float("nan") if value is None else float(value)
def _grouped_bar(path: Path, title: str, ylabel: str, labels: list[str], values: dict[str, list[float]]) -> None:
fig, ax = plt.subplots(figsize=(max(6, 1.3 * len(labels) + 3), 4.2))
width = 0.8 / max(1, len(values))
x = np.arange(len(labels))
for i, (model, vals) in enumerate(values.items()):
arr = np.array([0.0 if (v is None or math.isnan(v)) else v for v in vals])
bars = ax.bar(x + i * width - 0.4 + width / 2, arr, width, label=model)
for bar, raw in zip(bars, vals):
txt = "n/a" if (raw is None or math.isnan(raw)) else f"{raw:.2f}"
ax.annotate(txt, (bar.get_x() + bar.get_width() / 2, bar.get_height()),
ha="center", va="bottom", fontsize=7)
ax.set_xticks(x)
ax.set_xticklabels(labels, rotation=30 if len(labels) > 4 else 0, ha="right" if len(labels) > 4 else "center")
ax.set_title(title)
ax.set_ylabel(ylabel)
ax.legend()
ax.grid(axis="y", alpha=0.3)
fig.tight_layout()
fig.savefig(path, dpi=150)
plt.close(fig)
def _metric_chart(path, title, ylabel, summaries, items):
labels = [lbl for lbl, _, _ in items]
values = {m: [_num(_value(summaries.get(m), sec, key)) for _, sec, key in items] for m in summaries}
_grouped_bar(path, title, ylabel, labels, values)
def generate_report(directory: Path | None = None) -> dict | None:
"""Create CSVs, charts and report.md from the saved summaries. Returns paths, or None if no data."""
directory = directory or reports_dir()
summaries = load_summaries(directory)
if not summaries:
logger.warning("No evaluation summaries found in %s - evaluation has not been completed.", directory)
return None
outputs: dict[str, str] = {}
table = build_comparison_table(summaries)
table.to_csv(directory / "comparison_table.csv", index=False)
outputs["comparison_table"] = str(directory / "comparison_table.csv")
per_cat = build_per_category_table(summaries)
if not per_cat.empty:
per_cat.to_csv(directory / "per_category_comparison.csv", index=False)
outputs["per_category"] = str(directory / "per_category_comparison.csv")
charts = {
"accuracy.png": ("Accuracy metrics (IoU 0.50 matching)", "score",
[("Precision", "overall", "precision"), ("Recall", "overall", "recall"),
("F1", "overall", "f1"), ("mAP@50", "overall", "map50"),
("mAP@50-95", "overall", "map50_95")]),
"inference_time.png": ("Average inference time", "ms / image",
[("avg", "performance", "avg_inference_ms"),
("min", "performance", "min_inference_ms"),
("max", "performance", "max_inference_ms")]),
"fps.png": ("Throughput", "frames (images) per second",
[("Inference FPS", "performance", "inference_fps"),
("End-to-end FPS", "performance", "end_to_end_fps")]),
"gpu_memory.png": ("GPU memory (PyTorch allocated)", "MB",
[("Allocated (end)", "performance", "gpu_allocated_mb"),
("Peak allocated", "performance", "gpu_peak_allocated_mb"),
("Total GPU", "performance", "gpu_total_mb")]),
"ram.png": ("Process RAM", "MB",
[("Initial", "performance", "ram_initial_mb"), ("Peak", "performance", "ram_peak_mb"),
("Final", "performance", "ram_final_mb")]),
}
for fname, (title, ylabel, items) in charts.items():
_metric_chart(directory / fname, title, ylabel, summaries, items)
outputs[fname] = str(directory / fname)
if not per_cat.empty:
cats = list(dict.fromkeys(per_cat["category"]))
for metric in ("precision", "recall"):
vals = {}
for model in summaries:
sub = per_cat[per_cat["model"] == model].set_index("category")
vals[model] = [_num(sub[metric].get(c)) if c in sub.index else float("nan") for c in cats]
_grouped_bar(directory / f"per_category_{metric}.png", f"Per-category {metric}", metric, cats, vals)
outputs[f"per_category_{metric}.png"] = str(directory / f"per_category_{metric}.png")
uncommon = [u.lower() for u in load_test_prompts().get("uncommon", [])]
unc = [c for c in cats if c.lower() in uncommon]
if unc:
vals = {}
for model in summaries:
sub = per_cat[per_cat["model"] == model].set_index("category")
vals[model] = [_num(sub["f1"].get(c)) if c in sub.index else float("nan") for c in unc]
_grouped_bar(directory / "uncommon_categories.png",
"Uncommon categories - F1 (rare in typical datasets; not a claim about pretraining data)",
"F1", unc, vals)
outputs["uncommon_categories.png"] = str(directory / "uncommon_categories.png")
lines = ["# Open-Vocabulary Detection - Benchmark Report", ""]
for model, s in summaries.items():
lines.append(f"- **{model}**: device `{s['device']}`, {s['num_images_evaluated']} images, "
f"operating confidence {s['operating_conf']}, run {s['timestamp']}")
lines += ["", "## Comparison", "", table.to_markdown(index=False) if _has_tabulate() else table.to_string(index=False), "",
"Missing models are shown as 'Not evaluated'. Confidence is not accuracy. "
"Both models were evaluated in separate processes on the same hardware, images and annotations.", ""]
(directory / "benchmark_report.md").write_text("\n".join(lines), encoding="utf-8")
outputs["report"] = str(directory / "benchmark_report.md")
return outputs
def _has_tabulate() -> bool:
try:
import tabulate # noqa: F401
return True
except ImportError:
return False