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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# dependencies = [
|
| 3 |
+
# "torch",
|
| 4 |
+
# "torchvision",
|
| 5 |
+
# "datasets",
|
| 6 |
+
# "pycocotools",
|
| 7 |
+
# "Pillow",
|
| 8 |
+
# "numpy",
|
| 9 |
+
# "huggingface_hub",
|
| 10 |
+
# ]
|
| 11 |
+
# ///
|
| 12 |
+
"""Fine-tune torchvision Faster R-CNN (ResNet50-FPN, COCO-pretrained, BSD-3-Clause)
|
| 13 |
+
on biglam/loc_beyond_words and push to harness-race/opencode-r1.
|
| 14 |
+
"""
|
| 15 |
+
import argparse
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import random
|
| 19 |
+
import time
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torch
|
| 23 |
+
from PIL import Image
|
| 24 |
+
|
| 25 |
+
import torchvision
|
| 26 |
+
from torchvision.models.detection import fasterrcnn_resnet50_fpn, FasterRCNN_ResNet50_FPN_Weights
|
| 27 |
+
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
|
| 28 |
+
|
| 29 |
+
class_names = [
|
| 30 |
+
"Photograph", "Illustration", "Map", "Comics/Cartoon",
|
| 31 |
+
"Editorial Cartoon", "Headline", "Advertisement",
|
| 32 |
+
]
|
| 33 |
+
NUM_CLASSES = len(class_names) + 1 # + background for torchvision
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def set_seed(seed):
|
| 37 |
+
random.seed(seed)
|
| 38 |
+
np.random.seed(seed)
|
| 39 |
+
torch.manual_seed(seed)
|
| 40 |
+
torch.cuda.manual_seed_all(seed)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def process_row(row, max_dim):
|
| 44 |
+
img = row["image"]
|
| 45 |
+
if img.mode != "RGB":
|
| 46 |
+
img = img.convert("RGB")
|
| 47 |
+
w, h = img.size
|
| 48 |
+
scale = min(1.0, max_dim / max(h, w))
|
| 49 |
+
nw, nh = max(1, round(w * scale)), max(1, round(h * scale))
|
| 50 |
+
if (nw, nh) != (w, h):
|
| 51 |
+
img = img.resize((nw, nh), Image.BILINEAR)
|
| 52 |
+
arr = np.asarray(img, dtype=np.uint8) # H,W,C
|
| 53 |
+
|
| 54 |
+
boxes, labels, areas, ids = [], [], [], []
|
| 55 |
+
for obj in row["objects"]:
|
| 56 |
+
x, y, bw, bh = obj["bbox"]
|
| 57 |
+
x1, y1 = x * scale, y * scale
|
| 58 |
+
x2, y2 = (x + bw) * scale, (y + bh) * scale
|
| 59 |
+
if x2 <= x1 or y2 <= y1:
|
| 60 |
+
continue
|
| 61 |
+
boxes.append([x1, y1, x2, y2])
|
| 62 |
+
labels.append(int(obj["category_id"]))
|
| 63 |
+
areas.append((x2 - x1) * (y2 - y1))
|
| 64 |
+
ids.append(int(obj["id"]))
|
| 65 |
+
target = {
|
| 66 |
+
"boxes": torch.as_tensor(boxes, dtype=torch.float32) if boxes else torch.zeros((0, 4), dtype=torch.float32),
|
| 67 |
+
"labels": torch.as_tensor(labels, dtype=torch.int64) if labels else torch.zeros(0, dtype=torch.int64),
|
| 68 |
+
"image_id": torch.tensor([int(row["image_id"])]),
|
| 69 |
+
"area": torch.as_tensor(areas, dtype=torch.float32) if areas else torch.zeros(0, dtype=torch.float32),
|
| 70 |
+
"iscrowd": torch.zeros((len(boxes),), dtype=torch.int64),
|
| 71 |
+
}
|
| 72 |
+
return arr, target
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def collate(batch):
|
| 76 |
+
images, targets = [], []
|
| 77 |
+
for item in batch:
|
| 78 |
+
arr, target = item
|
| 79 |
+
t = torch.as_tensor(arr, dtype=torch.float32).permute(2, 0, 1) / 255.0
|
| 80 |
+
images.append(t)
|
| 81 |
+
targets.append(target)
|
| 82 |
+
return images, targets
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def train_one_epoch(model, optimizer, loader, device, epoch, log_every=25):
|
| 86 |
+
model.train()
|
| 87 |
+
tot, cnt = 0.0, 0
|
| 88 |
+
t0 = time.time()
|
| 89 |
+
for i, (images, targets) in enumerate(loader):
|
| 90 |
+
images = [im.to(device) for im in images]
|
| 91 |
+
targets = [{k: (v.to(device) if k != "image_id" else v) for k, v in t.items()} for t in targets]
|
| 92 |
+
loss_dict = model(images, targets)
|
| 93 |
+
loss = sum(v for v in loss_dict.values())
|
| 94 |
+
optimizer.zero_grad()
|
| 95 |
+
loss.backward()
|
| 96 |
+
optimizer.step()
|
| 97 |
+
tot += loss.item()
|
| 98 |
+
cnt += 1
|
| 99 |
+
if i % log_every == 0:
|
| 100 |
+
names = {k: round(float(v.item()), 3) for k, v in loss_dict.items()}
|
| 101 |
+
print(f"[epoch {epoch}] step {i}/{len(loader)} loss={loss.item():.4f} {names} "
|
| 102 |
+
f"elapsed={time.time()-t0:.0f}s", flush=True)
|
| 103 |
+
return tot / max(cnt, 1)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
@torch.no_grad()
|
| 107 |
+
def evaluate(model, loader, device, images_per_run=0):
|
| 108 |
+
model.eval()
|
| 109 |
+
preds = []
|
| 110 |
+
for images, targets in loader:
|
| 111 |
+
images = [im.to(device) for im in images]
|
| 112 |
+
out = model(images)
|
| 113 |
+
for img_id, t, dets in zip([int(t["image_id"][0]) for t in targets], targets, out):
|
| 114 |
+
boxes = dets["boxes"].cpu().numpy()
|
| 115 |
+
scores = dets["scores"].cpu().numpy()
|
| 116 |
+
labels = dets["labels"].cpu().numpy()
|
| 117 |
+
for box, sc, lab in zip(boxes, scores, labels):
|
| 118 |
+
if sc < 0.5:
|
| 119 |
+
continue
|
| 120 |
+
x1, y1, x2, y2 = box
|
| 121 |
+
preds.append({
|
| 122 |
+
"image_id": img_id,
|
| 123 |
+
"category_id": int(lab),
|
| 124 |
+
"bbox": [float(x1), float(y1), float(x2 - x1), float(y2 - y1)],
|
| 125 |
+
"score": float(sc),
|
| 126 |
+
})
|
| 127 |
+
return preds
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def build_gt(items):
|
| 131 |
+
anns, img_infos = [], {}
|
| 132 |
+
for arr, target in items:
|
| 133 |
+
iid = int(target["image_id"][0])
|
| 134 |
+
img_infos[iid] = {"id": iid, "width": arr.shape[1], "height": arr.shape[0]}
|
| 135 |
+
for bx, lab, ar in zip(target["boxes"], target["labels"], target["area"]):
|
| 136 |
+
x1, y1, x2, y2 = bx.tolist()
|
| 137 |
+
anns.append({
|
| 138 |
+
"id": len(anns) + 1, "image_id": iid, "category_id": int(lab),
|
| 139 |
+
"bbox": [x1, y1, max(x2 - x1, 1), max(y2 - y1, 1)],
|
| 140 |
+
"area": float(ar), "iscrowd": 0,
|
| 141 |
+
})
|
| 142 |
+
gt = {"images": list(img_infos.values()), "annotations": anns,
|
| 143 |
+
"categories": [{"id": i, "name": n} for i, n in enumerate(class_names)]}
|
| 144 |
+
return gt
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def coco_eval(gt, preds):
|
| 148 |
+
from pycocotools.coco import COCO
|
| 149 |
+
from pycocotools.cocoeval import COCOeval
|
| 150 |
+
coco_gt = COCO()
|
| 151 |
+
coco_gt.dataset = gt
|
| 152 |
+
coco_gt.createIndex()
|
| 153 |
+
coco_dt = coco_gt.loadRes(preds)
|
| 154 |
+
ev = COCOeval(coco_gt, coco_dt, "bbox")
|
| 155 |
+
ev.evaluate()
|
| 156 |
+
ev.accumulate()
|
| 157 |
+
ev.summarize()
|
| 158 |
+
stats = ev.stats # [mAP .5:.95, mAP50, mAP75, mAP small, med, large, AR...]
|
| 159 |
+
out = {
|
| 160 |
+
"mAP_050_095": float(stats[0]),
|
| 161 |
+
"mAP_050": float(stats[1]),
|
| 162 |
+
"mAP_075": float(stats[2]),
|
| 163 |
+
}
|
| 164 |
+
print(json.dumps(out), flush=True)
|
| 165 |
+
return out
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def main():
|
| 169 |
+
ap = argparse.ArgumentParser()
|
| 170 |
+
ap.add_argument("--epochs", type=int, default=12)
|
| 171 |
+
ap.add_argument("--batch", type=int, default=8)
|
| 172 |
+
ap.add_argument("--max-dim", type=int, default=520)
|
| 173 |
+
ap.add_argument("--lr", type=float, default=2e-3)
|
| 174 |
+
ap.add_argument("--base-lr", type=float, default=2e-4)
|
| 175 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 176 |
+
ap.add_argument("--push", default="1")
|
| 177 |
+
args = ap.parse_args()
|
| 178 |
+
|
| 179 |
+
set_seed(args.seed)
|
| 180 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 181 |
+
print("device:", device, torch.cuda.get_device_name(0) if torch.cuda.is_available() else "", flush=True)
|
| 182 |
+
|
| 183 |
+
from datasets import load_dataset
|
| 184 |
+
from torch.utils.data import DataLoader
|
| 185 |
+
|
| 186 |
+
print("loading dataset ...", flush=True)
|
| 187 |
+
ds = load_dataset("biglam/loc_beyond_words")
|
| 188 |
+
train_src = ds["train"]
|
| 189 |
+
val_src = ds["validation"]
|
| 190 |
+
print("train rows:", len(train_src), "val rows:", len(val_src), flush=True)
|
| 191 |
+
|
| 192 |
+
print("preprocessing ...", flush=True)
|
| 193 |
+
t0 = time.time()
|
| 194 |
+
train_items = [process_row(r, args.max_dim) for r in train_src]
|
| 195 |
+
val_items = [process_row(r, args.max_dim) for r in val_src]
|
| 196 |
+
print(f"preprocess done in {time.time()-t0:.0f}s", flush=True)
|
| 197 |
+
gt = build_gt(val_items)
|
| 198 |
+
|
| 199 |
+
from torch.utils.data import Dataset
|
| 200 |
+
|
| 201 |
+
class Wrap(Dataset):
|
| 202 |
+
def __init__(self, items):
|
| 203 |
+
self.items = items
|
| 204 |
+
|
| 205 |
+
def __len__(self):
|
| 206 |
+
return len(self.items)
|
| 207 |
+
|
| 208 |
+
def __getitem__(self, i):
|
| 209 |
+
return self.items[i]
|
| 210 |
+
|
| 211 |
+
train_loader = DataLoader(Wrap(train_items), batch_size=args.batch, shuffle=True,
|
| 212 |
+
num_workers=4, collate_fn=collate, drop_last=False)
|
| 213 |
+
val_loader = DataLoader(Wrap(val_items), batch_size=4, shuffle=False,
|
| 214 |
+
num_workers=4, collate_fn=collate)
|
| 215 |
+
|
| 216 |
+
model = fasterrcnn_resnet50_fpn(weights=FasterRCNN_ResNet50_FPN_Weights.COCO_V1)
|
| 217 |
+
in_features = model.roi_heads.box_predictor.cls_score.in_features
|
| 218 |
+
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, NUM_CLASSES)
|
| 219 |
+
model.transform.min_size = (args.max_dim,)
|
| 220 |
+
model.transform.max_size = int(args.max_dim * 1.5)
|
| 221 |
+
model.to(device)
|
| 222 |
+
|
| 223 |
+
params = [
|
| 224 |
+
{"params": [p for n, p in model.backbone.named_parameters() if p.requires_grad],
|
| 225 |
+
"lr": args.base_lr},
|
| 226 |
+
{"params": [p for n, p in model.named_parameters()
|
| 227 |
+
if not n.startswith("backbone") and p.requires_grad],
|
| 228 |
+
"lr": args.lr},
|
| 229 |
+
]
|
| 230 |
+
optimizer = torch.optim.SGD(params, momentum=0.9, weight_decay=1e-4)
|
| 231 |
+
lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=8, gamma=0.3)
|
| 232 |
+
|
| 233 |
+
best = -1.0
|
| 234 |
+
for epoch in range(1, args.epochs + 1):
|
| 235 |
+
avg = train_one_epoch(model, optimizer, train_loader, device, epoch)
|
| 236 |
+
lr_scheduler.step()
|
| 237 |
+
print(f"=== epoch {epoch} done, avg_train_loss={avg:.4f}, lr={optimizer.param_groups[-1]['lr']:.2e} ===", flush=True)
|
| 238 |
+
if epoch % 4 == 0 or epoch == args.epochs:
|
| 239 |
+
preds = evaluate(model, val_loader, device)
|
| 240 |
+
results = coco_eval(gt, preds)
|
| 241 |
+
if epoch == args.epochs or results["mAP_050_095"] > best:
|
| 242 |
+
best = results["mAP_050_095"]
|
| 243 |
+
os.makedirs("output", exist_ok=True)
|
| 244 |
+
torch.save(model.state_dict(), "output/model.pth")
|
| 245 |
+
torch.save(model, "output/full_model.pth")
|
| 246 |
+
with open("output/results.json", "w") as f:
|
| 247 |
+
json.dump(results, f)
|
| 248 |
+
with open("output/args.json", "w") as f:
|
| 249 |
+
json.dump(vars(args), f)
|
| 250 |
+
with open("output/class_names.json", "w") as f:
|
| 251 |
+
json.dump(class_names, f)
|
| 252 |
+
print(f"[saved checkpoint] mAP={results['mAP_050_095']:.4f}", flush=True)
|
| 253 |
+
|
| 254 |
+
print("training complete.", flush=True)
|
| 255 |
+
if args.push == "1" and os.path.exists("output/results.json"):
|
| 256 |
+
push_model(args, "output")
|
| 257 |
+
else:
|
| 258 |
+
print("skipping push.", flush=True)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def push_model(args, out_dir):
|
| 262 |
+
from huggingface_hub import HfApi, upload_folder
|
| 263 |
+
import shutil
|
| 264 |
+
|
| 265 |
+
results = json.load(open(os.path.join(out_dir, "results.json")))
|
| 266 |
+
params = json.load(open(os.path.join(out_dir, "args.json")))
|
| 267 |
+
|
| 268 |
+
repo_id = "harness-race/opencode-r1"
|
| 269 |
+
token = os.environ.get("HF_TOKEN")
|
| 270 |
+
api = HfApi(token=token)
|
| 271 |
+
api.create_repo(repo_id, repo_type="model", exist_ok=True)
|
| 272 |
+
# put README / metadata inside out_dir (upload_folder pushes everything there)
|
| 273 |
+
readme = f"""---
|
| 274 |
+
license: bsd-3-clause
|
| 275 |
+
language:
|
| 276 |
+
- en
|
| 277 |
+
tags:
|
| 278 |
+
- object-detection
|
| 279 |
+
- faster-rcnn
|
| 280 |
+
- resnet50
|
| 281 |
+
- document-layout
|
| 282 |
+
- historical-newspapers
|
| 283 |
+
pipeline_tag: object-detection
|
| 284 |
+
metrics:
|
| 285 |
+
- {float(results['mAP_050_095']):.4f}
|
| 286 |
+
widget:
|
| 287 |
+
- src: https://datasets-server.huggingface.co/cached-assets/biglam/loc_beyond_words/--/6c7f5fb3c60f02d9fe925cfc14aa7008f6c89099/--/default/train/0/image/image.jpg
|
| 288 |
+
---
|
| 289 |
+
|
| 290 |
+
# opencode-r1
|
| 291 |
+
|
| 292 |
+
Object detection model fine-tuned from **torchvision Faster R-CNN (ResNet-50-FPN)**
|
| 293 |
+
pre-trained on COCO (base model license: BSD-3-Clause, open and shareable) on the
|
| 294 |
+
[`biglam/loc_beyond_words`](https://huggingface.co/datasets/biglam/loc_beyond_words) dataset
|
| 295 |
+
(Library of Congress "Beyond Words", data license CC0-1.0).
|
| 296 |
+
|
| 297 |
+
## Classes (7) + background
|
| 298 |
+
|
| 299 |
+
{", ".join(class_names)}
|
| 300 |
+
|
| 301 |
+
## Validation results (COCO-style, biglam/loc_beyond_words validation set)
|
| 302 |
+
|
| 303 |
+
| Metric | Value |
|
| 304 |
+
|---|---|
|
| 305 |
+
| mAP @[IoU=0.50:0.95] | {results['mAP_050_095']:.4f} |
|
| 306 |
+
| mAP @ IoU=0.50 | {results['mAP_050']:.4f} |
|
| 307 |
+
| mAP @ IoU=0.75 | {results['mAP_075']:.4f} |
|
| 308 |
+
|
| 309 |
+
## Training
|
| 310 |
+
|
| 311 |
+
| Setting | Value |
|
| 312 |
+
|---|---|
|
| 313 |
+
| Base model | Faster R-CNN ResNet50-FPN (COCO, BSD-3-Clause) |
|
| 314 |
+
| Epochs | {params['epochs']} |
|
| 315 |
+
| Batch size | {params['batch']} |
|
| 316 |
+
| Max image dim | {params['max_dim']} |
|
| 317 |
+
| Optimizer | SGD (momentum 0.9), StepLR x0.3/8 epochs |
|
| 318 |
+
| Head LR / Backbone LR | {params['lr']} / {params['base_lr']} |
|
| 319 |
+
| Hardware | NVIDIA GPU (Hugging Face jobs) |
|
| 320 |
+
|
| 321 |
+
Images are downscaled so the largest dimension is {params['max_dim']}px (aspect preserved);
|
| 322 |
+
boxes scaled accordingly. Predictions below score 0.5 are discarded.
|
| 323 |
+
|
| 324 |
+
## To load and run
|
| 325 |
+
|
| 326 |
+
```python
|
| 327 |
+
import torch
|
| 328 |
+
from torchvision.models.detection import fasterrcnn_resnet50_fpn
|
| 329 |
+
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
|
| 330 |
+
from huggingface_hub import hf_hub_download
|
| 331 |
+
from PIL import Image
|
| 332 |
+
import numpy as np
|
| 333 |
+
|
| 334 |
+
state = torch.load(hf_hub_download("harness-race/opencode-r1", "model.pth"),
|
| 335 |
+
map_location="cpu")
|
| 336 |
+
model = fasterrcnn_resnet50_fpn(weights=None)
|
| 337 |
+
in_features = model.roi_heads.box_predictor.cls_score.in_features
|
| 338 |
+
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, 1 + 7) # 7 + background
|
| 339 |
+
model.load_state_dict(state)
|
| 340 |
+
model.eval()
|
| 341 |
+
|
| 342 |
+
img = Image.open("page.jpg").convert("RGB")
|
| 343 |
+
# resize to max-dim {params['max_dim']} like training, then:
|
| 344 |
+
x = torch.as_tensor(np.asarray(img), dtype=torch.float32).permute(2, 0, 1) / 255.0
|
| 345 |
+
with torch.no_grad():
|
| 346 |
+
dets = model([x])[0]
|
| 347 |
+
```
|
| 348 |
+
"""
|
| 349 |
+
with open(os.path.join(out_dir, "README.md"), "w") as f:
|
| 350 |
+
f.write(readme)
|
| 351 |
+
|
| 352 |
+
upload_folder(
|
| 353 |
+
repo_id=repo_id,
|
| 354 |
+
folder_path=out_dir,
|
| 355 |
+
repo_type="model",
|
| 356 |
+
token=token,
|
| 357 |
+
commit_message="Fine-tuned Faster R-CNN ResNet50-FPN on loc_beyond_words",
|
| 358 |
+
)
|
| 359 |
+
print(f"pushed model to {repo_id}", flush=True)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
if __name__ == "__main__":
|
| 363 |
+
main()
|