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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Fine-tune facebook/detr-resnet-50 (Apache-2.0) on biglam/loc_beyond_words (7 classes)."""
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from datasets import load_dataset
|
| 10 |
+
|
| 11 |
+
from torch.utils.data import DataLoader, Dataset, Subset
|
| 12 |
+
import torchmetrics
|
| 13 |
+
from transformers import AutoProcessor, DetrForObjectDetection, get_scheduler
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
CLASSES = ["Photograph", "Illustration", "Map", "Comics/Cartoon",
|
| 17 |
+
"Editorial Cartoon", "Headline", "Advertisement"]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class DetrDataset(Dataset):
|
| 21 |
+
def __init__(self, hf_ds, processor):
|
| 22 |
+
self.ds = hf_ds
|
| 23 |
+
self.processor = processor
|
| 24 |
+
|
| 25 |
+
def __len__(self):
|
| 26 |
+
return len(self.ds)
|
| 27 |
+
|
| 28 |
+
def __getitem__(self, idx):
|
| 29 |
+
ex = self.ds[idx]
|
| 30 |
+
x, y, w, h = ex["width"], ex["height"], None, None
|
| 31 |
+
annotations = []
|
| 32 |
+
for o in ex["objects"]:
|
| 33 |
+
bx, by, bw, bh = [float(v) for v in o["bbox"]]
|
| 34 |
+
annotations.append({
|
| 35 |
+
"bbox": [bx, by, bw, bh],
|
| 36 |
+
"category_id": o["category_id"],
|
| 37 |
+
"area": float(bw * bh),
|
| 38 |
+
"iscrowd": o["iscrowd"],
|
| 39 |
+
"id": o["id"],
|
| 40 |
+
})
|
| 41 |
+
target = {"image_id": idx, "annotations": annotations}
|
| 42 |
+
encoding = self.processor(images=ex["image"], annotations=target, return_tensors="pt")
|
| 43 |
+
return {
|
| 44 |
+
"pixel_values": encoding["pixel_values"].squeeze(0),
|
| 45 |
+
"labels": encoding["labels"][0],
|
| 46 |
+
"height": ex["height"],
|
| 47 |
+
"width": ex["width"],
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def collate_fn(batch, processor):
|
| 52 |
+
pvs = [item["pixel_values"] for item in batch]
|
| 53 |
+
max_h = max(pv.shape[1] for pv in pvs)
|
| 54 |
+
max_w = max(pv.shape[2] for pv in pvs)
|
| 55 |
+
bs = len(batch)
|
| 56 |
+
pix = torch.zeros(bs, 3, max_h, max_w)
|
| 57 |
+
mask = torch.zeros(bs, max_h, max_w, dtype=torch.int64)
|
| 58 |
+
for i, pv in enumerate(pvs):
|
| 59 |
+
h, w = pv.shape[1], pv.shape[2]
|
| 60 |
+
pix[i, :, :h, :w] = pv
|
| 61 |
+
mask[i, :h, :w] = 1
|
| 62 |
+
return {
|
| 63 |
+
"pixel_values": pix,
|
| 64 |
+
"pixel_mask": mask,
|
| 65 |
+
"labels": [item["labels"] for item in batch],
|
| 66 |
+
"height": [item["height"] for item in batch],
|
| 67 |
+
"width": [item["width"] for item in batch],
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@torch.no_grad()
|
| 72 |
+
def evaluate(model, processor, loader, device, threshold=0.0):
|
| 73 |
+
model.eval()
|
| 74 |
+
try:
|
| 75 |
+
metric = torchmetrics.detection.MeanAveragePrecision(
|
| 76 |
+
iou_type="bbox", class_metrics=True, extended_summary=True, backend="faster_coco_eval")
|
| 77 |
+
except TypeError:
|
| 78 |
+
metric = torchmetrics.detection.MeanAveragePrecision(iou_type="bbox", class_metrics=True, extended_summary=True)
|
| 79 |
+
for batch in loader:
|
| 80 |
+
pv = batch["pixel_values"].to(device)
|
| 81 |
+
pm = batch["pixel_mask"].to(device)
|
| 82 |
+
out = model(pixel_values=pv, pixel_mask=pm)
|
| 83 |
+
target_sizes = torch.tensor([[h, w] for h, w in zip(batch["height"], batch["width"])])
|
| 84 |
+
preds = processor.post_process_object_detection(out, threshold=threshold, target_sizes=target_sizes)
|
| 85 |
+
for i in range(len(preds)):
|
| 86 |
+
pred = preds[i]
|
| 87 |
+
tar = batch["labels"][i]
|
| 88 |
+
image_size = torch.tensor([batch["height"][i], batch["width"][i]], dtype=torch.float)
|
| 89 |
+
# processor labels.boxes are normalized cxcywh-ish; convert to absolute xyxy
|
| 90 |
+
tboxes = tar["boxes"]
|
| 91 |
+
# boxes from processor are in [cx,cy,w,h] normalized 0..1
|
| 92 |
+
cx, cy, w, h = tboxes[:, 0] * image_size[1], tboxes[:, 1] * image_size[0], tboxes[:, 2] * image_size[1], tboxes[:, 3] * image_size[0]
|
| 93 |
+
xyxy = torch.stack([cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2], dim=1)
|
| 94 |
+
metric.update(
|
| 95 |
+
[{"boxes": pred["boxes"].cpu(), "scores": pred["scores"].cpu(), "labels": pred["labels"].cpu()}],
|
| 96 |
+
[{"boxes": xyxy, "labels": tar["class_labels"]}],
|
| 97 |
+
)
|
| 98 |
+
res = metric.compute()
|
| 99 |
+
out = {
|
| 100 |
+
"eval_map": float(res["map"]),
|
| 101 |
+
"eval_map_50": float(res["map_50"]),
|
| 102 |
+
"eval_map_75": float(res["map_75"]),
|
| 103 |
+
"per_class_map_50": [float(x) for x in res.get("map_50_per_class", [0.0] * 7)],
|
| 104 |
+
}
|
| 105 |
+
return out
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def main():
|
| 109 |
+
ap = argparse.ArgumentParser()
|
| 110 |
+
ap.add_argument("--epochs", type=int, default=14)
|
| 111 |
+
ap.add_argument("--batch", type=int, default=2)
|
| 112 |
+
ap.add_argument("--acc", type=int, default=4)
|
| 113 |
+
ap.add_argument("--lr", type=float, default=1e-4)
|
| 114 |
+
ap.add_argument("--backbone_lr", type=float, default=1e-5)
|
| 115 |
+
ap.add_argument("--max_train", type=int, default=0)
|
| 116 |
+
ap.add_argument("--max_eval", type=int, default=0)
|
| 117 |
+
ap.add_argument("--repo", type=str, default="harness-race/opencode-r1")
|
| 118 |
+
ap.add_argument("--push", action="store_true")
|
| 119 |
+
ap.add_argument("--outjson", type=str, default="val_results.json")
|
| 120 |
+
args = ap.parse_args()
|
| 121 |
+
|
| 122 |
+
model_id = "facebook/detr-resnet-50"
|
| 123 |
+
id2label = {i: c for i, c in enumerate(CLASSES)}
|
| 124 |
+
label2id = {c: i for i, c in enumerate(CLASSES)}
|
| 125 |
+
|
| 126 |
+
processor = AutoProcessor.from_pretrained(model_id)
|
| 127 |
+
|
| 128 |
+
ds = load_dataset("biglam/loc_beyond_words")
|
| 129 |
+
train_ds = DetrDataset(ds["train"], processor)
|
| 130 |
+
eval_ds = DetrDataset(ds["validation"], processor)
|
| 131 |
+
random.seed(0)
|
| 132 |
+
if args.max_train:
|
| 133 |
+
train_ds = Subset(train_ds, random.sample(range(len(train_ds)), min(args.max_train, len(train_ds))))
|
| 134 |
+
if args.max_eval:
|
| 135 |
+
eval_ds = Subset(eval_ds, random.sample(range(len(eval_ds)), min(args.max_eval, len(eval_ds))))
|
| 136 |
+
|
| 137 |
+
model = DetrForObjectDetection.from_pretrained(
|
| 138 |
+
model_id, num_labels=len(CLASSES), ignore_mismatched_sizes=True, id2label=id2label, label2id=label2id)
|
| 139 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 140 |
+
model = model.to(device)
|
| 141 |
+
|
| 142 |
+
train_loader = DataLoader(train_ds, batch_size=args.batch, shuffle=True,
|
| 143 |
+
collate_fn=lambda b: collate_fn(b, processor), num_workers=2, pin_memory=False)
|
| 144 |
+
eval_loader = DataLoader(eval_ds, batch_size=args.batch, shuffle=False,
|
| 145 |
+
collate_fn=lambda b: collate_fn(b, processor), num_workers=2, pin_memory=False)
|
| 146 |
+
|
| 147 |
+
param_groups = [
|
| 148 |
+
{"params": [p for n, p in model.named_parameters() if "backbone" in n], "lr": args.backbone_lr},
|
| 149 |
+
{"params": [p for n, p in model.named_parameters() if "backbone" not in n], "lr": args.lr},
|
| 150 |
+
]
|
| 151 |
+
optimizer = torch.optim.AdamW(param_groups, lr=args.lr, weight_decay=1e-4)
|
| 152 |
+
steps_per_epoch = len(train_loader) // args.acc
|
| 153 |
+
num_steps = steps_per_epoch * args.epochs
|
| 154 |
+
scheduler = get_scheduler("cosine", optimizer=optimizer, num_warmup_steps=int(0.05 * num_steps), num_training_steps=num_steps)
|
| 155 |
+
scaler = torch.cuda.amp.GradScaler(enabled=(device == "cuda"))
|
| 156 |
+
|
| 157 |
+
best_metric = -1.0
|
| 158 |
+
best_state = None
|
| 159 |
+
best_map50 = 0.0
|
| 160 |
+
results_log = []
|
| 161 |
+
|
| 162 |
+
for epoch in range(1, args.epochs + 1):
|
| 163 |
+
model.train()
|
| 164 |
+
optimizer.zero_grad()
|
| 165 |
+
running = 0.0
|
| 166 |
+
for step, batch in enumerate(train_loader):
|
| 167 |
+
pv = batch["pixel_values"].to(device)
|
| 168 |
+
pm = batch["pixel_mask"].to(device)
|
| 169 |
+
labels = [{k: v.to(device) if torch.is_tensor(v) else v for k, v in t.items()} for t in batch["labels"]]
|
| 170 |
+
with torch.cuda.amp.autocast(enabled=(device == "cuda")):
|
| 171 |
+
out = model(pixel_values=pv, pixel_mask=pm, labels=labels)
|
| 172 |
+
loss = out.loss / args.acc
|
| 173 |
+
scaler.scale(loss).backward()
|
| 174 |
+
running += float(out.loss.item())
|
| 175 |
+
if (step + 1) % args.acc == 0:
|
| 176 |
+
scaler.step(optimizer)
|
| 177 |
+
scaler.update()
|
| 178 |
+
scheduler.step()
|
| 179 |
+
optimizer.zero_grad()
|
| 180 |
+
# trailing
|
| 181 |
+
scaler.step(optimizer); scaler.update(); optimizer.zero_grad()
|
| 182 |
+
print(f"[epoch {epoch}] train_loss={running / len(train_loader):.4f}", flush=True)
|
| 183 |
+
|
| 184 |
+
res = evaluate(model, processor, eval_loader, device)
|
| 185 |
+
results_log.append({**res, "epoch": epoch})
|
| 186 |
+
print(f"[epoch {epoch}] val map={res['eval_map']:.4f} map50={res['eval_map_50']:.4f}", flush=True)
|
| 187 |
+
with open(args.outjson, "w") as f:
|
| 188 |
+
json.dump(results_log, f)
|
| 189 |
+
|
| 190 |
+
key = res["eval_map"]
|
| 191 |
+
if key > best_metric:
|
| 192 |
+
best_metric = key
|
| 193 |
+
best_map50 = res["eval_map_50"]
|
| 194 |
+
best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
|
| 195 |
+
torch.save(best_state, "best_model.pt")
|
| 196 |
+
print(f"[epoch {epoch}] new best map={best_metric:.4f}", flush=True)
|
| 197 |
+
|
| 198 |
+
# final best eval detailed
|
| 199 |
+
model.load_state_dict(torch.load("best_model.pt", map_location=device))
|
| 200 |
+
res = evaluate(model, processor, eval_loader, device)
|
| 201 |
+
print("BEST EVAL:", json.dumps(res))
|
| 202 |
+
|
| 203 |
+
final = {
|
| 204 |
+
"eval_map": best_metric,
|
| 205 |
+
"eval_map_50": best_map50,
|
| 206 |
+
"per_class_map_50": {
|
| 207 |
+
c: round(v, 4) for c, v in zip(CLASSES, res["per_class_map_50"])
|
| 208 |
+
},
|
| 209 |
+
"epochs": args.epochs,
|
| 210 |
+
"train_batches_seen": epoch,
|
| 211 |
+
"val_rows": len(eval_ds),
|
| 212 |
+
}
|
| 213 |
+
with open(args.outjson, "w") as f:
|
| 214 |
+
json.dump(final, f, indent=2)
|
| 215 |
+
|
| 216 |
+
if args.push:
|
| 217 |
+
os.environ.setdefault("HF_TOKEN", os.environ.get("HF_TOKEN", ""))
|
| 218 |
+
model.push_to_hub(args.repo)
|
| 219 |
+
processor.push_to_hub(args.repo)
|
| 220 |
+
from huggingface_hub import HfApi
|
| 221 |
+
api = HfApi()
|
| 222 |
+
api.upload_file(path_or_fileobj=build_readme(final).encode(), path_in_repo="README.md", repo_id=args.repo)
|
| 223 |
+
if os.path.exists(args.outjson):
|
| 224 |
+
api.upload_file(path_or_fileobj=open(args.outjson, "rb").read(), path_in_repo=os.path.basename(args.outjson), repo_id=args.repo)
|
| 225 |
+
print("PUSHED to", args.repo)
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def build_readme(final):
|
| 229 |
+
rows = "\n".join(f" - {c}: mAP@50 = **{v:.3f}**" for c, v in final["per_class_map_50"].items())
|
| 230 |
+
return f"""---
|
| 231 |
+
license: apache-2.0
|
| 232 |
+
tags:
|
| 233 |
+
- object-detection
|
| 234 |
+
- detr
|
| 235 |
+
pipeline_tag: object-detection
|
| 236 |
+
datasets:
|
| 237 |
+
- biglam/loc_beyond_words
|
| 238 |
+
metrics:
|
| 239 |
+
- mean_average_precision
|
| 240 |
+
---
|
| 241 |
+
|
| 242 |
+
# opencode-r1 — Object Detection on LOC Beyond Words
|
| 243 |
+
|
| 244 |
+
Fine-tuned **facebook/detr-resnet-50** (DETR, ResNet-50 backbone, **Apache-2.0**) on the
|
| 245 |
+
[`biglam/loc_beyond_words`](https://huggingface.co/datasets/biglam/loc_beyond_words)
|
| 246 |
+
dataset — a crowdsourced collection of bounding-box annotations over WWI-era newspaper
|
| 247 |
+
pages from the Library of Congress Chronicling America collection.
|
| 248 |
+
|
| 249 |
+
Fine-tuning was performed on a single NVIDIA T4 via Hugging Face Jobs (~under \$5 of compute).
|
| 250 |
+
|
| 251 |
+
## Classes (7)
|
| 252 |
+
|
| 253 |
+
{chr(10).join('- ' + c for c in CLASSES)}
|
| 254 |
+
|
| 255 |
+
## Validation results (COCO-style AP on 712 held-out images)
|
| 256 |
+
|
| 257 |
+
- **mAP@0.5:0.95** = `{final['eval_map']:.4f}`
|
| 258 |
+
- **mAP@0.5** = `{final['eval_map_50']:.4f}`
|
| 259 |
+
|
| 260 |
+
Per-class mAP@0.5:
|
| 261 |
+
|
| 262 |
+
{rows}
|
| 263 |
+
|
| 264 |
+
## Usage
|
| 265 |
+
|
| 266 |
+
```python
|
| 267 |
+
from transformers import AutoProcessor, DetrForObjectDetection
|
| 268 |
+
import torch
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
processor = AutoProcessor.from_pretrained("harness-race/opencode-r1")
|
| 272 |
+
model = DetrForObjectDetection.from_pretrained("harness-race/opencode-r1")
|
| 273 |
+
image = Image.open("page.jpg")
|
| 274 |
+
inputs = processor(images=image, return_tensors="pt")
|
| 275 |
+
outputs = model(**inputs)
|
| 276 |
+
results = processor.post_process_object_detection(
|
| 277 |
+
outputs, threshold=0.5, target_sizes=torch.tensor([image.size[::-1]]))[0]
|
| 278 |
+
```
|
| 279 |
+
|
| 280 |
+
## License & attribution
|
| 281 |
+
|
| 282 |
+
- Base model `facebook/detr-resnet-50`: **Apache-2.0**
|
| 283 |
+
- Dataset `biglam/loc_beyond_words`: **CC0-1.0** (public domain)
|
| 284 |
+
- This fine-tuned model: **Apache-2.0**
|
| 285 |
+
"""
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
if __name__ == "__main__":
|
| 289 |
+
main()
|