TTA Ablation for One RF-DETR Size: Zoom Range, Antialiasing and Masks¶
RFDETRInference.predict(images, tta=TTAConfig(...)) fuses several views of each image: copies that are moved by a fraction of a backbone patch (shift) or resized (zoom). The Test-Time Augmentation page measured the shift sweep for every size and the zoom recipes for Nano, Small and Large. This notebook measures what that page leaves open for one model size at a time, set by MODEL_SIZE (Medium by default), and is meant to run on a GPU such as a Colab T4, L4 or A100. Run it once per size to compare sizes.
It answers four questions:
- Which single zoom scale adds the most box AP, and where does the allowed range
0.75to1.5stop paying? - Does antialiasing the zoom-out views change that? The default
antialias=Falsematches the resize the model was trained with, so the question is whether the views should differ from it. - Do the zoom and shift + zoom recipes beat the same number of shift views on every fold of the data, and by at least 0.3 box AP?
- Do the same recipes keep the mask AP of the segmentation model of the same size? Sizes without a segmentation model skip this step.
The fold protocol keeps the choice honest. The 5000 COCO val2017 images are split into five interleaved folds. Fold 0 is only used to select the best single zoom. Folds 1 to 4 decide: a recipe passes only when its mean gain over shift views is at least the threshold and the gain has the same sign on every one of those folds.
Note: Nothing here is a published result. Every number comes from the run you start, on the device and package versions printed in the footer. Copy numbers into other docs only together with that footer.
Install the package with the COCO scoring backends (train) and the plotting dependencies (visual). The install pins the 1.13.0 release, which includes TTAConfig. For the Plus sizes (Atto, Femto, Pico, XLarge and 2XLarge) add the plus extra and "rfdetr_plus>=1.2.0". Restart the kernel afterwards so the recorded versions are the ones in use.
!pip install -q -U "rfdetr[train,visual]==1.13.0"
Keep imports together so every dependency of the measurement path is visible in one place.
import hashlib
import importlib.metadata
import json
import platform
from dataclasses import asdict, replace
from datetime import datetime, timezone
from pathlib import Path
from typing import NamedTuple
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
from IPython.display import display
from PIL import Image
from tqdm.auto import tqdm
import rfdetr
from rfdetr import RFDETRInference, TTAConfig
from rfdetr._prediction.tta import view_count
from rfdetr.datasets._develop import _download_and_extract
from rfdetr.export._benchmark import (
cpu_brand,
evaluate_coco_ap,
evaluate_coco_predictions,
fetch_coco_val2017,
time_predict_call,
)
Choose what to run¶
The defaults score all 5000 COCO val2017 images for the box arms and the four gate folds for the mask arms. Every row is written to disk as soon as it exists, so an interrupted run resumes. For a quick check lower N_AP_IMAGES to a few hundred, which keeps the fold logic but shrinks every fold.
MODEL_SIZEis the size measured. The detection model isRFDETR<size>, and the mask guard usesRFDETRSeg<size>where one exists (Nano to 2XLarge).- PML 1.0 covers the Plus detection models (Atto, Femto, Pico, XLarge and 2XLarge): commercial use is included when you deploy on Roboflow, and commercial self-hosting requires the Enterprise add-on. Set
ACCEPT_PLATFORM_MODEL_LICENSE = Trueonly after accepting it. Nano, Small, Medium, Large and every segmentation size are Apache 2.0. SELECTION_FOLDpicks the best single zoom andGATE_FOLDSdecide whether a recipe ships.GATE_ZOOM_APis the least box AP a zoom recipe must add over the same number of shift views, andMASK_TOLERANCEis the most mask AP a recipe may lose against four shift views.
MODEL_SIZE = "Medium"
ACCEPT_PLATFORM_MODEL_LICENSE = False
SIZE_ORDER = ("Atto", "Femto", "Pico", "Nano", "Small", "Medium", "Large", "XLarge", "2XLarge")
PLUS_SIZES = ("Atto", "Femto", "Pico", "XLarge", "2XLarge")
SEGMENTATION_SIZES = ("Nano", "Small", "Medium", "Large", "XLarge", "2XLarge")
DETECT_MODEL = f"RFDETR{MODEL_SIZE}"
# `None` for a size without a segmentation model: the mask guard is skipped for it.
SEGMENT_MODEL = f"RFDETRSeg{MODEL_SIZE}" if MODEL_SIZE in SEGMENTATION_SIZES else None
# Images scored for box AP: None scores all 5000 val2017 images.
N_AP_IMAGES = None
# Interleaved folds: every fold sees the whole range of the data.
N_FOLDS = 5
SELECTION_FOLD = 0
GATE_FOLDS = (1, 2, 3, 4)
GATE_ZOOM_AP = 0.3
MASK_TOLERANCE = 0.2
# Images per call while scoring box AP. AP does not depend on it; it only keeps the scoring pass short.
AP_BATCH = 8
# A confidence threshold near zero traces the whole precision-recall curve; 0.5 is a typical serving value.
AP_THRESHOLD = 0.001
LATENCY_THRESHOLD = 0.5
# Images per call for the two latency settings: one image, and a batch whose per-image cost is the throughput view.
BATCH_SIZES = (1, 8)
# Distinct images the latency calls cycle through, so no cache flatters the timing.
N_LATENCY_IMAGES = 64
WARMUP = 10
RUNS = 50
COCO_ROOT = Path("coco")
WORK_DIR = Path("tta-ablation-run")
Describe one arm of the sweep: a name, how many views it runs, the TTAConfig that produces them and whether the resize antialiases. To measure the gain from adding views, compare each arm with the plain prediction at the same flag, since the flag also changes how the base image is resized.
class Arm(NamedTuple):
"""One view recipe at one view count."""
name: str
views: int
config: TTAConfig | None
antialias: bool = False
# `None` keeps the plain prediction on the plain path: the baseline every other row is compared with.
PLAIN = Arm("plain", 1, None)
PLAIN_ANTIALIAS = Arm("plain, antialias", 1, None, True)
ZOOM_SCALES = (0.75, 0.85, 1.1, 1.25, 1.5)
SINGLE_ZOOMS = [Arm(f"zoom {z}", 2, TTAConfig(zoom=(z,))) for z in ZOOM_SCALES]
# Antialiasing only matters for views that shrink the image.
ANTIALIAS_ZOOMS = [Arm(f"zoom {z}, antialias", 2, TTAConfig(zoom=(z,)), True) for z in (0.75, 0.85)]
SHIFTS = [Arm(f"shift {n}", n, TTAConfig(shift=n)) for n in (2, 4, 8)]
ZOOM_RECIPES = [
Arm("default zoom", 4, TTAConfig()),
Arm("shift 2 + zoom 1.25, 1.5", 4, TTAConfig(shift=2, zoom=(1.25, 1.5))),
Arm("shift 4 + zoom 0.85 to 1.5", 8, TTAConfig(shift=4, zoom=(0.85, 1.15, 1.3, 1.5))),
]
ARMS = [PLAIN, PLAIN_ANTIALIAS, *SINGLE_ZOOMS, *ANTIALIAS_ZOOMS, *SHIFTS, *ZOOM_RECIPES]
# Pair mixed zoom recipes with their same-view-count shift baselines.
MIXED_COMPARISONS = [(ZOOM_RECIPES[0], SHIFTS[1]), (ZOOM_RECIPES[1], SHIFTS[1]), (ZOOM_RECIPES[2], SHIFTS[2])]
MASK_BASELINE = SHIFTS[1]
for arm in ARMS:
assert arm.config is None or view_count(arm.config) == arm.views, arm
Reject unusable settings before any download.
assert MODEL_SIZE in SIZE_ORDER, f"MODEL_SIZE must be one of {SIZE_ORDER}."
assert ACCEPT_PLATFORM_MODEL_LICENSE or MODEL_SIZE not in PLUS_SIZES, (
"Plus models require ACCEPT_PLATFORM_MODEL_LICENSE = True after accepting PML 1.0."
)
assert N_AP_IMAGES is None or N_AP_IMAGES >= N_FOLDS, "Each fold needs at least one image."
assert SELECTION_FOLD not in GATE_FOLDS, "The fold that selects must not also decide."
assert all(0 <= fold < N_FOLDS for fold in (SELECTION_FOLD, *GATE_FOLDS)), "Folds are numbered from 0."
assert 1 in BATCH_SIZES and all(size >= 1 for size in BATCH_SIZES), "Include batch size 1 for the eager baseline."
assert N_LATENCY_IMAGES >= max(BATCH_SIZES), "The latency pool must hold at least one full batch."
assert len({arm.name for arm in ARMS}) == len(ARMS), "Arm names identify result rows, so they must be unique."
Prepare COCO val2017¶
Download the image archive in one transfer (5000 single downloads can hit socket timeouts); the completion check requires 5000 nonempty JPEG files. Skipped when the folder is already complete.
_download_and_extract(
"http://images.cocodataset.org/zips/val2017.zip",
COCO_ROOT,
is_complete=lambda: sum(path.stat().st_size > 0 for path in (COCO_ROOT / "val2017").glob("*.jpg")) == 5000,
)
Fetch the annotations and pick the images to score. A subset is seeded, so every row scores the same images and a difference between rows is not a difference in data.
subset = fetch_coco_val2017(COCO_ROOT, n_images=N_AP_IMAGES)
print(f"Scoring {len(subset.image_ids)} COCO val2017 images per box row.")
Split the image IDs into the interleaved folds once, and build a subset per fold for the mask scoring. Every arm is scored on the same folds.
ids = list(subset.image_ids)
folds = [ids[k::N_FOLDS] for k in range(N_FOLDS)]
print([len(fold) for fold in folds])
Record provenance¶
Record the device, package versions and UTC start date once, so every table and plot can be traced to the run that made it.
device_kind = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
device = torch.device(device_kind)
host_cpu = cpu_brand()
device_name = torch.cuda.get_device_name(device) if device_kind == "cuda" else host_cpu
direct_url = json.loads(importlib.metadata.distribution("rfdetr").read_text("direct_url.json") or "{}")
def package_version(name: str) -> str | None:
"""Return the installed version of ``name``, or ``None`` when it is not installed."""
try:
return importlib.metadata.version(name)
except importlib.metadata.PackageNotFoundError:
return None
provenance = {
"device": f"{device_kind}: {device_name}",
"rfdetr": package_version("rfdetr"),
"rfdetr_plus": package_version("rfdetr_plus") if MODEL_SIZE in PLUS_SIZES else None,
"commit": direct_url.get("vcs_info", {}).get("commit_id"),
"torch": torch.__version__,
"torchvision": package_version("torchvision"),
"pillow": package_version("pillow"),
"host_cpu": host_cpu,
"platform": platform.platform(),
"torch_threads": torch.get_num_threads(),
"cuda": torch.version.cuda,
"matmul_precision": torch.get_float32_matmul_precision(),
"supervision": package_version("supervision"),
"faster_coco_eval": package_version("faster-coco-eval"),
"python": platform.python_version(),
"started_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
}
print(json.dumps(provenance, indent=2))
Views batch on CUDA only; on MPS and CPU each view is its own forward pass. Say so up front, since it changes what the latency columns mean.
if device_kind != "cuda":
print(
f"Device is {device_kind}: views run one forward pass each here, so latency grows about linearly with the "
"view count. Read the latency table as the worst case, not as the batched cost."
)
Load the images the timing reuses¶
Read the timing images once so disk I/O stays outside the measured calls. Take them from the downloaded validation split in image-ID order, so a quick AP subset still exercises the same full timing batches.
# COCO names each file after its zero-padded image id.
image_paths = {image_id: subset.images_dir / f"{image_id:012d}.jpg" for image_id in subset.image_ids}
latency_paths = sorted(subset.images_dir.glob("[0-9]" * 12 + ".jpg"))[:N_LATENCY_IMAGES]
assert len(latency_paths) >= max(BATCH_SIZES), "The COCO image directory has too few images for the timing batches."
pool = [Image.open(path).convert("RGB") for path in latency_paths]
print(f"Loaded {len(pool)} images.")
Define the measurements¶
Each measurement is one small function, so the loop that runs them stays readable. All go through the public RFDETRInference.predict(..., tta=...), the call users make.
Box AP first. The predictor scores a whole list of image paths in batches and the predictions are kept, so the same run is scored on all images and on each fold without predicting twice. fold_box_ap is what the paired gains are built from.
def score_box_ap(predictor: RFDETRInference, arm: Arm) -> dict[str, object]:
"""Return box AP, AP50 and the per-fold box AP of ``arm`` on the COCO subset."""
detections = predictor.predict(
[str(image_paths[i]) for i in ids],
threshold=AP_THRESHOLD,
include_source_image=False,
batch=AP_BATCH,
antialias=arm.antialias,
tta=arm.config,
)
stored = dict(zip(ids, detections, strict=True))
whole = evaluate_coco_predictions(stored, subset, "detect")
fold_ap = [evaluate_coco_predictions(stored, subset, "detect", image_ids=fold).box_ap for fold in folds]
return {"box_ap": whole.box_ap, "box_ap50": whole.box_ap50, "fold_box_ap": fold_ap}
Mask AP next. A segmentation prediction carries one mask per detection, so keeping a fold of them in memory is too much: each image is scored as it is predicted, one fold at a time.
def score_mask_ap(predictor: RFDETRInference, arm: Arm, fold: list[int]) -> dict[str, float]:
"""Return the box AP and mask AP of ``arm`` on the images of one fold."""
fold_subset = replace(subset, image_ids=tuple(fold))
def run(image: Image.Image) -> object:
return predictor.predict(
image, threshold=AP_THRESHOLD, include_source_image=False, antialias=arm.antialias, tta=arm.config
)
result = evaluate_coco_ap(run, fold_subset, "segment", progress=False)
return {"box_ap": result.box_ap, "mask_ap": result.task_ap}
Latency last. A call takes B distinct images and returns after fusion, so the timing covers preprocessing, the forward pass, mapping back and fusing: the cost a user pays per call. The median call time is kept; the table divides it by B to get the cost per image.
def time_call(predictor: RFDETRInference, arm: Arm, batch_size: int) -> dict[str, float]:
"""Return the median and 95th-percentile time of one call of ``batch_size`` images, in milliseconds."""
return time_predict_call(
predictor,
pool,
batch_size,
label=f"{arm.name} B={batch_size}",
device=device_kind,
warmup=WARMUP,
runs=RUNS,
threshold=LATENCY_THRESHOLD,
include_source_image=False,
antialias=arm.antialias,
tta=arm.config,
)
Run the sweep¶
The sweep stores one result file per experiment. The experiment identity records the ordered image IDs, arms, scoring and timing settings, and runtime provenance. A changed setting starts a new file, while the same settings reuse completed rows and retain the original run date. Keep one notebook kernel writing to a given experiment at a time.
# Keep only the displayed start time out of the experiment identity so identical runs can resume.
experiment = {
"schema_version": 2,
"runtime": {key: value for key, value in provenance.items() if key != "started_utc"},
"models": [DETECT_MODEL, SEGMENT_MODEL],
"arms": [
{"name": a.name, "views": a.views, "config": asdict(a.config) if a.config else None, "antialias": a.antialias}
for a in ARMS
],
"single_zoom_candidates": [arm.name for arm in SINGLE_ZOOMS],
"mixed_comparisons": [(arm.name, baseline.name) for arm, baseline in MIXED_COMPARISONS],
"mask_baseline": MASK_BASELINE.name,
"ap_images": ids,
"latency_images": [int(path.stem) for path in latency_paths],
"ap_batch": AP_BATCH,
"batch_sizes": list(BATCH_SIZES),
"ap_threshold": AP_THRESHOLD,
"latency_threshold": LATENCY_THRESHOLD,
"folds": N_FOLDS,
"selection_fold": SELECTION_FOLD,
"gate_folds": list(GATE_FOLDS),
"warmup": WARMUP,
"runs": RUNS,
}
experiment_json = json.dumps(experiment, sort_keys=True)
experiment_id = hashlib.sha256(experiment_json.encode("utf-8")).hexdigest()
experiment_dir = WORK_DIR / experiment_id
experiment_dir.mkdir(parents=True, exist_ok=True)
manifest_path = experiment_dir / "experiment.json"
if not manifest_path.exists():
manifest_path.write_text(
json.dumps({"experiment": experiment, "provenance": provenance}, indent=2), encoding="utf-8"
)
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
assert json.dumps(manifest["experiment"], sort_keys=True) == experiment_json, "Saved experiment settings differ."
provenance = manifest["provenance"]
RESULTS_PATH = experiment_dir / "results.jsonl"
KEY = ("kind", "model", "arm", "batch_size", "fold")
saved_rows = (
[json.loads(line) for line in RESULTS_PATH.read_text(encoding="utf-8").splitlines()]
if RESULTS_PATH.exists()
else []
)
assert all(row["experiment_id"] == experiment_id for row in saved_rows), "A result belongs to another experiment."
done = {tuple(row[k] for k in KEY) for row in saved_rows}
assert len(done) == len(saved_rows), "The experiment contains duplicate result rows."
print(f"{len(done)} rows already recorded in {experiment_dir}.")
Write one row to disk the moment it exists, so a later failure keeps everything before it.
def have(kind: str, model_name: str, arm: Arm, batch_size: int | None = None, fold: int | None = None) -> bool:
"""Return whether the row is already recorded."""
return (kind, model_name, arm.name, batch_size, fold) in done
def record(
kind: str, model_name: str, arm: Arm, batch_size: int | None = None, fold: int | None = None, **values: object
) -> None:
"""Append one result row, with the run's provenance, to ``results.jsonl``."""
row = {
"experiment_id": experiment_id,
"kind": kind,
"model": model_name,
"arm": arm.name,
"views": arm.views,
"antialias": arm.antialias,
"batch_size": batch_size,
"fold": fold,
**values,
**provenance,
}
with RESULTS_PATH.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(row, allow_nan=True) + "\n")
saved_rows.append(row)
done.add((kind, model_name, arm.name, batch_size, fold))
Run the box and latency sweep for the selected size. For each arm: the box AP on all images and every fold, and the latency at each batch size. Warnings stay visible, since a warning about a deprecated path changes how a number should be read.
detector = getattr(rfdetr, DETECT_MODEL)(device=device_kind)
predictor = RFDETRInference(detector)
for arm in tqdm(ARMS, desc=DETECT_MODEL):
if not have("accuracy", DETECT_MODEL, arm):
record("accuracy", DETECT_MODEL, arm, **score_box_ap(predictor, arm))
for batch_size in BATCH_SIZES:
if not have("latency", DETECT_MODEL, arm, batch_size):
record("latency", DETECT_MODEL, arm, batch_size, **time_call(predictor, arm, batch_size))
del predictor, detector
if device_kind == "cuda":
torch.cuda.empty_cache()
Choose the single zoom before starting mask scoring. The selection fold picks the candidate, and the gate folds determine whether it beats two shifts. The mask sweep uses this same candidate and the mixed recipes so its results cover the box gate.
fold_ap = pd.DataFrame(
{
row["arm"]: np.array(row["fold_box_ap"]) * 100
for row in saved_rows
if row["kind"] == "accuracy" and row["model"] == DETECT_MODEL
},
index=range(N_FOLDS),
).T
best_zoom = max(SINGLE_ZOOMS, key=lambda arm: fold_ap.at[arm.name, SELECTION_FOLD])
comparisons = [(best_zoom, SHIFTS[0]), *MIXED_COMPARISONS]
mask_arms = [PLAIN, MASK_BASELINE, *(recipe for recipe, _ in comparisons)]
print(f"Best single zoom on fold {SELECTION_FOLD}: {best_zoom.name}")
Run the mask guard on the segmentation model of the same size when one exists. Score the selected single zoom and all three mixed recipes on every gate fold. The plain prediction and four shift views provide mask references.
if SEGMENT_MODEL is None:
print(f"RF-DETR {MODEL_SIZE} has no segmentation model: the mask guard is skipped.")
else:
segmenter = getattr(rfdetr, SEGMENT_MODEL)(device=device_kind)
predictor = RFDETRInference(segmenter)
for arm in tqdm(mask_arms, desc=SEGMENT_MODEL):
for fold_index in GATE_FOLDS:
if not have("mask", SEGMENT_MODEL, arm, fold=fold_index):
record("mask", SEGMENT_MODEL, arm, fold=fold_index, **score_mask_ap(predictor, arm, folds[fold_index]))
del predictor, segmenter
if device_kind == "cuda":
torch.cuda.empty_cache()
Analyze the rows¶
Analyze the validated rows loaded from the experiment file and the measurements appended in this session. Show every row of the tables below: pandas truncates a table of more than 60 rows to its first and last rows.
pd.set_option("display.max_rows", None)
rows = pd.DataFrame(saved_rows)
by_name = {arm.name: arm for arm in ARMS}
accuracy = rows[rows["kind"] == "accuracy"].set_index("arm")[
["views", "antialias", "box_ap", "box_ap50", "fold_box_ap"]
]
latency = (
rows[rows["kind"] == "latency"]
.astype({"batch_size": int})
.set_index(["arm", "batch_size"])[["call_ms", "call_p95_ms"]]
)
print(f"{len(accuracy)} box arms, {len(latency)} latency rows, {int((rows['kind'] == 'mask').sum())} mask rows.")
Show the box AP table. AP is in percent. gain is the AP of the arm minus the AP of the plain prediction at the same antialias flag, on all images; gain_se is the standard error of the same gain computed fold by fold, so a gain well inside it is not evidence of an improvement.
def paired_gain(frame: pd.DataFrame) -> pd.DataFrame:
"""Add the AP gain over the plain prediction at the same antialias flag, and its fold-to-fold standard error."""
out = frame.copy()
gains, errors = [], []
for name, row in frame.iterrows():
plain = frame.loc["plain, antialias" if row["antialias"] else "plain"]
fold_gain = (np.array(row["fold_box_ap"]) - np.array(plain["fold_box_ap"])) * 100
gains.append((row["box_ap"] - plain["box_ap"]) * 100)
errors.append(fold_gain.std(ddof=1) / np.sqrt(len(fold_gain)) if len(fold_gain) > 1 else float("nan"))
out["box_ap"] *= 100
out["gain"], out["gain_se"] = gains, errors
return out.drop(columns=["box_ap50", "fold_box_ap"])
gains = paired_gain(accuracy.loc[[arm.name for arm in ARMS if arm.name in accuracy.index]])
display(gains.round(2))
Plot the gain against the zoom scale¶
The figure answers the first two questions. Each point is a two-view recipe: the native-scale view plus one zoomed copy at the scale on the x axis. The y axis is the paired box AP gain over the plain prediction with the fold-to-fold standard error as error bars. The second line shows the zoom-out scales with antialiasing on, each against the plain prediction at the same flag.
fig, ax = plt.subplots(figsize=(6.5, 4.2))
plain_line = [gains.loc[f"zoom {z}"] for z in ZOOM_SCALES]
ax.errorbar(
ZOOM_SCALES,
[row["gain"] for row in plain_line],
yerr=[row["gain_se"] for row in plain_line],
marker="o",
capsize=2,
label="antialias off (default)",
)
anti_scales = (0.75, 0.85)
anti_line = [gains.loc[f"zoom {z}, antialias"] for z in anti_scales]
ax.errorbar(
anti_scales,
[row["gain"] for row in anti_line],
yerr=[row["gain_se"] for row in anti_line],
marker="s",
capsize=2,
linestyle="--",
label="antialias on",
)
ax.axhline(0, color="gray", linewidth=0.8)
ax.axvline(1.0, color="gray", linewidth=0.8, linestyle=":")
ax.set_xlabel("zoom scale of the second view")
ax.set_ylabel("box AP gain over plain, points")
ax.grid(alpha=0.3)
ax.legend()
fig.tight_layout()
plt.show()
Read each curve as the gain from zoom over its own plain baseline. A larger gain under antialiasing can still yield lower final AP because the base resize changes too. The paired comparison below answers which flag setting gives each zoom-out recipe higher AP.
Compare the two flag settings on the same zoom-out recipe. The table reports absolute AP for both settings and their difference on the full sample. The standard error comes from paired fold differences. This measures the public flag as used in both the input and zoom resize.
antialias_rows = []
for arm in ANTIALIAS_ZOOMS:
off_name = arm.name.removesuffix(", antialias")
off_ap = accuracy.loc[off_name, "box_ap"] * 100
on_ap = accuracy.loc[arm.name, "box_ap"] * 100
paired_delta = fold_ap.loc[arm.name] - fold_ap.loc[off_name]
antialias_rows.append(
{
"recipe": off_name,
"antialias off AP": off_ap,
"antialias on AP": on_ap,
"gain": on_ap - off_ap,
"gain_se": paired_delta.std(ddof=1) / np.sqrt(len(paired_delta)),
}
)
display(pd.DataFrame(antialias_rows).set_index("recipe").round(2))
Held-out box AP gate¶
The single zoom was chosen using only the selection fold. Show gains against the matching plain baseline for each arm, then compare each candidate with the same number of shift views on the held-out folds. Keeping these folds separate avoids using the same images for selection and acceptance.
# Compare with each arm's own resize setting when displaying the gains from adding views.
fold_gains = fold_ap.copy()
for arm in ARMS:
plain_arm = PLAIN_ANTIALIAS if arm.antialias else PLAIN
fold_gains.loc[arm.name] = fold_ap.loc[arm.name] - fold_ap.loc[plain_arm.name]
display(fold_gains.round(2))
Apply the gate. Each zoom recipe is compared with the shift recipe of the same view count on the gate folds: it passes when the mean gain is at least GATE_ZOOM_AP and no gate fold has a gain at or below zero. The single zoom is compared with two shift views.
# Use only held-out deltas when deciding which recipes beat their shift baseline.
gate_rows = []
for recipe, baseline in comparisons:
delta = (fold_ap.loc[recipe.name] - fold_ap.loc[baseline.name]).loc[list(GATE_FOLDS)]
gate_rows.append(
{
"recipe": recipe.name,
"views": recipe.views,
"versus": baseline.name,
**{f"fold {k}": delta.loc[k] for k in GATE_FOLDS},
"mean": delta.mean(),
"passes": bool(delta.mean() >= GATE_ZOOM_AP and (delta > 0).all()),
}
)
display(pd.DataFrame(gate_rows).set_index("recipe").round(2))
Latency¶
Show the latency table. call_ms is the median time of one call and per_image_ms divides it by the images in the call. The ratio divides a row by the plain call of the same batch size, so it reads as how many plain calls a call costs: 1.0 is free and V is the cost of running the network V times in sequence.
cost = latency.reset_index()
cost["per_image_ms"] = cost["call_ms"] / cost["batch_size"]
plain_ms = cost[cost["arm"] == "plain"].set_index("batch_size")["call_ms"]
cost["ratio_vs_plain"] = cost["call_ms"] / cost["batch_size"].map(plain_ms)
cost["views"] = cost["arm"].map(lambda name: by_name[name].views)
display(cost.set_index(["arm", "batch_size"]).round(2))
Mask guard¶
Zoomed views change how masks are voted, which the box gates do not see. For each recipe show the mask AP change against four shift views on every gate fold. A recipe stays acceptable for segmentation models when its mean change is not below -MASK_TOLERANCE.
if SEGMENT_MODEL is None:
print(f"RF-DETR {MODEL_SIZE} has no segmentation model: there is no mask table.")
else:
mask_rows = rows[(rows["kind"] == "mask") & (rows["model"] == SEGMENT_MODEL)]
mask = mask_rows.pivot(index="arm", columns="fold", values="mask_ap") * 100
mask = mask.loc[[arm.name for arm in mask_arms], list(GATE_FOLDS)]
mask_gain = mask.sub(mask.loc[MASK_BASELINE.name], axis=1)
mask_gain["mean"] = mask_gain.mean(axis=1)
mask_gain["acceptable"] = mask_gain["mean"] >= -MASK_TOLERANCE
display(mask.round(2))
display(mask_gain.round(2))
How to read it: the first table is mask AP in percent per gate fold, and the second is each recipe minus four shift views. A recipe with a clearly negative mean costs mask quality even when its boxes improve, so it should not be the default for segmentation models.
Footer: what produced these numbers¶
Print the provenance the tables depend on. Paste this footer next to any table you copy into the docs.
# Include the optional model package only when the sweep uses it.
plus_note = f"rfdetr_plus {provenance['rfdetr_plus']} | " if MODEL_SIZE in PLUS_SIZES else ""
print(
f"Hardware: {provenance['device']} | rfdetr {provenance['rfdetr']} (commit {provenance['commit']}) | "
f"{plus_note}torch {provenance['torch']} | supervision {provenance['supervision']} | "
f"faster-coco-eval {provenance['faster_coco_eval']} | Python {provenance['python']} | "
f"run started {provenance['started_utc']} UTC | box AP on {len(subset.image_ids)} COCO val2017 images at "
f"threshold {AP_THRESHOLD} in {N_FOLDS} folds, mask AP on folds {list(GATE_FOLDS)}, latency at threshold "
f"{LATENCY_THRESHOLD}, median of {RUNS} timed calls after {WARMUP} warm-up calls."
)