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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# /// script
|
| 3 |
+
# requires-python = ">=3.11"
|
| 4 |
+
# dependencies = [
|
| 5 |
+
# "torch",
|
| 6 |
+
# "transformers>=4.45",
|
| 7 |
+
# "datasets",
|
| 8 |
+
# "accelerate",
|
| 9 |
+
# "albumentations>=1.4.16",
|
| 10 |
+
# "torchmetrics",
|
| 11 |
+
# "pycocotools",
|
| 12 |
+
# "Pillow",
|
| 13 |
+
# "numpy",
|
| 14 |
+
# ]
|
| 15 |
+
# ///
|
| 16 |
+
import os
|
| 17 |
+
import sys
|
| 18 |
+
import logging
|
| 19 |
+
import json
|
| 20 |
+
from functools import partial
|
| 21 |
+
from collections import defaultdict
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
import torch
|
| 25 |
+
from datasets import load_dataset
|
| 26 |
+
|
| 27 |
+
import transformers
|
| 28 |
+
from transformers import (
|
| 29 |
+
AutoConfig,
|
| 30 |
+
AutoImageProcessor,
|
| 31 |
+
AutoModelForObjectDetection,
|
| 32 |
+
Trainer,
|
| 33 |
+
TrainingArguments,
|
| 34 |
+
)
|
| 35 |
+
from transformers.image_processing_utils import BatchFeature
|
| 36 |
+
from transformers.image_transforms import center_to_corners_format
|
| 37 |
+
from transformers.trainer import EvalPrediction
|
| 38 |
+
|
| 39 |
+
logger = logging.getLogger(__name__)
|
| 40 |
+
logging.basicConfig(format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 41 |
+
datefmt="%m/%d/%Y %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout)])
|
| 42 |
+
logger.setLevel(logging.INFO)
|
| 43 |
+
transformers.utils.logging.set_verbosity_info()
|
| 44 |
+
|
| 45 |
+
MODEL = "PekingU/rtdetr_r50vd"
|
| 46 |
+
DATASET = "biglam/loc_beyond_words"
|
| 47 |
+
SQUARE = int(os.environ.get("SQUARE", "800"))
|
| 48 |
+
RARE_BOOST = {1: 3, 2: 4, 3: 3, 4: 4} # Illustration, Map, Comics, EditorialCartoon
|
| 49 |
+
|
| 50 |
+
import albumentations as A
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class ModelOutput:
|
| 54 |
+
def __init__(self, logits, pred_boxes):
|
| 55 |
+
self.logits = logits
|
| 56 |
+
self.pred_boxes = pred_boxes
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def format_image_annotations_as_coco(image_id, categories, areas, bboxes):
|
| 60 |
+
annotations = []
|
| 61 |
+
for category, area, bbox in zip(categories, areas, bboxes):
|
| 62 |
+
annotations.append({
|
| 63 |
+
"image_id": image_id, "category_id": category, "iscrowd": 0,
|
| 64 |
+
"area": area, "bbox": list(bbox),
|
| 65 |
+
})
|
| 66 |
+
return {"image_id": image_id, "annotations": annotations}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def convert_bbox_yolo_to_pascal(boxes, image_size):
|
| 70 |
+
boxes = center_to_corners_format(boxes)
|
| 71 |
+
height, width = image_size
|
| 72 |
+
boxes = boxes * torch.tensor([[width, height, width, height]])
|
| 73 |
+
return boxes
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def augment_and_transform_batch(examples, transform, image_processor, return_pixel_mask=False):
|
| 77 |
+
images, annotations = [], []
|
| 78 |
+
for image_id, image, objects in zip(examples["image_id"], examples["image"], examples["objects"]):
|
| 79 |
+
image = np.array(image.convert("RGB"))
|
| 80 |
+
if isinstance(objects, dict):
|
| 81 |
+
bboxes, categories, areas = objects["bbox"], objects["category"], objects["area"]
|
| 82 |
+
else:
|
| 83 |
+
bboxes = [o["bbox"] for o in objects]
|
| 84 |
+
categories = [o["category_id"] for o in objects]
|
| 85 |
+
areas = [o["area"] for o in objects]
|
| 86 |
+
output = transform(image=image, bboxes=bboxes, category=categories)
|
| 87 |
+
images.append(output["image"])
|
| 88 |
+
annotations.append(format_image_annotations_as_coco(
|
| 89 |
+
image_id, output["category"], areas, output["bboxes"]))
|
| 90 |
+
result = image_processor(images=images, annotations=annotations, return_tensors="pt")
|
| 91 |
+
if not return_pixel_mask:
|
| 92 |
+
result.pop("pixel_mask", None)
|
| 93 |
+
return result
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def collate_fn(batch):
|
| 97 |
+
data = {
|
| 98 |
+
"pixel_values": torch.stack([x["pixel_values"] for x in batch]),
|
| 99 |
+
"labels": [x["labels"] for x in batch],
|
| 100 |
+
}
|
| 101 |
+
if "pixel_mask" in batch[0]:
|
| 102 |
+
data["pixel_mask"] = torch.stack([x["pixel_mask"] for x in batch])
|
| 103 |
+
return data
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def evaluate_model(model, image_processor, ds, device, batch_size=4):
|
| 107 |
+
from torchmetrics.detection.mean_ap import MeanAveragePrecision
|
| 108 |
+
metric = MeanAveragePrecision(box_format="xyxy", class_metrics=True)
|
| 109 |
+
N = len(ds)
|
| 110 |
+
for start in range(0, N, batch_size):
|
| 111 |
+
end = min(start + batch_size, N)
|
| 112 |
+
chunk = ds[start:end]
|
| 113 |
+
images, anns, origsizes = [], [], []
|
| 114 |
+
imgouts = chunk["objects"]
|
| 115 |
+
for k in range(end - start):
|
| 116 |
+
im = chunk["image"][k].convert("RGB")
|
| 117 |
+
origsizes.append((im.height, im.width))
|
| 118 |
+
objects = imgouts[k]
|
| 119 |
+
if isinstance(objects, dict):
|
| 120 |
+
bboxes, categories, areas = objects["bbox"], objects["category"], objects["area"]
|
| 121 |
+
else:
|
| 122 |
+
bboxes = [o["bbox"] for o in objects]
|
| 123 |
+
categories = [o["category_id"] for o in objects]
|
| 124 |
+
areas = [o["area"] for o in objects]
|
| 125 |
+
images.append(np.array(im))
|
| 126 |
+
anns.append(format_image_annotations_as_coco(
|
| 127 |
+
chunk["image_id"][k], categories, areas, bboxes))
|
| 128 |
+
inputs = image_processor(images=images, annotations=anns, return_tensors="pt").to(device)
|
| 129 |
+
with torch.no_grad():
|
| 130 |
+
outputs = model(pixel_values=inputs["pixel_values"],
|
| 131 |
+
pixel_mask=inputs.get("pixel_mask", None))
|
| 132 |
+
preds = image_processor.post_process_object_detection(
|
| 133 |
+
ModelOutput(logits=outputs.logits, pred_boxes=outputs.pred_boxes),
|
| 134 |
+
threshold=0.5, target_sizes=torch.tensor(origsizes, device=device),
|
| 135 |
+
)
|
| 136 |
+
for k in range(end - start):
|
| 137 |
+
lab = inputs["labels"][k]
|
| 138 |
+
tboxes = convert_bbox_yolo_to_pascal(torch.tensor(lab["boxes"]), lab["orig_size"])
|
| 139 |
+
metric.update(
|
| 140 |
+
[{"boxes": preds[k]["boxes"], "scores": preds[k]["scores"],
|
| 141 |
+
"labels": preds[k]["labels"]}],
|
| 142 |
+
[{"boxes": tboxes, "labels": torch.tensor(lab["class_labels"]).reshape(-1)}],
|
| 143 |
+
)
|
| 144 |
+
results = metric.compute()
|
| 145 |
+
out = {"map_50_95": round(results["map"].item(), 4),
|
| 146 |
+
"map_50": round(results["map_50"].item(), 4),
|
| 147 |
+
"map_75": round(results["map_75"].item(), 4),
|
| 148 |
+
"mar_100": round(results["mar_100"].item(), 4)}
|
| 149 |
+
if "classes" in results:
|
| 150 |
+
cls = results["classes"]
|
| 151 |
+
mpc = results["map_per_class"]
|
| 152 |
+
for c_id, m in zip(cls, mpc):
|
| 153 |
+
out[f"map_{c_id.item()}"] = round(m.item(), 4)
|
| 154 |
+
return out
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def oversample(dataset, boost, seed=42):
|
| 158 |
+
rng = np.random.default_rng(seed)
|
| 159 |
+
weights = []
|
| 160 |
+
for i in range(len(dataset)):
|
| 161 |
+
objs = dataset[i]["objects"]
|
| 162 |
+
if isinstance(objs, dict):
|
| 163 |
+
cats = objs["category"]
|
| 164 |
+
else:
|
| 165 |
+
cats = [o["category_id"] for o in objs]
|
| 166 |
+
w = 1
|
| 167 |
+
for c in set(int(c) for c in cats):
|
| 168 |
+
w = max(w, 1 + boost.get(int(c), 0))
|
| 169 |
+
weights.append(w)
|
| 170 |
+
weights = np.array(weights, dtype=float)
|
| 171 |
+
n = len(weights)
|
| 172 |
+
pick = rng.choice(n, size=n, replace=True, p=weights / weights.sum())
|
| 173 |
+
return dataset.select(pick.tolist())
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def main():
|
| 177 |
+
do_push = os.environ.get("PUSH", "1") == "1"
|
| 178 |
+
epochs = int(os.environ.get("EPOCHS", "3"))
|
| 179 |
+
bs = int(os.environ.get("BATCH", "4"))
|
| 180 |
+
grad_acc = int(os.environ.get("GRAD_ACC", "2"))
|
| 181 |
+
max_train = int(os.environ.get("MAX_TRAIN", "0")) or None
|
| 182 |
+
max_eval = int(os.environ.get("MAX_EVAL", "0")) or None
|
| 183 |
+
|
| 184 |
+
dataset = load_dataset(DATASET)
|
| 185 |
+
feat = dataset["train"].features["objects"]
|
| 186 |
+
inner = feat if isinstance(feat, dict) else feat.feature
|
| 187 |
+
cat_feat = inner["category_id"]
|
| 188 |
+
categories = cat_feat.names if hasattr(cat_feat, "names") else list(range(cat_feat.num_classes))
|
| 189 |
+
id2label = dict(enumerate(categories))
|
| 190 |
+
label2id = {v: k for k, v in id2label.items()}
|
| 191 |
+
logger.info(f"Cats: {categories}")
|
| 192 |
+
|
| 193 |
+
if max_train:
|
| 194 |
+
dataset["train"] = dataset["train"].select(range(min(max_train, len(dataset["train"]))))
|
| 195 |
+
if max_eval:
|
| 196 |
+
dataset["validation"] = dataset["validation"].select(range(min(max_eval, len(dataset["validation"]))))
|
| 197 |
+
|
| 198 |
+
config = AutoConfig.from_pretrained(MODEL, **{"label2id": label2id, "id2label": id2label})
|
| 199 |
+
model = AutoModelForObjectDetection.from_pretrained(MODEL, config=config, ignore_mismatched_sizes=True)
|
| 200 |
+
image_processor = AutoImageProcessor.from_pretrained(
|
| 201 |
+
MODEL,
|
| 202 |
+
do_resize=True,
|
| 203 |
+
size={"max_height": SQUARE, "max_width": SQUARE},
|
| 204 |
+
do_pad=True,
|
| 205 |
+
pad_size={"height": SQUARE, "width": SQUARE},
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
max_size = SQUARE
|
| 209 |
+
train_transforms = A.Compose(
|
| 210 |
+
[
|
| 211 |
+
A.Compose(
|
| 212 |
+
[A.SmallestMaxSize(max_size=max_size, p=1.0),
|
| 213 |
+
A.RandomSizedBBoxSafeCrop(height=max_size, width=max_size, p=1.0)],
|
| 214 |
+
p=0.2,
|
| 215 |
+
),
|
| 216 |
+
A.OneOf([A.Blur(blur_limit=7, p=0.5), A.MotionBlur(blur_limit=7, p=0.5)], p=0.1),
|
| 217 |
+
A.Perspective(p=0.1),
|
| 218 |
+
A.HorizontalFlip(p=0.5),
|
| 219 |
+
A.RandomBrightnessContrast(p=0.3),
|
| 220 |
+
],
|
| 221 |
+
bbox_params=A.BboxParams(format="coco", label_fields=["category"], clip=True, min_area=25),
|
| 222 |
+
)
|
| 223 |
+
validation_transform = A.Compose(
|
| 224 |
+
[A.NoOp()], bbox_params=A.BboxParams(format="coco", label_fields=["category"], clip=True)
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
train_transform_batch = partial(augment_and_transform_batch,
|
| 228 |
+
transform=train_transforms, image_processor=image_processor)
|
| 229 |
+
val_transform_batch = partial(augment_and_transform_batch,
|
| 230 |
+
transform=validation_transform, image_processor=image_processor)
|
| 231 |
+
|
| 232 |
+
train_ds = dataset["train"]
|
| 233 |
+
if not max_train:
|
| 234 |
+
train_ds = oversample(train_ds, RARE_BOOST)
|
| 235 |
+
logger.info(f"Oversampled train size: {len(train_ds)}")
|
| 236 |
+
train_ds = train_ds.with_transform(train_transform_batch)
|
| 237 |
+
val_ds = dataset["validation"].with_transform(val_transform_batch)
|
| 238 |
+
|
| 239 |
+
logging_steps = int(os.environ.get("LOG_STEPS", "50"))
|
| 240 |
+
args = TrainingArguments(
|
| 241 |
+
output_dir="./out",
|
| 242 |
+
per_device_train_batch_size=bs,
|
| 243 |
+
gradient_accumulation_steps=grad_acc,
|
| 244 |
+
num_train_epochs=epochs,
|
| 245 |
+
learning_rate=float(os.environ.get("LR", "1e-4")),
|
| 246 |
+
lr_scheduler_type="cosine",
|
| 247 |
+
warmup_ratio=0.05,
|
| 248 |
+
weight_decay=1e-4,
|
| 249 |
+
fp16=torch.cuda.is_available(),
|
| 250 |
+
dataloader_num_workers=3,
|
| 251 |
+
dataloader_pin_memory=True,
|
| 252 |
+
dataloader_prefetch_factor=4,
|
| 253 |
+
remove_unused_columns=False,
|
| 254 |
+
logging_steps=logging_steps,
|
| 255 |
+
report_to=[],
|
| 256 |
+
eval_strategy="no",
|
| 257 |
+
save_strategy="no",
|
| 258 |
+
seed=42,
|
| 259 |
+
ddp_find_unused_parameters=None,
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
trainer = Trainer(
|
| 263 |
+
model=model,
|
| 264 |
+
args=args,
|
| 265 |
+
train_dataset=train_ds,
|
| 266 |
+
processing_class=image_processor,
|
| 267 |
+
data_collator=collate_fn,
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
trainer.train()
|
| 271 |
+
torch.cuda.empty_cache()
|
| 272 |
+
metrics = evaluate_model(model, image_processor, dataset["validation"], device=model.device)
|
| 273 |
+
logger.info("FINAL RESULT: " + json.dumps(metrics, indent=2))
|
| 274 |
+
with open("final_metrics.json", "w") as f:
|
| 275 |
+
json.dump(metrics, f, indent=2)
|
| 276 |
+
|
| 277 |
+
model.save_pretrained("./out/best")
|
| 278 |
+
image_processor.save_pretrained("./out/best")
|
| 279 |
+
|
| 280 |
+
if do_push:
|
| 281 |
+
repo_id = os.environ.get("REPO", "harness-race/opencode-r3")
|
| 282 |
+
logger.info(f"Pushing to {repo_id}")
|
| 283 |
+
model.push_to_hub(
|
| 284 |
+
repo_id=repo_id,
|
| 285 |
+
commit_message="Fine-tune RT-DETR-R50 on biglam/loc_beyond_words (Beyond Words)",
|
| 286 |
+
private=False,
|
| 287 |
+
)
|
| 288 |
+
image_processor.push_to_hub(repo_id=repo_id, commit_message="Update processor")
|
| 289 |
+
with open("result.txt", "w") as f:
|
| 290 |
+
f.write(json.dumps(metrics))
|
| 291 |
+
logger.info("DONE")
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
if __name__ == "__main__":
|
| 295 |
+
main()
|