Godsonntungi2 commited on
Commit
bc82997
·
verified ·
1 Parent(s): 3de49a5

Add RT-DETR object detection training script

Browse files
Files changed (1) hide show
  1. train_rtdetr_detection.py +266 -0
train_rtdetr_detection.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # dependencies = [
3
+ # "transformers>=4.40.0",
4
+ # "torch",
5
+ # "torchvision",
6
+ # "datasets",
7
+ # "albumentations",
8
+ # "accelerate",
9
+ # "huggingface_hub",
10
+ # "Pillow",
11
+ # "evaluate",
12
+ # "pycocotools",
13
+ # ]
14
+ # ///
15
+
16
+ """
17
+ RT-DETR Fine-tuning Script for Object Detection
18
+ Fine-tunes RT-DETR on the CPPE-5 dataset (medical PPE detection)
19
+ """
20
+
21
+ import os
22
+ import torch
23
+ import numpy as np
24
+ from PIL import Image
25
+ from functools import partial
26
+ from dataclasses import dataclass
27
+ from typing import Dict, List, Any
28
+
29
+ from datasets import load_dataset
30
+ from transformers import (
31
+ RTDetrForObjectDetection,
32
+ RTDetrImageProcessor,
33
+ TrainingArguments,
34
+ Trainer,
35
+ )
36
+ from huggingface_hub import login
37
+
38
+ # Login
39
+ hf_token = os.environ.get("HF_TOKEN")
40
+ if hf_token:
41
+ login(token=hf_token)
42
+ print("Logged in to Hugging Face Hub")
43
+
44
+ # ============================================================================
45
+ # Configuration
46
+ # ============================================================================
47
+ MODEL_NAME = "PekingU/rtdetr_r50vd" # RT-DETR with ResNet-50 backbone
48
+ DATASET_NAME = "cppe-5" # Medical PPE detection dataset (5 classes)
49
+ OUTPUT_DIR = "rtdetr-cppe5-detection"
50
+ HUB_MODEL_ID = "Godsonntungi2/rtdetr-cppe5-detection"
51
+
52
+ # Training parameters (optimized for A10G 24GB)
53
+ BATCH_SIZE = 4
54
+ LEARNING_RATE = 1e-5
55
+ NUM_EPOCHS = 10
56
+ MAX_TRAIN_SAMPLES = 500 # Limit for demo (full dataset has ~1000)
57
+
58
+ print(f"Loading model: {MODEL_NAME}")
59
+ print(f"Dataset: {DATASET_NAME}")
60
+
61
+ # ============================================================================
62
+ # Load Dataset
63
+ # ============================================================================
64
+ print("\nLoading CPPE-5 dataset...")
65
+ dataset = load_dataset(DATASET_NAME)
66
+ print(f"Train samples: {len(dataset['train'])}")
67
+ print(f"Test samples: {len(dataset['test'])}")
68
+
69
+ # Limit samples for demo
70
+ if MAX_TRAIN_SAMPLES:
71
+ dataset["train"] = dataset["train"].select(range(min(MAX_TRAIN_SAMPLES, len(dataset["train"]))))
72
+ dataset["test"] = dataset["test"].select(range(min(100, len(dataset["test"]))))
73
+ print(f"Using {len(dataset['train'])} train, {len(dataset['test'])} test samples")
74
+
75
+ # Get categories
76
+ categories = dataset["train"].features["objects"].feature["category"].names
77
+ id2label = {i: label for i, label in enumerate(categories)}
78
+ label2id = {label: i for i, label in enumerate(categories)}
79
+ print(f"Classes: {categories}")
80
+
81
+ # ============================================================================
82
+ # Image Processor & Model
83
+ # ============================================================================
84
+ print("\nLoading image processor and model...")
85
+ image_processor = RTDetrImageProcessor.from_pretrained(MODEL_NAME)
86
+
87
+ model = RTDetrForObjectDetection.from_pretrained(
88
+ MODEL_NAME,
89
+ id2label=id2label,
90
+ label2id=label2id,
91
+ ignore_mismatched_sizes=True, # Important: class head size changes
92
+ )
93
+ print(f"Model loaded with {len(id2label)} classes")
94
+
95
+ # ============================================================================
96
+ # Data Preprocessing
97
+ # ============================================================================
98
+ def format_annotations(image_id, objects, image_size):
99
+ """Convert dataset annotations to COCO format for RT-DETR"""
100
+ annotations = []
101
+ for i, (bbox, category) in enumerate(zip(objects["bbox"], objects["category"])):
102
+ # CPPE-5 bbox format: [x, y, width, height]
103
+ annotations.append({
104
+ "id": i,
105
+ "image_id": image_id,
106
+ "category_id": category,
107
+ "bbox": bbox,
108
+ "area": bbox[2] * bbox[3],
109
+ "iscrowd": 0,
110
+ })
111
+ return {
112
+ "image_id": image_id,
113
+ "annotations": annotations,
114
+ }
115
+
116
+ def transform_batch(examples, image_processor):
117
+ """Transform a batch of examples for RT-DETR"""
118
+ images = []
119
+ annotations = []
120
+
121
+ for idx, (image, objects) in enumerate(zip(examples["image"], examples["objects"])):
122
+ # Convert to RGB if needed
123
+ if image.mode != "RGB":
124
+ image = image.convert("RGB")
125
+ images.append(image)
126
+
127
+ # Format annotations
128
+ anno = format_annotations(idx, objects, image.size)
129
+ annotations.append(anno)
130
+
131
+ # Process with image processor
132
+ result = image_processor(
133
+ images=images,
134
+ annotations=annotations,
135
+ return_tensors="pt",
136
+ )
137
+
138
+ return result
139
+
140
+ # Apply transforms
141
+ print("\nPreparing datasets...")
142
+ transform_fn = partial(transform_batch, image_processor=image_processor)
143
+
144
+ # Process in batches
145
+ train_dataset = dataset["train"].with_transform(
146
+ lambda x: transform_fn(x)
147
+ )
148
+ eval_dataset = dataset["test"].with_transform(
149
+ lambda x: transform_fn(x)
150
+ )
151
+
152
+ # ============================================================================
153
+ # Custom Collator
154
+ # ============================================================================
155
+ def collate_fn(batch):
156
+ """Custom collate function for object detection"""
157
+ pixel_values = torch.stack([item["pixel_values"] for item in batch])
158
+ labels = [item["labels"] for item in batch]
159
+
160
+ return {
161
+ "pixel_values": pixel_values,
162
+ "labels": labels,
163
+ }
164
+
165
+ # ============================================================================
166
+ # Training Arguments
167
+ # ============================================================================
168
+ training_args = TrainingArguments(
169
+ output_dir=OUTPUT_DIR,
170
+
171
+ # Training params
172
+ num_train_epochs=NUM_EPOCHS,
173
+ per_device_train_batch_size=BATCH_SIZE,
174
+ per_device_eval_batch_size=BATCH_SIZE,
175
+ learning_rate=LEARNING_RATE,
176
+ weight_decay=0.01,
177
+
178
+ # Optimization
179
+ lr_scheduler_type="cosine",
180
+ warmup_ratio=0.1,
181
+ fp16=True, # Mixed precision
182
+ gradient_accumulation_steps=4,
183
+
184
+ # Logging & saving
185
+ logging_steps=10,
186
+ eval_strategy="epoch",
187
+ save_strategy="epoch",
188
+ save_total_limit=2,
189
+ load_best_model_at_end=True,
190
+ metric_for_best_model="eval_loss",
191
+
192
+ # Hub
193
+ push_to_hub=True,
194
+ hub_model_id=HUB_MODEL_ID,
195
+ hub_strategy="end",
196
+
197
+ # Other
198
+ remove_unused_columns=False,
199
+ dataloader_num_workers=2,
200
+ )
201
+
202
+ # ============================================================================
203
+ # Trainer
204
+ # ============================================================================
205
+ print("\nInitializing Trainer...")
206
+ trainer = Trainer(
207
+ model=model,
208
+ args=training_args,
209
+ train_dataset=train_dataset,
210
+ eval_dataset=eval_dataset,
211
+ processing_class=image_processor,
212
+ data_collator=collate_fn,
213
+ )
214
+
215
+ # ============================================================================
216
+ # Train!
217
+ # ============================================================================
218
+ print("\nStarting training...")
219
+ print(f" Epochs: {NUM_EPOCHS}")
220
+ print(f" Batch size: {BATCH_SIZE}")
221
+ print(f" Learning rate: {LEARNING_RATE}")
222
+ print("="*60)
223
+
224
+ trainer.train()
225
+
226
+ # ============================================================================
227
+ # Save & Push to Hub
228
+ # ============================================================================
229
+ print("\nSaving model...")
230
+ trainer.save_model()
231
+ image_processor.save_pretrained(OUTPUT_DIR)
232
+
233
+ print("\nPushing to Hub...")
234
+ trainer.push_to_hub()
235
+
236
+ print("\n" + "="*60)
237
+ print("Training complete!")
238
+ print(f"Model: https://huggingface.co/{HUB_MODEL_ID}")
239
+ print("="*60)
240
+
241
+ # ============================================================================
242
+ # Quick Inference Test
243
+ # ============================================================================
244
+ print("\nRunning quick inference test...")
245
+ test_image = dataset["test"][0]["image"]
246
+ if test_image.mode != "RGB":
247
+ test_image = test_image.convert("RGB")
248
+
249
+ inputs = image_processor(images=test_image, return_tensors="pt")
250
+ inputs = {k: v.to(model.device) for k, v in inputs.items()}
251
+
252
+ with torch.no_grad():
253
+ outputs = model(**inputs)
254
+
255
+ # Post-process
256
+ results = image_processor.post_process_object_detection(
257
+ outputs,
258
+ target_sizes=torch.tensor([test_image.size[::-1]]),
259
+ threshold=0.5
260
+ )[0]
261
+
262
+ print(f"Detected {len(results['labels'])} objects:")
263
+ for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
264
+ print(f" - {id2label[label.item()]}: {score.item():.2f}")
265
+
266
+ print("\nDone!")