Test-Time Augmentation Views: What They Cost and What They Buy¶
RFDETRInference.predict(images, tta=TTAConfig(...)) runs the same network on several views of each image, maps every view's detections back to the image, and averages the matching ones. A view is a copy of the image that is moved by a fraction of a backbone patch (shift) or resized (zoom). TTA is opt-in: without tta the call is the plain prediction. TTAConfig() runs one native-scale view and three zooms on padded canvases. CUDA combines views by canvas shape and can split each group across several forwards.
This notebook runs every released detection size on full COCO val2017 and answers two questions on your own hardware:
- How much box AP do
Vviews add for each model size, for shift views (V= 1, 2, 4, 6, 8) and for the default zoom views (V= 2, 4), and how far does that gain move between disjoint folds of the data? - What does one prediction cost in latency at one image per call and at eight images per call, and does a smaller model with views ever beat a larger model without them?
The docs page Test-Time Augmentation, under Learn, holds the full study, including the shift+zoom recipes, per-stage cost, memory and runtime switches, measured with an extended version of this notebook.
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 at the end. Copy numbers into other docs only together with that footer.
Install the package with the COCO scoring backends (train), the plotting dependencies (visual) and the Plus models (plus). The install pins the 1.13.0 release, which includes the views. Restart the kernel afterwards so the recorded versions are the ones in use.
!pip install -q -U "rfdetr[train,visual,plus]==1.13.0" "rfdetr_plus>=1.2.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
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.detr import _default_compile_backend
from rfdetr.export._benchmark import (
CocoValSubset,
cpu_brand,
evaluate_coco_predictions,
fetch_coco_val2017,
time_predict_call,
)
Choose what to run¶
The defaults cover every released detection size, the Plus models included while ACCEPT_PLATFORM_MODEL_LICENSE = True, and score all 5000 COCO val2017 images. VIEWS counts shift views per image: 1 is the plain prediction and the baseline every other row is compared with. A full run takes hours on one GPU; every row is written to disk as soon as it exists, so an interrupted run resumes. For a quick check lower N_AP_IMAGES and shorten MODELS and VIEWS.
Note: 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. Apache 2.0 covers the package, Nano–Large detection, every Seg size and Keypoint: commercial, closed-source and self-hosted use is included without a license fee or an obligation to open-source your code. Keep
ACCEPT_PLATFORM_MODEL_LICENSE = Trueonly if you accept the Plus model terms; set it toFalseto measure the Apache 2.0 models alone.
MODELS = ("RFDETRNano", "RFDETRSmall", "RFDETRMedium", "RFDETRLarge")
PLUS_MODELS = ("RFDETRAtto", "RFDETRFemto", "RFDETRPico", "RFDETRXLarge", "RFDETR2XLarge")
ACCEPT_PLATFORM_MODEL_LICENSE = True
# Smallest to largest, so plots and tables list the sizes in the order a reader expects.
SIZE_ORDER = ("Atto", "Femto", "Pico", "Nano", "Small", "Medium", "Large", "XLarge", "2XLarge")
if ACCEPT_PLATFORM_MODEL_LICENSE:
MODELS = tuple(sorted(MODELS + PLUS_MODELS, key=lambda name: SIZE_ORDER.index(name.removeprefix("RFDETR"))))
# Shift views per image. 1 is the plain prediction.
VIEWS = (1, 2, 4, 6, 8)
# Images scored for AP: None scores all 5000 val2017 images.
N_AP_IMAGES = None
# AP is also scored on this many disjoint folds, to show how much a gain moves between parts of the data.
N_FOLDS = 5
# Images per call while scoring 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-views-run")
Describe one arm of the sweep: a recipe name, how many views it runs and the TTAConfig that produces them. The shift arms are the main sweep. The zoom arms are the recommended recipe: TTAConfig(zoom=(1.25,)) is two views and TTAConfig() is four. view_count confirms each arm runs the number of views it claims.
class Arm(NamedTuple):
"""One view recipe at one view count."""
recipe: str
views: int
config: TTAConfig | None
# `None` keeps V=1 on the plain path, the baseline every other row is compared with.
PLAIN = Arm("shift", 1, None)
SHIFT_ARMS = [Arm("shift", v, TTAConfig(shift=v) if v > 1 else None) for v in VIEWS]
ZOOM_ARMS = [Arm("zoom", 2, TTAConfig(zoom=(1.25,))), Arm("zoom", 4, TTAConfig())]
ARMS = SHIFT_ARMS + ZOOM_ARMS
for arm in ARMS:
assert arm.config is None or view_count(arm.config) == arm.views, arm
Reject unusable settings before any download. The shift count of a model is bounded by its patch size, so that part is checked after each model loads.
assert MODELS and VIEWS, "Select at least one model and view count."
assert VIEWS[0] == 1, "List 1 first: V=1 is the baseline the other rows are compared with."
assert all(isinstance(v, int) and v >= 1 for v in VIEWS), "View counts are integers >= 1."
assert ACCEPT_PLATFORM_MODEL_LICENSE or not set(MODELS) & set(PLUS_MODELS), (
"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 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 the largest timing batch."
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 row.")
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
snapshot_backend = _default_compile_backend(device)
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"),
"commit": direct_url.get("vcs_info", {}).get("commit_id"),
"rfdetr_plus": package_version("rfdetr_plus"),
"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(),
"snapshot_backend": snapshot_backend,
"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 plots 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 plots 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, with identical inputs for eager and optimized inference.
# 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. Both 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 disjoint fold without predicting twice. fold_box_ap is what the paired gain and its spread are built from.
def score_ap(predictor: RFDETRInference, arm: Arm, images: CocoValSubset) -> dict[str, object]:
"""Return box AP, AP50 and the per-fold box AP of ``arm`` on the COCO subset ``images``."""
ids = list(images.image_ids)
detections = predictor.predict(
[str(image_paths[i]) for i in ids],
threshold=AP_THRESHOLD,
include_source_image=False,
batch=AP_BATCH,
tta=arm.config,
)
stored = dict(zip(ids, detections, strict=True))
whole = evaluate_coco_predictions(stored, images, "detect")
# Interleaved folds, so every fold sees the whole range of the data.
folds = [ids[k::N_FOLDS] for k in range(N_FOLDS)]
fold_ap = [evaluate_coco_predictions(stored, images, "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}
Latency next. 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 figures divide 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.recipe} V={arm.views} B={batch_size}",
device=device_kind,
warmup=WARMUP,
runs=RUNS,
threshold=LATENCY_THRESHOLD,
include_source_image=False,
tta=arm.config,
)
Run the sweep¶
The sweep stores one result file per experiment. The experiment identity records the ordered image IDs, recipes, 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": 1,
"runtime": {key: value for key, value in provenance.items() if key != "started_utc"},
"models": list(MODELS),
"arms": [
{"recipe": arm.recipe, "views": arm.views, "config": asdict(arm.config) if arm.config is not None else None}
for arm in ARMS
],
"ap_images": list(subset.image_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,
"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", "recipe", "views", "batch_size")
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) -> bool:
"""Return whether the row is already recorded."""
return (kind, model_name, arm.recipe, arm.views, batch_size) in done
def record(kind: str, model_name: str, arm: Arm, batch_size: 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,
"recipe": arm.recipe,
"views": arm.views,
"batch_size": batch_size,
**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.recipe, arm.views, batch_size))
Run the loop. For each model: the accuracy of every arm, the latency of every arm at each batch size, and the plain prediction of an optimized inference() snapshot, the reference a user could run instead of views. Warnings stay visible, since a warning about a deprecated path changes how a number should be read.
OPTIMIZED = Arm("plain-optimized", 1, None)
for model_name in MODELS:
model = getattr(rfdetr, model_name)(device=device_kind)
patch = model.model_config.patch_size
assert max(VIEWS) <= patch, f"{model_name}: shift views are at most the patch size ({patch}), got {max(VIEWS)}."
predictor = RFDETRInference(model)
for arm in tqdm(ARMS, desc=model_name):
if not have("accuracy", model_name, arm):
record("accuracy", model_name, arm, **score_ap(predictor, arm, subset))
for batch_size in BATCH_SIZES:
if not have("latency", model_name, arm, batch_size):
record("latency", model_name, arm, batch_size, **time_call(predictor, arm, batch_size))
if not have("latency", model_name, OPTIMIZED, 1):
snapshot = model.inference(compile_backend=snapshot_backend)
record("latency", model_name, OPTIMIZED, 1, **time_call(snapshot, OPTIMIZED, 1))
del snapshot
del predictor, model
if device_kind == "cuda":
torch.cuda.empty_cache()
Analyze the validated rows loaded from the experiment file and the measurements appended in this session. The tables below share the same input IDs and runtime settings, whether the sweep ran in one session or resumed.
# 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)
index = ["model", "recipe", "views"]
accuracy = rows[rows["kind"] == "accuracy"].set_index(index)[["box_ap", "box_ap50", "fold_box_ap"]].sort_index()
# Accuracy rows have no batch size, so the column holds NaN until they are filtered out.
latency = (
rows[rows["kind"] == "latency"]
.astype({"batch_size": int})
.set_index(index + ["batch_size"])[["call_ms", "call_p95_ms"]]
.sort_index()
)
models_in_order = [m for m in MODELS if m in set(rows["model"])]
Show the accuracy table. AP is in percent. gain is the AP of the arm minus the model's plain AP 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. The gain is paired: the plain prediction is scored on the same images in every fold.
def paired_gain(frame: pd.DataFrame) -> pd.DataFrame:
"""Add the AP gain over the plain prediction of the same model, and its fold-to-fold standard error."""
out = frame.copy()
out["box_ap"] *= 100
base = frame.xs(("shift", 1), level=("recipe", "views"))
gains, errors = [], []
for (model_name, _, _), row in frame.iterrows():
plain = base.loc[model_name]
fold_gain = (np.array(row["fold_box_ap"]) - np.array(plain["fold_box_ap"])) * 100
gains.append(row["box_ap"] * 100 - plain["box_ap"] * 100)
errors.append(fold_gain.std(ddof=1) / np.sqrt(len(fold_gain)))
out["gain"], out["gain_se"] = gains, errors
return out.drop(columns=["fold_box_ap", "box_ap50"])
gains = paired_gain(accuracy)
display(gains.round(3))
Show the latency table. call_ms is the median time of one call. The ratio divides a row by the same model's plain call at one image, 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.
plain_call = latency.xs(("shift", 1, 1), level=("recipe", "views", "batch_size"))["call_ms"]
cost = latency.copy()
cost["ratio_vs_plain"] = [row.call_ms / plain_call.loc[key[0]] for key, row in cost.iterrows()]
display(cost.round(2))
Plot box AP against latency, one curve per model¶
This is the figure to read first. Each solid curve is one model size; each point on it is the number of shift views, labelled V (1, 2, 4, 6, 8). Each square joined to the plain point by a dashed line is a zoom recipe, labelled V (2 and 4). The x axis is the latency of one prediction per image. Each panel is a configured image count per call. The analysis divides call time by image count. On CUDA, the forward passes group rows by canvas shape and can split a group to fit more views. The leftmost point of a curve is the plain prediction, and the cross marks the optimized inference() latency at the eager baseline AP for visual reference. Snapshot AP was not measured. A point above and to the left of another is better on both axes, so the question is whether the views of a small model beat the plain prediction of a larger one.
colors = {name: plt.cm.viridis(i / max(1, len(models_in_order) - 1)) for i, name in enumerate(models_in_order)}
fig, axes = plt.subplots(1, len(BATCH_SIZES), figsize=(7 * len(BATCH_SIZES), 6), sharey=True)
for ax, batch_size in zip(np.atleast_1d(axes), BATCH_SIZES):
for name in models_in_order:
def point(recipe: str, v: int) -> tuple[float, float]:
"""Return (latency per image in ms, box AP in percent) of one arm."""
return latency.loc[(name, recipe, v, batch_size), "call_ms"] / batch_size, accuracy.loc[
(name, recipe, v), "box_ap"
] * 100
shift_points = [point("shift", v) for v in VIEWS]
ax.plot(*zip(*shift_points), marker="o", color=colors[name], label=name.removeprefix("RFDETR"))
for (x, y), v in zip(shift_points, VIEWS):
ax.annotate(str(v), (x, y), textcoords="offset points", xytext=(4, 4), fontsize=8)
zoom_points = [shift_points[0]] + [point("zoom", arm.views) for arm in ZOOM_ARMS]
ax.plot(*zip(*zoom_points), marker="s", linestyle="--", color=colors[name])
if batch_size == 1:
optimized = latency.xs((name, "plain-optimized"), level=("model", "recipe"))["call_ms"]
ax.scatter(
[optimized.iloc[0]],
[shift_points[0][1]],
marker="x",
color=colors[name],
label="Snapshot latency at eager AP" if name == models_in_order[0] else None,
)
ax.set_xscale("log")
ax.set_title(f"Latency with batch size {batch_size}")
ax.set_xlabel("latency per image (ms, log)")
ax.grid(alpha=0.3)
np.atleast_1d(axes)[0].set_ylabel("box AP, % (COCO val2017)")
np.atleast_1d(axes)[0].legend(title="model", ncol=1, loc="lower right")
plt.tight_layout()
plt.show()
How to read it: the labels are views per image. A curve that rises steeply and then flattens has hit diminishing returns at the label where it bends; compare that label with the gain and gain_se in the table before calling a bend real. If the plain point of a larger model sits above and to the left of a smaller model's last point, the larger model is the better use of the latency. With larger image batches the views and images compete for the same device, so the curves can stretch farther to the right. On a device without CUDA the views do not batch, so every curve is stretched to the right.
Plot the gain against the number of views¶
The left panel is the paired AP gain over the plain prediction for shift views, one line per model, with the fold-to-fold standard error as error bars. The right panel is the same for the zoom recipes, which run two and four views. Both share the y axis, so the two recipes compare directly at the same number of views.
fig, (ax_shift, ax_zoom) = plt.subplots(1, 2, figsize=(11, 4), sharey=True)
for ax, recipe in ((ax_shift, "shift"), (ax_zoom, "zoom")):
for name in models_in_order:
group = gains.xs((name, recipe), level=("model", "recipe"))
ax.errorbar(
group.index,
group["gain"],
yerr=group["gain_se"],
marker="o",
color=colors[name],
label=name.removeprefix("RFDETR"),
capsize=2,
)
ax.axhline(0, color="gray", linewidth=0.8)
ax.set_title(f"{recipe} views")
ax.set_xscale("log", base=2)
ax.set_xticks(VIEWS, labels=[str(v) for v in VIEWS])
ax.set_xlabel("views per image")
ax.grid(alpha=0.3)
ax_shift.set_ylabel("box AP gain over plain, points")
ax_shift.legend(ncol=1, fontsize=8)
plt.show()
How to read it: an error bar that covers zero means the gain is not distinguishable from the fold-to-fold spread. Compare the two panels at the same view count: a higher zoom line at 2 and 4 views means a zoomed view buys more AP than a shifted one, at the cost of a larger canvas and so a longer call, which the latency table shows.
Footer: what produced these numbers¶
Print the provenance the tables and plots depend on. Paste this footer next to any table you copy into the docs.
print(
f"Hardware: {provenance['device']} | rfdetr {provenance['rfdetr']} (commit {provenance['commit']}) | "
f"rfdetr_plus {provenance['rfdetr_plus']} | torch {provenance['torch']} | supervision {provenance['supervision']} | "
f"faster-coco-eval {provenance['faster_coco_eval']} | Python {provenance['python']} | "
f"run started {provenance['started_utc']} UTC | AP on {len(subset.image_ids)} COCO val2017 images at threshold "
f"{AP_THRESHOLD} in {N_FOLDS} folds, latency at threshold {LATENCY_THRESHOLD}, median of {RUNS} timed calls after "
f"{WARMUP} warm-up calls."
)