salahkhenfer commited on
Commit
8475155
·
verified ·
1 Parent(s): b5a5e68

Add Florence-2/DaViT LoRA training script

Browse files
Files changed (1) hide show
  1. train_lora_pear_florence.py +387 -0
train_lora_pear_florence.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ train_lora_pear_florence.py
3
+ ============================
4
+
5
+ Florence-2 / DaViT counterpart to train_lora_pear.py, targeting the paper's
6
+ best-reported configuration (DaViT-base, LoRA rank 32 -> F1 0.8769,
7
+ mAP@0.5 0.9171).
8
+
9
+ Same recipe as the DINOv2 script: freeze the vision backbone, add LoRA
10
+ adapters to its attention, feed its features to a COCO-pretrained
11
+ Deformable-DETR head, train only LoRA + neck + prediction heads.
12
+
13
+ IMPORTANT — read before running, this file is riskier than the DINOv2 one:
14
+ Florence-2's DaViT vision tower ships as custom "remote code" on the Hub
15
+ (`trust_remote_code=True`), not as a native, documented transformers class.
16
+ There is no stable public API for pulling out its four intermediate,
17
+ multi-scale feature maps, so `_extract_stage_features()` below uses forward
18
+ hooks with a best-effort heuristic to auto-locate the four DaViT stages. It
19
+ was written from documented DaViT architecture conventions but could NOT be
20
+ executed against the real weights in the environment this was written in
21
+ (broken local torch/transformers install). If it raises the RuntimeError in
22
+ `_locate_stage_container()`, run this file with `--debug` first: it prints
23
+ the vision tower's module tree so you can hard-code the two-line fix noted
24
+ in that function.
25
+
26
+ Two backbone sources are supported:
27
+ --source florence2 (default): the real Florence-2 vision-language-pretrained
28
+ DaViT weights — matches the paper, but is the fragile path above.
29
+ --source timm: a plain ImageNet-pretrained DaViT from timm, wired through
30
+ HF's long-stable timm-backbone support. Reliable, reproduces the
31
+ paper's *architectural* advantage (native multi-scale hierarchy) but
32
+ not its *pretraining* advantage (Florence-2's language-grounded
33
+ semantics). Use this if --source florence2 doesn't run on your machine.
34
+
35
+ Requirements: see requirements-train.txt, plus `timm` if using --source timm.
36
+
37
+ Usage:
38
+ python train_lora_pear_florence.py --source florence2 --rank 32 --epochs 10
39
+ python train_lora_pear_florence.py --source timm --rank 32 --epochs 10
40
+ python train_lora_pear_florence.py --debug # inspect Florence-2's structure, no training
41
+ """
42
+
43
+ import argparse
44
+
45
+ import torch
46
+ from datasets import load_dataset
47
+ from peft import LoraConfig, get_peft_model
48
+ from torch.utils.data import DataLoader
49
+ from transformers import (
50
+ AutoModelForCausalLM,
51
+ DeformableDetrConfig,
52
+ DeformableDetrForObjectDetection,
53
+ DeformableDetrImageProcessor,
54
+ )
55
+
56
+ DATASET_NAME = "salahkhenfer/pear-pests-dataset"
57
+ COCO_CHECKPOINT = "SenseTime/deformable-detr"
58
+ FLORENCE_CHECKPOINT = "microsoft/Florence-2-base"
59
+ TIMM_MODEL_NAME = "davit_base"
60
+ CLASS_NAMES = ["beetle", "black block", "dry blight", "health", "rust", "scab"]
61
+ LORA_TARGET_MODULES = ["qkv"] # DaViT's spatial + channel attention both use a single fused QKV Linear
62
+
63
+
64
+ # --------------------------------------------------------------------------
65
+ # Model construction — each step is its own small function.
66
+ # --------------------------------------------------------------------------
67
+
68
+ def build_model(source="florence2", num_labels=6, lora_rank=32):
69
+ """Frozen DaViT backbone (+LoRA) feeding a Deformable-DETR detection head."""
70
+ if source == "timm":
71
+ model = _build_bare_model_timm(num_labels)
72
+ else:
73
+ model = _build_bare_model_florence2(num_labels)
74
+ _reuse_pretrained_head(model)
75
+ _apply_lora_to_backbone(model, lora_rank)
76
+ _unfreeze_trainable_parts(model)
77
+ return model
78
+
79
+
80
+ def _build_bare_model_timm(num_labels):
81
+ """Reliable path: a real DaViT, ImageNet-pretrained, via HF's timm-backbone support."""
82
+ config = DeformableDetrConfig(
83
+ backbone=TIMM_MODEL_NAME,
84
+ use_timm_backbone=True,
85
+ use_pretrained_backbone=True,
86
+ num_labels=num_labels,
87
+ num_feature_levels=4,
88
+ )
89
+ return DeformableDetrForObjectDetection(config)
90
+
91
+
92
+ def _build_bare_model_florence2(num_labels):
93
+ """Fragile path: Florence-2's own vision-language-pretrained DaViT.
94
+
95
+ Builds a plain Deformable-DETR (default ResNet-50 config, so input_proj
96
+ shapes are a placeholder) and then swaps in a custom backbone module that
97
+ wraps Florence-2's DaViT and returns its four stage feature maps. The
98
+ neck (input_proj) is rebuilt to match DaViT-base's real stage channel
99
+ widths, since they differ from ResNet-50's.
100
+ """
101
+ davit = _load_florence2_davit()
102
+ stage_channels = [128, 256, 512, 1024] # DaViT-base stage widths (Sec. 2.3 of the paper)
103
+
104
+ config = DeformableDetrConfig(num_labels=num_labels, num_feature_levels=4)
105
+ model = DeformableDetrForObjectDetection(config)
106
+ # Reuse the model's own (sine/learned) position-embedding module rather than
107
+ # reimplementing it — Deformable-DETR's backbone wrapper must return position
108
+ # embeddings alongside feature maps, or the encoder call after it breaks.
109
+ position_embedding = model.model.backbone.position_embedding
110
+ model.model.backbone = _DaViTBackboneWrapper(davit, position_embedding)
111
+ model.model.input_proj = _build_input_proj(stage_channels, config.d_model)
112
+ return model
113
+
114
+
115
+ def _load_florence2_davit():
116
+ """Download Florence-2 and pull out just its vision tower (DaViT)."""
117
+ florence = AutoModelForCausalLM.from_pretrained(FLORENCE_CHECKPOINT, trust_remote_code=True)
118
+ for name, module in florence.named_modules():
119
+ if type(module).__name__ == "DaViT":
120
+ print(f"Found DaViT vision tower at `{name}`")
121
+ return module
122
+ raise RuntimeError(
123
+ "Could not find a `DaViT` submodule inside Florence-2. Run with --debug to print "
124
+ "the module tree, find the vision tower's attribute name, and adjust `_load_florence2_davit`."
125
+ )
126
+
127
+
128
+ class _DaViTBackboneWrapper(torch.nn.Module):
129
+ """Adapts a raw DaViT module to the interface Deformable-DETR's backbone must
130
+ provide: forward(pixel_values, pixel_mask) -> (list[(feature_map, mask)], list[pos_embed])."""
131
+
132
+ def __init__(self, davit, position_embedding):
133
+ super().__init__()
134
+ self.davit = davit
135
+ self.position_embedding = position_embedding
136
+
137
+ def forward(self, pixel_values, pixel_mask):
138
+ feature_maps = _extract_stage_features(self.davit, pixel_values)
139
+ out, pos = [], []
140
+ for fmap in feature_maps:
141
+ mask = torch.nn.functional.interpolate(pixel_mask[None].float(), size=fmap.shape[-2:]).to(torch.bool)[0]
142
+ out.append((fmap, mask))
143
+ pos.append(self.position_embedding(fmap, mask).to(fmap.dtype))
144
+ return out, pos
145
+
146
+
147
+ def _extract_stage_features(davit, pixel_values):
148
+ """Run DaViT and capture its four stages' output feature maps via forward hooks.
149
+
150
+ NOT VERIFIED against real weights (see module docstring). If this raises
151
+ or returns fewer/more than 4 maps, run --debug and fix `_locate_stage_container`.
152
+ """
153
+ stages = _locate_stage_container(davit)
154
+ captured = []
155
+
156
+ def hook(_module, _inputs, output):
157
+ captured.append(output)
158
+
159
+ handles = [stage.register_forward_hook(hook) for stage in stages]
160
+ try:
161
+ davit(pixel_values)
162
+ finally:
163
+ for handle in handles:
164
+ handle.remove()
165
+
166
+ feature_maps = []
167
+ for tensor in captured:
168
+ if tensor.dim() == 3: # [B, N, C] token sequence -> reshape to [B, C, H, W]
169
+ batch, num_tokens, channels = tensor.shape
170
+ side = int(num_tokens**0.5)
171
+ tensor = tensor.transpose(1, 2).reshape(batch, channels, side, side)
172
+ feature_maps.append(tensor)
173
+ return feature_maps
174
+
175
+
176
+ def _locate_stage_container(davit):
177
+ """Heuristic: DaViT commonly exposes its 4 stages as a top-level ModuleList of length 4.
178
+
179
+ If this fails, replace the body with the real attribute, e.g.:
180
+ return list(davit.stages)
181
+ """
182
+ for module in davit.children():
183
+ if isinstance(module, torch.nn.ModuleList) and len(module) == 4:
184
+ return list(module)
185
+ raise RuntimeError(
186
+ "Could not auto-detect DaViT's 4 stages. Run with --debug, inspect the printed "
187
+ "module tree for the vision tower, and hard-code the stage list in `_locate_stage_container`."
188
+ )
189
+
190
+
191
+ def _build_input_proj(stage_channels, d_model):
192
+ """Mirror Deformable-DETR's own neck: a 1x1 conv + GroupNorm per feature level."""
193
+ return torch.nn.ModuleList(
194
+ torch.nn.Sequential(
195
+ torch.nn.Conv2d(channels, d_model, kernel_size=1),
196
+ torch.nn.GroupNorm(32, d_model),
197
+ )
198
+ for channels in stage_channels
199
+ )
200
+
201
+
202
+ def _reuse_pretrained_head(model):
203
+ """Copy the COCO-pretrained encoder/decoder weights onto our model (see train_lora_pear.py)."""
204
+ pretrained_sd = DeformableDetrForObjectDetection.from_pretrained(COCO_CHECKPOINT).state_dict()
205
+ our_sd = model.state_dict()
206
+ reusable = {
207
+ key: value
208
+ for key, value in pretrained_sd.items()
209
+ if key in our_sd
210
+ and value.shape == our_sd[key].shape
211
+ and "backbone" not in key
212
+ and "input_proj" not in key
213
+ }
214
+ our_sd.update(reusable)
215
+ model.load_state_dict(our_sd)
216
+ print(f"Reused {len(reusable)} pretrained encoder/decoder tensors from {COCO_CHECKPOINT}")
217
+
218
+
219
+ def _apply_lora_to_backbone(model, rank):
220
+ """Freeze everything, then inject trainable LoRA adapters into the backbone's fused
221
+ QKV projections (`target_modules` matches by leaf name, so it only touches the
222
+ backbone, wherever it lives in the module tree)."""
223
+ lora_config = LoraConfig(
224
+ r=rank, lora_alpha=2 * rank, lora_dropout=0.1, target_modules=LORA_TARGET_MODULES, bias="none",
225
+ )
226
+ backbone = model.model.backbone
227
+ peft_backbone = get_peft_model(backbone, lora_config)
228
+ model.model.backbone = peft_backbone
229
+
230
+
231
+ def _unfreeze_trainable_parts(model):
232
+ """Per the paper: the neck and prediction heads are trained; the encoder/decoder
233
+ stay frozen (already true from `_reuse_pretrained_head` + peft's default freeze)."""
234
+ for module in [model.model.input_proj, model.class_embed, model.bbox_embed]:
235
+ for param in module.parameters():
236
+ param.requires_grad = True
237
+
238
+
239
+ def count_trainable_parameters(model):
240
+ trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
241
+ total = sum(p.numel() for p in model.parameters())
242
+ return trainable, total
243
+
244
+
245
+ # --------------------------------------------------------------------------
246
+ # Data — identical to train_lora_pear.py.
247
+ # --------------------------------------------------------------------------
248
+
249
+ def load_splits():
250
+ return load_dataset(DATASET_NAME)
251
+
252
+
253
+ def to_coco_annotations(example):
254
+ objects = example["objects"]
255
+ return {
256
+ "image_id": example["image_id"],
257
+ "annotations": [
258
+ {"image_id": example["image_id"], "category_id": category, "bbox": bbox, "area": area, "iscrowd": 0}
259
+ for bbox, category, area in zip(objects["bbox"], objects["category"], objects["area"])
260
+ ],
261
+ }
262
+
263
+
264
+ def make_collate_fn(processor):
265
+ def collate_fn(batch):
266
+ images = [example["image"].convert("RGB") for example in batch]
267
+ annotations = [to_coco_annotations(example) for example in batch]
268
+ return processor(images=images, annotations=annotations, return_tensors="pt")
269
+
270
+ return collate_fn
271
+
272
+
273
+ def make_dataloaders(dataset, processor, batch_size):
274
+ collate_fn = make_collate_fn(processor)
275
+ train_loader = DataLoader(dataset["train"], batch_size=batch_size, shuffle=True, collate_fn=collate_fn)
276
+ valid_loader = DataLoader(dataset["validation"], batch_size=batch_size, collate_fn=collate_fn)
277
+ return train_loader, valid_loader
278
+
279
+
280
+ # --------------------------------------------------------------------------
281
+ # Training — identical to train_lora_pear.py.
282
+ # --------------------------------------------------------------------------
283
+
284
+ def move_batch_to_device(batch, device):
285
+ batch["pixel_values"] = batch["pixel_values"].to(device)
286
+ batch["pixel_mask"] = batch["pixel_mask"].to(device)
287
+ batch["labels"] = [{k: v.to(device) for k, v in target.items()} for target in batch["labels"]]
288
+ return batch
289
+
290
+
291
+ def run_one_epoch(model, loader, optimizer, device):
292
+ model.train()
293
+ total_loss = 0.0
294
+ for batch in loader:
295
+ batch = move_batch_to_device(batch, device)
296
+ loss = model(**batch).loss
297
+ optimizer.zero_grad()
298
+ loss.backward()
299
+ optimizer.step()
300
+ total_loss += loss.item()
301
+ return total_loss / max(len(loader), 1)
302
+
303
+
304
+ @torch.no_grad()
305
+ def evaluate_loss(model, loader, device):
306
+ model.eval()
307
+ total_loss = 0.0
308
+ for batch in loader:
309
+ batch = move_batch_to_device(batch, device)
310
+ total_loss += model(**batch).loss.item()
311
+ return total_loss / max(len(loader), 1)
312
+
313
+
314
+ def train(model, train_loader, valid_loader, epochs, lr, weight_decay, device):
315
+ model.to(device)
316
+ trainable_params = [p for p in model.parameters() if p.requires_grad]
317
+ optimizer = torch.optim.AdamW(trainable_params, lr=lr, weight_decay=weight_decay)
318
+ scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[max(int(epochs * 0.8), 1)], gamma=0.1)
319
+
320
+ for epoch in range(1, epochs + 1):
321
+ train_loss = run_one_epoch(model, train_loader, optimizer, device)
322
+ valid_loss = evaluate_loss(model, valid_loader, device)
323
+ scheduler.step()
324
+ print(f"epoch {epoch}/{epochs} train_loss={train_loss:.4f} valid_loss={valid_loss:.4f}")
325
+
326
+ return model
327
+
328
+
329
+ # --------------------------------------------------------------------------
330
+ # Debug helper — prints Florence-2's structure so you can fix the two
331
+ # heuristic functions above without guessing.
332
+ # --------------------------------------------------------------------------
333
+
334
+ def debug_print_florence2_structure():
335
+ florence = AutoModelForCausalLM.from_pretrained(FLORENCE_CHECKPOINT, trust_remote_code=True)
336
+ print(florence)
337
+ davit = _load_florence2_davit()
338
+ print("\n--- DaViT vision tower children ---")
339
+ for name, module in davit.named_children():
340
+ print(f"{name}: {type(module).__name__}")
341
+
342
+
343
+ # --------------------------------------------------------------------------
344
+ # Entry point.
345
+ # --------------------------------------------------------------------------
346
+
347
+ def parse_args():
348
+ parser = argparse.ArgumentParser(description=__doc__)
349
+ parser.add_argument("--source", default="florence2", choices=["florence2", "timm"])
350
+ parser.add_argument("--rank", type=int, default=32, choices=[8, 16, 32],
351
+ help="Default is 32, the paper's best Florence configuration (DaViT-base, r=32).")
352
+ parser.add_argument("--epochs", type=int, default=10)
353
+ parser.add_argument("--batch_size", type=int, default=1)
354
+ parser.add_argument("--lr", type=float, default=1e-4)
355
+ parser.add_argument("--weight_decay", type=float, default=1e-4)
356
+ parser.add_argument("--output_dir", default="pear-lora-florence-checkpoint")
357
+ parser.add_argument("--debug", action="store_true", help="Print Florence-2's structure and exit, no training.")
358
+ return parser.parse_args()
359
+
360
+
361
+ def main():
362
+ args = parse_args()
363
+
364
+ if args.debug:
365
+ debug_print_florence2_structure()
366
+ return
367
+
368
+ device = "cuda" if torch.cuda.is_available() else "cpu"
369
+ print(f"Using device: {device}")
370
+
371
+ dataset = load_splits()
372
+ processor = DeformableDetrImageProcessor.from_pretrained(COCO_CHECKPOINT)
373
+ train_loader, valid_loader = make_dataloaders(dataset, processor, args.batch_size)
374
+
375
+ model = build_model(args.source, num_labels=len(CLASS_NAMES), lora_rank=args.rank)
376
+ trainable, total = count_trainable_parameters(model)
377
+ print(f"Trainable parameters: {trainable:,} / {total:,} ({100 * trainable / total:.2f}%)")
378
+
379
+ model = train(model, train_loader, valid_loader, args.epochs, args.lr, args.weight_decay, device)
380
+
381
+ model.save_pretrained(args.output_dir)
382
+ processor.save_pretrained(args.output_dir)
383
+ print(f"Saved model + processor to {args.output_dir}")
384
+
385
+
386
+ if __name__ == "__main__":
387
+ main()