Cofiber Threshold: trained weights, COCO mAP 4.0 from 70K params, eval script
Browse files- eval_coco_map.py +198 -0
- heads/cofiber_threshold/README.md +28 -4
- heads/cofiber_threshold/coco_eval.json +13 -0
- heads/cofiber_threshold/head_final.pth +3 -0
- outputs/cofiber_threshold_full/checkpoint.pth +1 -1
- outputs/cofiber_threshold_full/head_final.pth +3 -0
- outputs/cofiber_threshold_full/head_final_coco_summary.json +13 -0
eval_coco_map.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Evaluate a trained detection head on COCO val2017 using pycocotools mAP.
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
python eval_coco_map.py --checkpoint outputs/cofiber_threshold_full/head_final.pth --head cofiber_threshold
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import sys
|
| 12 |
+
import time
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import torch
|
| 16 |
+
import torch.nn.functional as F
|
| 17 |
+
from PIL import Image
|
| 18 |
+
from torchvision.transforms import v2
|
| 19 |
+
|
| 20 |
+
sys.path.insert(0, os.path.dirname(__file__))
|
| 21 |
+
|
| 22 |
+
EUPE_REPO = os.environ.get("ARENA_BACKBONE_REPO", "/home/zootest/EUPE")
|
| 23 |
+
EUPE_WEIGHTS = os.environ.get("ARENA_BACKBONE_WEIGHTS", "/home/zootest/weights/eupe_vitb/EUPE-ViT-B.pt")
|
| 24 |
+
COCO_ROOT = os.environ.get("ARENA_COCO_ROOT", "/mnt/d/JacobProject/datasets/llava_instruct/coco")
|
| 25 |
+
RESOLUTION = 640
|
| 26 |
+
|
| 27 |
+
if EUPE_REPO not in sys.path:
|
| 28 |
+
sys.path.insert(0, EUPE_REPO)
|
| 29 |
+
|
| 30 |
+
COCO_CONTIG_TO_CAT = [
|
| 31 |
+
1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,18,19,20,21,22,23,24,25,27,28,31,32,
|
| 32 |
+
33,34,35,36,37,38,39,40,41,42,43,44,46,47,48,49,50,51,52,53,54,55,56,57,58,
|
| 33 |
+
59,60,61,62,63,64,65,67,70,72,73,74,75,76,77,78,79,80,81,82,84,85,86,87,88,89,90,
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def letterbox(image, res):
|
| 38 |
+
W0, H0 = image.size
|
| 39 |
+
scale = res / max(H0, W0)
|
| 40 |
+
new_w, new_h = int(round(W0 * scale)), int(round(H0 * scale))
|
| 41 |
+
resized = image.resize((new_w, new_h), Image.BILINEAR)
|
| 42 |
+
canvas = Image.new("RGB", (res, res), (0, 0, 0))
|
| 43 |
+
canvas.paste(resized, (0, 0))
|
| 44 |
+
return canvas, scale
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def main():
|
| 48 |
+
parser = argparse.ArgumentParser()
|
| 49 |
+
parser.add_argument("--checkpoint", required=True)
|
| 50 |
+
parser.add_argument("--head", default="cofiber_threshold")
|
| 51 |
+
parser.add_argument("--score-thresh", type=float, default=0.05)
|
| 52 |
+
parser.add_argument("--max-images", type=int, default=5000)
|
| 53 |
+
args = parser.parse_args()
|
| 54 |
+
|
| 55 |
+
from pycocotools.coco import COCO
|
| 56 |
+
from pycocotools.cocoeval import COCOeval
|
| 57 |
+
|
| 58 |
+
print("=" * 60)
|
| 59 |
+
print(f"COCO mAP Evaluation: {args.head}")
|
| 60 |
+
print("=" * 60)
|
| 61 |
+
|
| 62 |
+
# Load backbone
|
| 63 |
+
print("\nLoading backbone...")
|
| 64 |
+
backbone = torch.hub.load(EUPE_REPO, "eupe_vitb16", source="local", weights=EUPE_WEIGHTS)
|
| 65 |
+
backbone = backbone.cuda().eval()
|
| 66 |
+
for p in backbone.parameters():
|
| 67 |
+
p.requires_grad = False
|
| 68 |
+
|
| 69 |
+
# Load head
|
| 70 |
+
print(f"Loading head: {args.head}")
|
| 71 |
+
from heads import get_head
|
| 72 |
+
head = get_head(args.head)
|
| 73 |
+
state_dict = torch.load(args.checkpoint, map_location="cuda", weights_only=False)
|
| 74 |
+
if "head" in state_dict:
|
| 75 |
+
state_dict = state_dict["head"]
|
| 76 |
+
head.load_state_dict(state_dict)
|
| 77 |
+
head = head.cuda().eval()
|
| 78 |
+
n_params = sum(p.numel() for p in head.parameters())
|
| 79 |
+
print(f" {n_params:,} params")
|
| 80 |
+
|
| 81 |
+
# Precompute locations
|
| 82 |
+
with torch.no_grad():
|
| 83 |
+
dummy = torch.randn(1, 768, RESOLUTION // 16, RESOLUTION // 16, device="cuda")
|
| 84 |
+
locs = head.get_locs(dummy)
|
| 85 |
+
|
| 86 |
+
# Load COCO val
|
| 87 |
+
ann_file = os.path.join(COCO_ROOT, "annotations", "instances_val2017.json")
|
| 88 |
+
img_dir = os.path.join(COCO_ROOT, "val2017")
|
| 89 |
+
coco_gt = COCO(ann_file)
|
| 90 |
+
img_ids = sorted(coco_gt.getImgIds())[:args.max_images]
|
| 91 |
+
print(f" {len(img_ids)} val images")
|
| 92 |
+
|
| 93 |
+
normalize = v2.Compose([
|
| 94 |
+
v2.ToImage(), v2.ToDtype(torch.float32, scale=True),
|
| 95 |
+
v2.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
|
| 96 |
+
])
|
| 97 |
+
|
| 98 |
+
# Run inference
|
| 99 |
+
print("\nRunning inference...")
|
| 100 |
+
results = []
|
| 101 |
+
t0 = time.time()
|
| 102 |
+
|
| 103 |
+
for i, img_id in enumerate(img_ids):
|
| 104 |
+
info = coco_gt.loadImgs(img_id)[0]
|
| 105 |
+
img = Image.open(os.path.join(img_dir, info["file_name"])).convert("RGB")
|
| 106 |
+
W0, H0 = img.size
|
| 107 |
+
canvas, scale = letterbox(img, RESOLUTION)
|
| 108 |
+
x = normalize(canvas).unsqueeze(0).cuda()
|
| 109 |
+
|
| 110 |
+
with torch.no_grad():
|
| 111 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 112 |
+
out = backbone.forward_features(x)
|
| 113 |
+
patches = out["x_norm_patchtokens"].float()
|
| 114 |
+
B, N, D = patches.shape
|
| 115 |
+
h = w = int(N ** 0.5)
|
| 116 |
+
spatial = patches.permute(0, 2, 1).reshape(B, D, h, w)
|
| 117 |
+
|
| 118 |
+
cls_l, reg_l, ctr_l = head(spatial)
|
| 119 |
+
|
| 120 |
+
# Decode
|
| 121 |
+
from utils.decode import decode_fcos
|
| 122 |
+
dets = decode_fcos(cls_l, reg_l, ctr_l, locs,
|
| 123 |
+
score_thresh=args.score_thresh, nms_thresh=0.5, max_det=100)
|
| 124 |
+
|
| 125 |
+
for det in dets:
|
| 126 |
+
boxes = det["boxes"].cpu().numpy() / scale
|
| 127 |
+
boxes[:, 0::2] = boxes[:, 0::2].clip(0, W0)
|
| 128 |
+
boxes[:, 1::2] = boxes[:, 1::2].clip(0, H0)
|
| 129 |
+
scores = det["scores"].cpu().numpy()
|
| 130 |
+
labels = det["labels"].cpu().numpy()
|
| 131 |
+
|
| 132 |
+
for box, score, label in zip(boxes, scores, labels):
|
| 133 |
+
x1, y1, x2, y2 = box
|
| 134 |
+
results.append({
|
| 135 |
+
"image_id": img_id,
|
| 136 |
+
"category_id": COCO_CONTIG_TO_CAT[int(label)],
|
| 137 |
+
"bbox": [float(x1), float(y1), float(x2 - x1), float(y2 - y1)],
|
| 138 |
+
"score": float(score),
|
| 139 |
+
})
|
| 140 |
+
|
| 141 |
+
if (i + 1) % 500 == 0:
|
| 142 |
+
elapsed = time.time() - t0
|
| 143 |
+
print(f" {i+1}/{len(img_ids)} ({elapsed:.0f}s, {(i+1)/elapsed:.1f} img/s)", flush=True)
|
| 144 |
+
|
| 145 |
+
elapsed = time.time() - t0
|
| 146 |
+
print(f"\nInference complete: {len(img_ids)} images, {len(results)} detections, {elapsed:.0f}s")
|
| 147 |
+
|
| 148 |
+
# Save results
|
| 149 |
+
results_file = args.checkpoint.replace(".pth", "_coco_results.json")
|
| 150 |
+
with open(results_file, "w") as f:
|
| 151 |
+
json.dump(results, f)
|
| 152 |
+
print(f"Saved: {results_file}")
|
| 153 |
+
|
| 154 |
+
# Evaluate
|
| 155 |
+
if len(results) == 0:
|
| 156 |
+
print("\nNo detections produced. mAP = 0.0")
|
| 157 |
+
return
|
| 158 |
+
|
| 159 |
+
print("\nRunning pycocotools evaluation...")
|
| 160 |
+
coco_dt = coco_gt.loadRes(results_file)
|
| 161 |
+
coco_eval = COCOeval(coco_gt, coco_dt, "bbox")
|
| 162 |
+
coco_eval.params.imgIds = img_ids
|
| 163 |
+
coco_eval.evaluate()
|
| 164 |
+
coco_eval.accumulate()
|
| 165 |
+
coco_eval.summarize()
|
| 166 |
+
|
| 167 |
+
# Save summary
|
| 168 |
+
summary = {
|
| 169 |
+
"head": args.head,
|
| 170 |
+
"params": n_params,
|
| 171 |
+
"checkpoint": args.checkpoint,
|
| 172 |
+
"n_images": len(img_ids),
|
| 173 |
+
"n_detections": len(results),
|
| 174 |
+
"mAP_0.5_0.95": float(coco_eval.stats[0]),
|
| 175 |
+
"mAP_0.50": float(coco_eval.stats[1]),
|
| 176 |
+
"mAP_0.75": float(coco_eval.stats[2]),
|
| 177 |
+
"mAP_small": float(coco_eval.stats[3]),
|
| 178 |
+
"mAP_medium": float(coco_eval.stats[4]),
|
| 179 |
+
"mAP_large": float(coco_eval.stats[5]),
|
| 180 |
+
}
|
| 181 |
+
summary_file = args.checkpoint.replace(".pth", "_coco_summary.json")
|
| 182 |
+
with open(summary_file, "w") as f:
|
| 183 |
+
json.dump(summary, f, indent=2)
|
| 184 |
+
print(f"\nSaved: {summary_file}")
|
| 185 |
+
|
| 186 |
+
print(f"\n{'='*60}")
|
| 187 |
+
print(f" {args.head}: {n_params:,} params")
|
| 188 |
+
print(f" mAP@[0.5:0.95] = {summary['mAP_0.5_0.95']:.1f}")
|
| 189 |
+
print(f" mAP@0.50 = {summary['mAP_0.50']:.1f}")
|
| 190 |
+
print(f" mAP@0.75 = {summary['mAP_0.75']:.1f}")
|
| 191 |
+
print(f" mAP small = {summary['mAP_small']:.1f}")
|
| 192 |
+
print(f" mAP medium = {summary['mAP_medium']:.1f}")
|
| 193 |
+
print(f" mAP large = {summary['mAP_large']:.1f}")
|
| 194 |
+
print(f"{'='*60}")
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
if __name__ == "__main__":
|
| 198 |
+
main()
|
heads/cofiber_threshold/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
# Cofiber Threshold
|
| 2 |
|
| 3 |
-
Adjoint cofiber decomposition + per-scale LayerNorm + prototype classification.
|
| 4 |
|
| 5 |
## Architecture
|
| 6 |
|
|
@@ -11,7 +11,7 @@ Scale decomposition (0 learned params):
|
|
| 11 |
cofiber_k = f_k - upsample(avgpool(f_k)) for k = 0, 1
|
| 12 |
residual = avgpool(avgpool(f)) for k = 2
|
| 13 |
|
| 14 |
-
Per-scale prediction (
|
| 15 |
For each scale k:
|
| 16 |
f = LayerNorm(cofiber_k)
|
| 17 |
cls = f @ prototypes.T + bias (80 classes)
|
|
@@ -23,13 +23,37 @@ The cofiber `x - upsample(pool(x))` isolates information present at a given spat
|
|
| 23 |
|
| 24 |
## Results
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
| Protocol | Domains | Avg Precision | Avg Recall | Total TP |
|
| 27 |
|----------|---------|---------------|------------|----------|
|
| 28 |
| 2K steps screening | 21 | 0.475 | 0.193 | 478 |
|
| 29 |
| 15K steps extended | 21 | 0.617 | 0.368 | 719 |
|
| 30 |
|
| 31 |
-
Exceeds Baseline FCOS (16.14M params, 0.470 avg precision) at 230x fewer parameters.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
## Threshold circuit form
|
| 34 |
|
| 35 |
-
The
|
|
|
|
| 1 |
# Cofiber Threshold
|
| 2 |
|
| 3 |
+
Adjoint cofiber decomposition + per-scale LayerNorm + prototype classification. 69,976 parameters.
|
| 4 |
|
| 5 |
## Architecture
|
| 6 |
|
|
|
|
| 11 |
cofiber_k = f_k - upsample(avgpool(f_k)) for k = 0, 1
|
| 12 |
residual = avgpool(avgpool(f)) for k = 2
|
| 13 |
|
| 14 |
+
Per-scale prediction (~70K learned params):
|
| 15 |
For each scale k:
|
| 16 |
f = LayerNorm(cofiber_k)
|
| 17 |
cls = f @ prototypes.T + bias (80 classes)
|
|
|
|
| 23 |
|
| 24 |
## Results
|
| 25 |
|
| 26 |
+
### COCO val2017 (pycocotools, 5000 images)
|
| 27 |
+
|
| 28 |
+
Trained on COCO 2017 train (117,266 images), 8 epochs, batch 64, AdamW lr 1e-3, cosine schedule with 3% warmup. Frozen EUPE-ViT-B backbone.
|
| 29 |
+
|
| 30 |
+
| Metric | Cofiber Threshold (70K) | Baseline FCOS (16.14M) |
|
| 31 |
+
|--------|------------------------|----------------------|
|
| 32 |
+
| mAP@[0.5:0.95] | 4.0 | 41.0 |
|
| 33 |
+
| mAP@0.50 | 15.8 | 64.8 |
|
| 34 |
+
| mAP@0.75 | 0.8 | 43.2 |
|
| 35 |
+
| mAP small | 1.3 | 21.4 |
|
| 36 |
+
| mAP medium | 4.1 | 44.9 |
|
| 37 |
+
| mAP large | 6.3 | 62.1 |
|
| 38 |
+
| AR@100 | 14.9 | — |
|
| 39 |
+
|
| 40 |
+
The mAP@0.50 of 15.8 indicates the head locates objects at the correct class; the collapse at mAP@0.75 (0.8) indicates the single-layer box regression cannot produce tight bounding boxes.
|
| 41 |
+
|
| 42 |
+
### Cross-domain screening (21 domains, COCO + RF100-VL)
|
| 43 |
+
|
| 44 |
| Protocol | Domains | Avg Precision | Avg Recall | Total TP |
|
| 45 |
|----------|---------|---------------|------------|----------|
|
| 46 |
| 2K steps screening | 21 | 0.475 | 0.193 | 478 |
|
| 47 |
| 15K steps extended | 21 | 0.617 | 0.368 | 719 |
|
| 48 |
|
| 49 |
+
Exceeds Baseline FCOS (16.14M params, 0.470 avg precision) at 230x fewer parameters on the cross-domain screening protocol.
|
| 50 |
+
|
| 51 |
+
## Files
|
| 52 |
+
|
| 53 |
+
- `head.py` — architecture implementation
|
| 54 |
+
- `head_final.pth` — trained weights (COCO 2017, 8 epochs)
|
| 55 |
+
- `coco_eval.json` — pycocotools evaluation summary
|
| 56 |
|
| 57 |
## Threshold circuit form
|
| 58 |
|
| 59 |
+
The head can be expressed as a depth-3 threshold gate network with 2,184,000 gates. Layers 0-1 use fixed integer weights {-1, 0, 1}. Layer 2 uses INT8 quantized prototypes (99.7% detection agreement with FP32). See `phanerozoic/threshold-cofiber-detection` for the serialized circuit.
|
heads/cofiber_threshold/coco_eval.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"head": "cofiber_threshold",
|
| 3 |
+
"params": 69976,
|
| 4 |
+
"checkpoint": "outputs/cofiber_threshold_full/head_final.pth",
|
| 5 |
+
"n_images": 5000,
|
| 6 |
+
"n_detections": 499925,
|
| 7 |
+
"mAP_0.5_0.95": 0.04049779195869424,
|
| 8 |
+
"mAP_0.50": 0.15815283266196423,
|
| 9 |
+
"mAP_0.75": 0.007915213278509007,
|
| 10 |
+
"mAP_small": 0.012886382966430599,
|
| 11 |
+
"mAP_medium": 0.04094513118407366,
|
| 12 |
+
"mAP_large": 0.06285424921271325
|
| 13 |
+
}
|
heads/cofiber_threshold/head_final.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b260a0fae7ec7a86bb38f3e087700f7c5ec171a7cd16ef0141f04478363001a8
|
| 3 |
+
size 284981
|
outputs/cofiber_threshold_full/checkpoint.pth
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
size 284981
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8423ca32fe6517e771d1ec7f009ffa8e58952e5be5ec172d0b227ade1bf01517
|
| 3 |
size 284981
|
outputs/cofiber_threshold_full/head_final.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b260a0fae7ec7a86bb38f3e087700f7c5ec171a7cd16ef0141f04478363001a8
|
| 3 |
+
size 284981
|
outputs/cofiber_threshold_full/head_final_coco_summary.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"head": "cofiber_threshold",
|
| 3 |
+
"params": 69976,
|
| 4 |
+
"checkpoint": "outputs/cofiber_threshold_full/head_final.pth",
|
| 5 |
+
"n_images": 5000,
|
| 6 |
+
"n_detections": 499925,
|
| 7 |
+
"mAP_0.5_0.95": 0.04049779195869424,
|
| 8 |
+
"mAP_0.50": 0.15815283266196423,
|
| 9 |
+
"mAP_0.75": 0.007915213278509007,
|
| 10 |
+
"mAP_small": 0.012886382966430599,
|
| 11 |
+
"mAP_medium": 0.04094513118407366,
|
| 12 |
+
"mAP_large": 0.06285424921271325
|
| 13 |
+
}
|