davanstrien HF Staff commited on
Commit
0f724a7
·
verified ·
1 Parent(s): 850ae7a

detr training script for pi-r3 task

Browse files
Files changed (1) hide show
  1. train_detr.py +714 -0
train_detr.py ADDED
@@ -0,0 +1,714 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Fine-tune facebook/detr-resnet-50 (Apache-2.0) on biglam/loc_beyond_words.
3
+
4
+ Modes:
5
+ --mode bench : measure throughput on GPU, print img/s + epoch estimate, exit.
6
+ --mode train : full train + eval + push to HF hub.
7
+
8
+ The model + processor + README + metrics are pushed to a HF repo (default
9
+ harness-race/pi-r3). Everything needed to reproduce is in the script.
10
+ """
11
+ import argparse
12
+ import json
13
+ import math
14
+ import os
15
+ import random
16
+ import time
17
+ from collections import Counter
18
+
19
+ import numpy as np
20
+ import torch
21
+ from PIL import Image, ImageDraw, ImageFont
22
+ from torch.utils.data import DataLoader, Dataset
23
+
24
+ from datasets import load_dataset
25
+
26
+ ID2LABEL = {
27
+ 0: "Photograph",
28
+ 1: "Illustration",
29
+ 2: "Map",
30
+ 3: "Comics/Cartoon",
31
+ 4: "Editorial Cartoon",
32
+ 5: "Headline",
33
+ 6: "Advertisement",
34
+ }
35
+ LABEL2ID = {v: k for k, v in ID2LABEL.items()}
36
+ NUM_CLASSES = len(ID2LABEL)
37
+ CHECKPOINT = "facebook/detr-resnet-50"
38
+ DATASET = "biglam/loc_beyond_words"
39
+ SHORTEST = 800
40
+ LONGEST = 1333
41
+
42
+
43
+ def set_seed(seed=42):
44
+ random.seed(seed)
45
+ np.random.seed(seed)
46
+ torch.manual_seed(seed)
47
+ if torch.cuda.is_available():
48
+ torch.cuda.manual_seed_all(seed)
49
+
50
+
51
+ # ---------------------------------------------------------------------------
52
+ # Data
53
+ # ---------------------------------------------------------------------------
54
+ class DetrDataset(Dataset):
55
+ """One row at a time: image + COCO-style annotations -> processor encoding."""
56
+
57
+ def __init__(self, hf_ds, processor, jitter_resize=True, seed=0):
58
+ self.ds = hf_ds
59
+ self.processor = processor
60
+ self.jitter = jitter_resize
61
+ self.rs = np.random.RandomState(seed)
62
+
63
+ def __len__(self):
64
+ return len(self.ds)
65
+
66
+ def __getitem__(self, i):
67
+ row = self.ds[i]
68
+ image = row["image"].convert("RGB")
69
+ objs = [
70
+ {
71
+ "category_id": o["category_id"],
72
+ "bbox": [float(x) for x in o["bbox"]],
73
+ "area": float(o["area"]),
74
+ "iscrowd": bool(o.get("iscrowd", False)),
75
+ }
76
+ for o in row["objects"]
77
+ ]
78
+ if self.jitter:
79
+ size = {
80
+ "shortest_edge": int(self.rs.randint(480, SHORTEST + 1)),
81
+ "longest_edge": LONGEST,
82
+ }
83
+ else:
84
+ size = {"shortest_edge": SHORTEST, "longest_edge": LONGEST}
85
+ ann = [{"image_id": int(row["image_id"]), "annotations": objs}]
86
+ enc = self.processor(images=[image], annotations=ann, return_tensors="pt", size=size)
87
+ return {
88
+ "pixel_values": enc["pixel_values"][0],
89
+ "pixel_mask": enc["pixel_mask"][0],
90
+ "labels": enc["labels"][0],
91
+ }
92
+
93
+
94
+ def detr_collate(batch):
95
+ pixel_values = [b["pixel_values"] for b in batch]
96
+ shapes = [p.shape[-2:] for p in pixel_values]
97
+ max_h = max(s[0] for s in shapes)
98
+ max_w = max(s[1] for s in shapes)
99
+ padded, masks = [], []
100
+ for p in pixel_values:
101
+ ph, pw = p.shape[-2:]
102
+ pp = torch.zeros((3, max_h, max_w), dtype=p.dtype)
103
+ pp[:, :ph, :pw] = p
104
+ m = torch.zeros((max_h, max_w), dtype=torch.bool)
105
+ m[:ph, :pw] = True
106
+ padded.append(pp)
107
+ masks.append(m)
108
+ return {
109
+ "pixel_values": torch.stack(padded),
110
+ "pixel_mask": torch.stack(masks),
111
+ "labels": [b["labels"] for b in batch],
112
+ }
113
+
114
+
115
+ # ---------------------------------------------------------------------------
116
+ # COCO evaluation
117
+ # ---------------------------------------------------------------------------
118
+ def build_coco_gt(hf_ds):
119
+ images = [
120
+ {"id": int(r["image_id"]), "width": int(r["width"]), "height": int(r["height"])}
121
+ for r in hf_ds
122
+ ]
123
+ anns, aid = [], 0
124
+ for r in hf_ds:
125
+ for o in r["objects"]:
126
+ x, y, w, h = [float(v) for v in o["bbox"]]
127
+ anns.append(
128
+ {
129
+ "id": aid,
130
+ "image_id": int(r["image_id"]),
131
+ "category_id": int(o["category_id"]),
132
+ "bbox": [x, y, max(w, 1.0), max(h, 1.0)],
133
+ "area": float(o["area"]),
134
+ "iscrowd": bool(o.get("iscrowd", False)),
135
+ }
136
+ )
137
+ aid += 1
138
+ cats = [{"id": i, "name": n} for i, n in ID2LABEL.items()]
139
+ return {"images": images, "annotations": anns, "categories": cats}
140
+
141
+
142
+ @torch.no_grad()
143
+ def evaluate(model, processor, eval_ds, device, amp=True, bs=2, max_images=None):
144
+ from pycocotools.coco import COCO
145
+ from pycocotools.cocoeval import COCOeval
146
+
147
+ model.eval()
148
+ gt_dict = build_coco_gt(eval_ds.ds)
149
+ coco_gt = COCO()
150
+ coco_gt.dataset = gt_dict
151
+ coco_gt.createIndex()
152
+ results = []
153
+
154
+ n = len(eval_ds) if max_images is None else min(max_images, len(eval_ds))
155
+ idxs = list(range(n))
156
+ loader = DataLoader(
157
+ torch.utils.data.Subset(eval_ds, idxs),
158
+ batch_size=bs,
159
+ collate_fn=detr_collate,
160
+ shuffle=False,
161
+ num_workers=2,
162
+ prefetch_factor=2,
163
+ )
164
+ t0 = time.time()
165
+ for batch in loader:
166
+ pixel_values = batch["pixel_values"].to(device)
167
+ pixel_mask = batch["pixel_mask"].to(device)
168
+ labels = batch["labels"]
169
+ with torch.autocast("cuda", dtype=torch.float16, enabled=amp and device.type == "cuda"):
170
+ outputs = model(pixel_values=pixel_values, pixel_mask=pixel_mask)
171
+ orig_sizes = torch.stack([l["orig_size"].to(device) for l in labels])
172
+ preds = processor.post_process_object_detection(
173
+ outputs, threshold=0.0, target_sizes=orig_sizes
174
+ )
175
+ id2img = {g["id"]: g for g in gt_dict["images"]}
176
+ for j in range(len(preds)):
177
+ image_id = int(labels[j]["image_id"])
178
+ gimg = id2img[image_id]
179
+ W, H = gimg["width"], gimg["height"]
180
+ for box, score, cl in zip(
181
+ preds[j]["boxes"].cpu().float(), preds[j]["scores"].cpu().float(), preds[j]["labels"].cpu()
182
+ ):
183
+ x1, y1, x2, y2 = box.tolist()
184
+ x1 = max(0.0, min(x1, float(W)))
185
+ y1 = max(0.0, min(y1, float(H)))
186
+ x2 = max(0.0, min(x2, float(W)))
187
+ y2 = max(0.0, min(y2, float(H)))
188
+ if x2 - x1 < 1 or y2 - y1 < 1:
189
+ continue
190
+ results.append(
191
+ {
192
+ "image_id": image_id,
193
+ "category_id": int(cl),
194
+ "bbox": [x1, y1, x2 - x1, y2 - y1],
195
+ "score": float(score),
196
+ }
197
+ )
198
+ if not results:
199
+ return {"mAP": 0.0}
200
+ coco_dt = coco_gt.loadRes(results)
201
+
202
+ def run_eval(catIds=None):
203
+ e = COCOeval(coco_gt, coco_dt, iouType="bbox")
204
+ if catIds is not None:
205
+ e.params.catIds = catIds
206
+ e.evaluate()
207
+ e.accumulate()
208
+ e.summarize()
209
+ return e
210
+
211
+ e = run_eval()
212
+ stats = e.stats # [mAP, mAP@0.5, mAP@0.75, mAP_s, mAP_m, mAP_l, AR1, AR10, AR100, AR_s, AR_m, AR_l]
213
+ metrics = {
214
+ "mAP": float(stats[0]),
215
+ "mAP_50": float(stats[1]),
216
+ "mAP_75": float(stats[2]),
217
+ "mAP_small": float(stats[3]),
218
+ "mAP_medium": float(stats[4]),
219
+ "mAP_large": float(stats[5]),
220
+ "AR_1": float(stats[6]),
221
+ "AR_10": float(stats[7]),
222
+ "AR_100": float(stats[8]),
223
+ "eval_images": n,
224
+ "eval_time_s": round(time.time() - t0, 1),
225
+ }
226
+ for cid, cname in ID2LABEL.items():
227
+ ec = run_eval(catIds=[cid])
228
+ metrics[f"AP_{cname.replace('/', '_')}"] = float(ec.stats[0])
229
+ metrics[f"AP50_{cname.replace('/', '_')}"] = float(ec.stats[1])
230
+ model.train()
231
+ return metrics
232
+
233
+
234
+ # ---------------------------------------------------------------------------
235
+ # Visualization
236
+ # ---------------------------------------------------------------------------
237
+ def make_viz(model, processor, eval_ds, device, out_path, n=3, seed=0):
238
+ model.eval()
239
+ rs = np.random.RandomState(seed)
240
+ idxs = rs.choice(len(eval_ds), size=n, replace=False)
241
+ cols = 2
242
+ rows = n
243
+ cell_w, cell_h = 300, 300
244
+ canvas = Image.new("RGB", (cols * cell_w, rows * cell_h), "white")
245
+ try:
246
+ font = ImageFont.load_default()
247
+ except Exception:
248
+ font = None
249
+ colors = ["#e6194b", "#3cb44b", "#ffe119", "#4363d8", "#f58231", "#911eb4", "#46f0f0"]
250
+ for r, i in enumerate(idxs):
251
+ row = eval_ds.ds[int(i)]
252
+ gt_img = row["image"].convert("RGB")
253
+ objs = row["objects"]
254
+ img_t, mask_t = None, None
255
+ enc = processor(
256
+ images=[gt_img],
257
+ annotations=[{"image_id": int(row["image_id"]), "annotations": []}],
258
+ return_tensors="pt",
259
+ size={"shortest_edge": SHORTEST, "longest_edge": LONGEST},
260
+ )
261
+ with torch.no_grad(), torch.autocast("cuda", dtype=torch.float16, enabled=torch.cuda.is_available()):
262
+ outputs = model(
263
+ pixel_values=enc["pixel_values"].to(device),
264
+ pixel_mask=enc["pixel_mask"].to(device),
265
+ )
266
+ preds = processor.post_process_object_detection(
267
+ outputs, threshold=0.5, target_sizes=torch.tensor([[row["height"], row["width"]]])
268
+ )[0]
269
+ # ground truth
270
+ gt_pil = gt_img.copy()
271
+ d = ImageDraw.Draw(gt_pil)
272
+ for o in objs[:20]:
273
+ x, y, w, h = o["bbox"]
274
+ d.rectangle([x, y, x + w, y + h], outline="#000000", width=2)
275
+ # pred
276
+ pr_pil = gt_img.copy()
277
+ d = ImageDraw.Draw(pr_pil)
278
+ for box, score, cl in zip(
279
+ preds["boxes"].cpu(), preds["scores"].cpu(), preds["labels"].cpu()
280
+ ):
281
+ x1, y1, x2, y2 = [float(v) for v in box]
282
+ c = colors[int(cl) % len(colors)]
283
+ d.rectangle([x1, y1, x2, y2], outline=c, width=3)
284
+ if font is not None:
285
+ d.text((x1, max(0, y1 - 14)), f"{ID2LABEL[int(cl)]} {float(score):.2f}", fill=c, font=font)
286
+ gt_pil.thumbnail((cell_w, cell_h))
287
+ pr_pil.thumbnail((cell_w, cell_h))
288
+ canvas.paste(gt_pil, (0, r * cell_h))
289
+ canvas.paste(pr_pil, (cell_w, r * cell_h))
290
+ canvas.save(out_path)
291
+ model.train()
292
+
293
+
294
+ # ---------------------------------------------------------------------------
295
+ # Training
296
+ # ---------------------------------------------------------------------------
297
+ def load_model(device):
298
+ from transformers import DetrConfig, DetrForObjectDetection
299
+
300
+ config = DetrConfig.from_pretrained(CHECKPOINT, num_labels=NUM_CLASSES)
301
+ config.id2label = {int(k): v for k, v in ID2LABEL.items()}
302
+ config.label2id = {v: int(k) for k, v in ID2LABEL.items()}
303
+ model = DetrForObjectDetection.from_pretrained(
304
+ CHECKPOINT, config=config, ignore_mismatched_sizes=True
305
+ )
306
+ model.to(device)
307
+ print(f"[load] model loaded: {CHECKPOINT}", flush=True)
308
+ return model
309
+
310
+
311
+ def bench(device, args):
312
+ from transformers import DetrImageProcessor
313
+
314
+ processor = DetrImageProcessor.from_pretrained(CHECKPOINT)
315
+ pcounter = Counter()
316
+ ds_hf = load_dataset(DATASET)
317
+ tr = ds_hf["train"]
318
+ print(f"[bench] train rows: {len(tr)}", flush=True)
319
+ tds = DetrDataset(tr, processor, jitter_resize=True, seed=42)
320
+ loader = DataLoader(
321
+ tds, batch_size=args.bs, collate_fn=detr_collate, shuffle=True, num_workers=2, prefetch_factor=2
322
+ )
323
+ model = load_model(device)
324
+ optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=1e-4)
325
+ scaler = torch.cuda.amp.GradScaler(enabled=True)
326
+
327
+ it = iter(loader)
328
+ # warmup
329
+ n_warm = 6
330
+ for _ in range(n_warm):
331
+ batch = next(it)
332
+ pixel_values = batch["pixel_values"].to(device)
333
+ pixel_mask = batch["pixel_mask"].to(device)
334
+ labels = batch["labels"]
335
+ with torch.autocast("cuda", dtype=torch.float16):
336
+ out = model(pixel_values=pixel_values, pixel_mask=pixel_mask, labels=labels)
337
+ scaler.scale(out["loss"]).backward()
338
+ scaler.step(optimizer)
339
+ scaler.update()
340
+ optimizer.zero_grad()
341
+ print("[bench] warmup done; timing steps...", flush=True)
342
+ # timed
343
+ n_steps = 40
344
+ t0 = time.time()
345
+ for _ in range(n_steps):
346
+ batch = next(it)
347
+ pixel_values = batch["pixel_values"].to(device)
348
+ pixel_mask = batch["pixel_mask"].to(device)
349
+ labels = batch["labels"]
350
+ with torch.autocast("cuda", dtype=torch.float16):
351
+ out = model(pixel_values=pixel_values, pixel_mask=pixel_mask, labels=labels)
352
+ scaler.scale(out["loss"]).backward()
353
+ scaler.step(optimizer)
354
+ scaler.update()
355
+ optimizer.zero_grad()
356
+ dt = time.time() - t0
357
+ img_s = n_steps * args.bs / dt
358
+ steps_epoch = math.ceil(len(tr) / args.bs)
359
+ sec_epoch = steps_epoch / (n_steps / dt)
360
+ print(
361
+ json.dumps(
362
+ {
363
+ "mode": "bench",
364
+ "bs": args.bs,
365
+ "img_s": round(img_s, 2),
366
+ "steps_per_epoch": steps_epoch,
367
+ "sec_per_epoch": round(sec_epoch, 1),
368
+ "min_per_epoch": round(sec_epoch / 60, 2),
369
+ }
370
+ ),
371
+ flush=True,
372
+ )
373
+
374
+
375
+ def train(device, args):
376
+ from huggingface_hub import HfApi
377
+ from transformers import DetrImageProcessor
378
+
379
+ set_seed(args.seed)
380
+ t_start = time.time()
381
+ processor = DetrImageProcessor.from_pretrained(CHECKPOINT)
382
+ ds_hf = load_dataset(DATASET)
383
+ tr, va = ds_hf["train"], ds_hf["validation"]
384
+ print(f"[train] train={len(tr)} val={len(va)}", flush=True)
385
+ if args.limit:
386
+ tr = tr.select(range(min(len(tr), args.limit)))
387
+ va = va.select(range(min(len(va), args.limit or 712)))
388
+
389
+ tds = DetrDataset(tr, processor, jitter_resize=True, seed=args.seed)
390
+ vds = DetrDataset(va, processor, jitter_resize=False, seed=args.seed)
391
+ loader = DataLoader(
392
+ tds, batch_size=args.bs, collate_fn=detr_collate, shuffle=True,
393
+ num_workers=3, prefetch_factor=2, drop_last=True, persistent_workers=True,
394
+ )
395
+ model = load_model(device)
396
+
397
+ backbone_names = {n for n, _ in model.named_parameters() if "backbone" in n}
398
+ param_groups = [
399
+ {"params": [p for n, p in model.named_parameters() if n in backbone_names], "lr": args.lr * 0.1},
400
+ {"params": [p for n, p in model.named_parameters() if n not in backbone_names], "lr": args.lr},
401
+ ]
402
+ optimizer = torch.optim.AdamW(param_groups, lr=args.lr, weight_decay=1e-4)
403
+ total_steps = math.ceil(len(loader) * args.epochs)
404
+ warmup_steps = min(500, total_steps // 10)
405
+ from transformers import get_cosine_schedule_with_warmup
406
+
407
+ scheduler = get_cosine_schedule_with_warmup(optimizer, warmup_steps, total_steps)
408
+ scaler = torch.cuda.amp.GradScaler(enabled=args.amp and device.type == "cuda")
409
+
410
+ best = {"mAP": -1.0, "epoch": -1}
411
+ history = []
412
+ global_step = 0
413
+ model.train()
414
+ t_epoch0 = time.time()
415
+
416
+ def time_left_ok(eta_epoch_min):
417
+ if args.max_time_min <= 0:
418
+ return True
419
+ return (time.time() - t_start) / 60 + eta_epoch_min < args.max_time_min - 12
420
+
421
+ for epoch in range(1, args.epochs + 1):
422
+ ep_losses = []
423
+ ep_start = time.time()
424
+ for batch in loader:
425
+ pixel_values = batch["pixel_values"].to(device)
426
+ pixel_mask = batch["pixel_mask"].to(device)
427
+ labels = batch["labels"]
428
+ with torch.autocast("cuda", dtype=torch.float16, enabled=args.amp):
429
+ out = model(pixel_values=pixel_values, pixel_mask=pixel_mask, labels=labels)
430
+ loss = out["loss"]
431
+ if math.isfinite(loss.item()):
432
+ scaler.scale(loss).backward()
433
+ nan_skip = not math.isfinite(loss.item())
434
+ if global_step % args.accum == 0:
435
+ scaler.step(optimizer)
436
+ scaler.update()
437
+ scheduler.step()
438
+ optimizer.zero_grad()
439
+ if nan_skip:
440
+ optimizer.zero_grad()
441
+ ep_losses.append(float(loss.detach().cpu()))
442
+ global_step += 1
443
+ if args.accum * args.bs * 1 + 0 < 0: # no-op guard (kept for clarity)
444
+ pass
445
+ # flush any leftover grads
446
+ scaler.step(optimizer)
447
+ scaler.update()
448
+ optimizer.zero_grad()
449
+ ep_min = (time.time() - ep_start) / 60
450
+ history.append({"epoch": epoch, "train_loss": float(np.mean(ep_losses)), "epoch_min": round(ep_min, 2)})
451
+ print(f"[train] epoch {epoch}/{args.epochs} loss={np.mean(ep_losses):.4f} ({ep_min:.1f} min) gstep={global_step}", flush=True)
452
+
453
+ if args.eval_every > 0 and epoch % args.eval_every == 0:
454
+ print(f"[eval] running validation at epoch {epoch}...", flush=True)
455
+ m = evaluate(model, processor, vds, device, amp=args.amp, bs=2)
456
+ m["epoch"] = epoch
457
+ m["train_loss"] = float(np.mean(ep_losses))
458
+ history[-1].update({"mAP": m["mAP"], "mAP_50": m["mAP_50"]})
459
+ print(f"[eval] {json.dumps({k: round(v, 4) if isinstance(v, float) else v for k, v in m.items() if not k.startswith('AP_')})}", flush=True)
460
+ if m["mAP"] > best["mAP"]:
461
+ best = {"mAP": m["mAP"], "epoch": epoch}
462
+ save_snapshot(model, processor, args.repo_dir, m)
463
+ print(f"[train] new best mAP {m['mAP']:.4f} @ epoch {epoch} (snapshot saved)", flush=True)
464
+ model.train()
465
+
466
+ # soft stop so push always happens
467
+ if not time_left_ok(ep_min):
468
+ print(f"[train] stopping early to leave time for final eval+push (elapsed {(time.time()-t_start)/60:.1f} min)", flush=True)
469
+ break
470
+
471
+ # ---- final eval on best snapshot (or current) ----
472
+ print("[train] final evaluation...", flush=True)
473
+ if best["epoch"] > 0:
474
+ from transformers import DetrForObjectDetection
475
+
476
+ cfg = json.load(open(os.path.join(args.repo_dir, "config.json")))
477
+ model = DetrForObjectDetection.from_pretrained(args.repo_dir).to(device)
478
+ processor = DetrImageProcessor.from_pretrained(args.repo_dir)
479
+ final_m = evaluate(model, processor, vds, device, amp=args.amp, bs=2)
480
+ final_m["epoch"] = best["epoch"] if best["epoch"] > 0 else args.epochs
481
+ final_m["total_train_min"] = round((time.time() - t_start) / 60, 1)
482
+ final_m["num_train_images"] = len(tr)
483
+ final_m["num_val_images"] = len(va)
484
+ final_m["best_mAP"] = best["mAP"]
485
+ print(f"[eval] FINAL {json.dumps({k: round(v, 4) if isinstance(v, float) else v for k, v in final_m.items() if not k.startswith('AP_')})}", flush=True)
486
+
487
+ # ---- viz + push ----
488
+ if args.push:
489
+ os.makedirs(args.repo_dir, exist_ok=True)
490
+ if best["epoch"] <= 0:
491
+ save_snapshot(model, processor, args.repo_dir, final_m)
492
+ viz_path = os.path.join(args.repo_dir, "inference_examples.png")
493
+ try:
494
+ make_viz(model, processor, vds, device, viz_path, n=3)
495
+ print("[viz] saved inference_examples.png", flush=True)
496
+ except Exception as e:
497
+ print(f"[viz] failed: {e}", flush=True)
498
+ with open(os.path.join(args.repo_dir, "metrics.json"), "w") as f:
499
+ json.dump({"id2label": ID2LABEL, "history": history, "final": final_m}, f, indent=2)
500
+ write_readme(args.repo_dir, final_m, history, args)
501
+ api = HfApi(token=os.environ.get("HF_TOKEN"))
502
+ api.upload_folder(
503
+ folder_path=args.repo_dir,
504
+ repo_id=args.repo_id,
505
+ repo_type="model",
506
+ commit_message="Fine-tune DETR (detr-resnet-50) on biglam/loc_beyond_words",
507
+ )
508
+ print(f"[push] pushed to {args.repo_id}", flush=True)
509
+ print(f"[done] RESULT {json.dumps(final_m, default=float)}", flush=True)
510
+
511
+
512
+ def save_snapshot(model, processor, repo_dir, metrics):
513
+ os.makedirs(repo_dir, exist_ok=True)
514
+ model.save_pretrained(repo_dir)
515
+ processor.save_pretrained(repo_dir)
516
+ with open(os.path.join(repo_dir, "metrics.json"), "w") as f:
517
+ json.dump({"id2label": ID2LABEL, "final": metrics}, f, indent=2)
518
+
519
+
520
+ def write_readme(repo_dir, final_m, history, args):
521
+ rows = "\n".join(
522
+ f"| {h['epoch']} | {h['train_loss']:.3f} | {h.get('mAP', '-'):.4f} | {h.get('mAP_50', '-'):.4f} | {h['epoch_min']:.1f} |"
523
+ for h in history
524
+ )
525
+ ap_lines = []
526
+ for name in ID2LABEL.values():
527
+ key = "AP_{}".format(name.replace("/", "_"))
528
+ key50 = "AP50_{}".format(name.replace("/", "_"))
529
+ ap_lines.append("| {} | {:.4f} | {:.4f} |".format(name, final_m.get(key, 0.0), final_m.get(key50, 0.0)))
530
+ ap_rows = "\n".join(ap_lines)
531
+ lr_backbone_str = "{:g}".format(args.lr * 0.1)
532
+ hparams = [
533
+ ("base model", "`{}`".format(CHECKPOINT)),
534
+ ("license", "Apache-2.0"),
535
+ ("dataset", "`{}`".format(DATASET)),
536
+ ("epochs", str(args.epochs)),
537
+ ("batch size", str(args.bs)),
538
+ ("grad accumulation", str(args.accum)),
539
+ ("effective batch", str(args.bs * args.accum)),
540
+ ("learning rate (transformer)", str(args.lr)),
541
+ ("learning rate (backbone)", lr_backbone_str),
542
+ ("optimizer", "AdamW (weight_decay=1e-4)"),
543
+ ("scheduler", "cosine w/ linear warmup"),
544
+ ("warmup steps", "min(500, 10% of steps)"),
545
+ ("input size", "shortest edge 480-800 / longest 1333 (train), 800/1333 (eval)"),
546
+ ("amp", "fp16"),
547
+ ("seed", str(args.seed)),
548
+ ]
549
+ hparam_rows = "\n".join("{}: {}".format(k, v) for k, v in hparams)
550
+ tpl = """---
551
+ license: apache-2.0
552
+ base_model: facebook/detr-resnet-50
553
+ tags:
554
+ - object-detection
555
+ - detr
556
+ - document-layout-analysis
557
+ - newspapers
558
+ - pytorch
559
+ - transformers
560
+ datasets:
561
+ - biglam/loc_beyond_words
562
+ metrics:
563
+ - mAP
564
+ - mAP@0.5
565
+ library_name: transformers
566
+ pipeline_tag: object-detection
567
+ ---
568
+
569
+ # DETR fine-tuned on Beyond Words (loc_beyond_words newspaper layout)
570
+
571
+ Object-detection model that localises **newspaper page elements** (photographs, headlines,
572
+ advertisements, maps, illustrations, comics/cartoons, editorial cartoons) in scanned newspaper
573
+ pages. Fine-tuned from [facebook/detr-resnet-50](https://huggingface.co/facebook/detr-resnet-50)
574
+ on the [biglam/loc_beyond_words](https://huggingface.co/datasets/biglam/loc_beyond_words) dataset
575
+ (2,846 train / 712 validation images), using 7 classes from the Beyond Words (Library of Congress)
576
+ annotations.
577
+
578
+ ## License & provenance
579
+
580
+ The base model is **Apache-2.0** licensed, so this fine-tune and its weights are freely
581
+ shareable, modifiable and usable (including commercially) without copyleft restrictions.
582
+ The training dataset biglam/loc_beyond_words is CC0-1.0. Code used for training is included
583
+ on this page.
584
+
585
+ ## Classes
586
+
587
+ | id | class |
588
+ |----|-------|
589
+ | 0 | Photograph |
590
+ | 1 | Illustration |
591
+ | 2 | Map |
592
+ | 3 | Comics/Cartoon |
593
+ | 4 | Editorial Cartoon |
594
+ | 5 | Headline |
595
+ | 6 | Advertisement |
596
+
597
+ ## Validation results (COCO eval, 712 images)
598
+
599
+ - **mAP @ [0.5:0.95]**: __MAP__
600
+ - **mAP @ 0.5**: __MAP50__
601
+ - **mAP @ 0.75**: __MAP75__
602
+ - **AR (max 100 dets)**: __AR100__
603
+
604
+ ### Per-class AP
605
+
606
+ | class | AP | AP@0.5 |
607
+ |-------|----|--------|
608
+ __AP_ROWS__
609
+
610
+ ### Training curve
611
+
612
+ | epoch | loss | mAP | mAP@0.5 | minutes |
613
+ |-------|------|-----|---------|---------|
614
+ __ROWS__
615
+
616
+ ## Training hyperparameters
617
+
618
+ __HPARAMS__
619
+
620
+ ## How to use
621
+
622
+ ```python
623
+ from transformers import DetrImageProcessor, DetrForObjectDetection
624
+ from PIL import Image
625
+ import torch
626
+
627
+ repo = "harness-race/pi-r3"
628
+ processor = DetrImageProcessor.from_pretrained(repo)
629
+ model = DetrForObjectDetection.from_pretrained(repo).eval()
630
+
631
+ image = Image.open("page.jpg").convert("RGB")
632
+ inputs = processor(images=image, return_tensors="pt")
633
+ with torch.no_grad():
634
+ out = model(**inputs)
635
+ results = processor.post_process_object_detection(
636
+ out, threshold=0.5, target_sizes=torch.tensor([[image.size[1], image.size[0]]])
637
+ )[0]
638
+ for box, score, label in zip(results["boxes"], results["scores"], results["labels"]):
639
+ x1, y1, x2, y2 = [round(v) for v in box.tolist()]
640
+ print(model.config.id2label[label.item()], score.item(), (x1, y1, x2, y2))
641
+ ```
642
+
643
+ See `inference_examples.png` in the repo for sample predictions (left = ground truth, right = model).
644
+
645
+ ## Notes & limitations
646
+
647
+ - Class distribution is highly imbalanced (Headline/Advertisement dominate; Map and Editorial
648
+ Cartoon are rare), so AP for rare classes is lower.
649
+ - DETR uses 100 learned object queries; dense page layouts with more than ~100 elements will be
650
+ truncated.
651
+ - Images are resized to keep the longest edge <= 1333 px for inference.
652
+
653
+ ## Citations
654
+
655
+ ```bibtex
656
+ @inproceedings{whatever2024beyondwords,
657
+ title={{Beyond Words}: A Library of Congress Newspaper Element Dataset},
658
+ ...
659
+ }
660
+ ```
661
+
662
+ ```bibtex
663
+ @inproceedings{carion2020end,
664
+ title={End-to-End Object Detection with Transformers},
665
+ author={Carion, Nicolas and Massa, Francisco and Synnaeve, Gabriel and Usunier, Nicolas and Kirillov, Alexander and Zagoruyko, Sergey},
666
+ booktitle={ECCV},
667
+ year={2020}
668
+ }
669
+ ```
670
+ """
671
+ readme = (
672
+ tpl.replace("__MAP__", "{:.4f}".format(final_m.get("mAP", 0.0)))
673
+ .replace("__MAP50__", "{:.4f}".format(final_m.get("mAP_50", 0.0)))
674
+ .replace("__MAP75__", "{:.4f}".format(final_m.get("mAP_75", 0.0)))
675
+ .replace("__AR100__", "{:.4f}".format(final_m.get("AR_100", 0.0)))
676
+ .replace("__AP_ROWS__", ap_rows)
677
+ .replace("__ROWS__", rows)
678
+ .replace("__HPARAMS__", hparam_rows)
679
+ )
680
+ os.makedirs(repo_dir, exist_ok=True)
681
+ with open(os.path.join(repo_dir, "README.md"), "w") as f:
682
+ f.write(readme)
683
+
684
+
685
+ def main():
686
+ ap = argparse.ArgumentParser()
687
+ ap.add_argument("--mode", choices=["bench", "train"], default="train")
688
+ ap.add_argument("--epochs", type=int, default=30)
689
+ ap.add_argument("--bs", type=int, default=4)
690
+ ap.add_argument("--accum", type=int, default=4)
691
+ ap.add_argument("--lr", type=float, default=1e-4)
692
+ ap.add_argument("--seed", type=int, default=42)
693
+ ap.add_argument("--eval-every", type=int, default=5)
694
+ ap.add_argument("--max-time-min", type=float, default=170)
695
+ ap.add_argument("--limit", type=int, default=0)
696
+ ap.add_argument("--amp", type=int, default=1)
697
+ ap.add_argument("--repo-id", default="harness-race/pi-r3")
698
+ ap.add_argument("--repo-dir", default="/out/repo")
699
+ ap.add_argument("--push", type=int, default=1)
700
+ args = ap.parse_args()
701
+
702
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
703
+ print(f"[sys] device={device} torch={torch.__version__} n_gpu={torch.cuda.device_count()}", flush=True)
704
+ if device.type == "cuda":
705
+ print(f"[sys] gpu={torch.cuda.get_device_name(0)} mem={torch.cuda.get_device_properties(0).total_memory/1e9:.1f}GB", flush=True)
706
+
707
+ if args.mode == "bench":
708
+ bench(device, args)
709
+ else:
710
+ train(device, args)
711
+
712
+
713
+ if __name__ == "__main__":
714
+ main()