samwell commited on
Commit
64485f8
·
verified ·
1 Parent(s): a56f141

Upload train_medsiglip.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. train_medsiglip.py +604 -0
train_medsiglip.py ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LaborView AI - MedSigLIP Training Script
3
+ Fine-tune MedSigLIP vision encoder for ultrasound segmentation
4
+ Self-contained script for HuggingFace Jobs
5
+ """
6
+
7
+ # /// script
8
+ # dependencies = [
9
+ # "torch>=2.0.0",
10
+ # "transformers>=4.50.0",
11
+ # "accelerate>=0.27.0",
12
+ # "albumentations>=1.3.0",
13
+ # "pillow>=10.0.0",
14
+ # "numpy>=1.24.0",
15
+ # "tqdm>=4.65.0",
16
+ # "huggingface_hub>=0.20.0",
17
+ # "pandas>=2.0.0",
18
+ # "opencv-python-headless>=4.8.0",
19
+ # ]
20
+ # ///
21
+
22
+ import os
23
+ import sys
24
+ import json
25
+ import zipfile
26
+ import urllib.request
27
+ from pathlib import Path
28
+ from dataclasses import dataclass
29
+ from typing import Dict, List, Optional, Tuple
30
+ from datetime import datetime
31
+
32
+ import torch
33
+ import torch.nn as nn
34
+ import torch.nn.functional as F
35
+ from torch.amp import GradScaler, autocast
36
+ from torch.optim import AdamW
37
+ from torch.optim.lr_scheduler import OneCycleLR
38
+ from torch.utils.data import Dataset, DataLoader
39
+ from PIL import Image
40
+ import numpy as np
41
+ from tqdm import tqdm
42
+
43
+ try:
44
+ import albumentations as A
45
+ from albumentations.pytorch import ToTensorV2
46
+ ALBU_AVAILABLE = True
47
+ except ImportError:
48
+ ALBU_AVAILABLE = False
49
+ import torchvision.transforms as T
50
+
51
+
52
+ @dataclass
53
+ class Config:
54
+ # Data
55
+ data_url: str = "https://zenodo.org/records/17655183/files/DatasetV3.zip?download=1"
56
+ data_dir: Path = Path("./data")
57
+ image_size: int = 448 # MedSigLIP native resolution
58
+
59
+ # Model - MedSigLIP
60
+ encoder_name: str = "medsiglip"
61
+ encoder_pretrained: str = "google/medsiglip-448"
62
+ encoder_hidden_dim: int = 1152 # SigLIP-Large hidden dim
63
+ projection_dim: int = 256
64
+
65
+ # Task heads
66
+ num_plane_classes: int = 2
67
+ num_seg_classes: int = 3 # background, symphysis, head
68
+
69
+ # Training
70
+ batch_size: int = 8 # Smaller batch for larger model
71
+ num_epochs: int = 30
72
+ learning_rate: float = 5e-5 # Lower LR for fine-tuning
73
+ weight_decay: float = 0.01
74
+ warmup_epochs: int = 2
75
+ gradient_accumulation: int = 4
76
+ freeze_encoder_epochs: int = 3 # Freeze encoder initially
77
+
78
+ # Output
79
+ output_dir: Path = Path("./outputs")
80
+ hub_model_id: str = "samwell/laborview-medsiglip"
81
+ push_to_hub: bool = True
82
+ seed: int = 42
83
+
84
+
85
+ class UltrasoundDataset(Dataset):
86
+ """Dataset for ultrasound segmentation"""
87
+
88
+ def __init__(self, data_dir: Path, split: str = "train", image_size: int = 448, augment: bool = True):
89
+ self.data_dir = Path(data_dir)
90
+ self.split = split
91
+ self.image_size = image_size
92
+ self.samples = self._find_samples()
93
+ print(f"Found {len(self.samples)} samples for {split}")
94
+ self.transform = self._get_transform(augment and split == "train")
95
+
96
+ def _find_samples(self) -> List[Dict]:
97
+ samples = []
98
+ seg_dir = self.data_dir / self.split / "seg"
99
+
100
+ if not seg_dir.exists():
101
+ print(f"Warning: {seg_dir} not found")
102
+ return samples
103
+
104
+ for video_dir in seg_dir.iterdir():
105
+ if not video_dir.is_dir():
106
+ continue
107
+
108
+ # Check for images and masks
109
+ image_dir = video_dir / "image"
110
+ mask_dir = video_dir / "mask"
111
+
112
+ if mask_dir.exists():
113
+ for mask_path in mask_dir.glob("*.png"):
114
+ # Try to find corresponding image
115
+ image_path = None
116
+ if image_dir.exists():
117
+ potential_image = image_dir / mask_path.name
118
+ if potential_image.exists():
119
+ image_path = str(potential_image)
120
+
121
+ samples.append({
122
+ "mask_path": str(mask_path),
123
+ "image_path": image_path,
124
+ "video_id": video_dir.name,
125
+ })
126
+
127
+ return samples
128
+
129
+ def _get_transform(self, augment: bool):
130
+ if ALBU_AVAILABLE:
131
+ if augment:
132
+ return A.Compose([
133
+ A.Resize(self.image_size, self.image_size),
134
+ A.HorizontalFlip(p=0.5),
135
+ A.RandomBrightnessContrast(p=0.3),
136
+ A.GaussNoise(var_limit=(10, 50), p=0.2),
137
+ A.ShiftScaleRotate(shift_limit=0.1, scale_limit=0.1, rotate_limit=10, p=0.3),
138
+ A.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]), # MedSigLIP normalization
139
+ ToTensorV2()
140
+ ])
141
+ else:
142
+ return A.Compose([
143
+ A.Resize(self.image_size, self.image_size),
144
+ A.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
145
+ ToTensorV2()
146
+ ])
147
+ else:
148
+ return T.Compose([
149
+ T.Resize((self.image_size, self.image_size)),
150
+ T.ToTensor(),
151
+ T.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
152
+ ])
153
+
154
+ def __len__(self):
155
+ return len(self.samples)
156
+
157
+ def __getitem__(self, idx):
158
+ sample = self.samples[idx]
159
+
160
+ # Load mask
161
+ mask = Image.open(sample["mask_path"]).convert("L")
162
+ mask = np.array(mask)
163
+
164
+ # Load or create image from mask
165
+ if sample["image_path"] and os.path.exists(sample["image_path"]):
166
+ image = Image.open(sample["image_path"]).convert("RGB")
167
+ image = np.array(image)
168
+ else:
169
+ # Use mask as grayscale image
170
+ image = np.stack([mask, mask, mask], axis=-1)
171
+
172
+ # Convert mask to class labels (0=background, 1=symphysis, 2=head)
173
+ # Assuming mask has different intensity values for different structures
174
+ mask_classes = np.zeros_like(mask, dtype=np.int64)
175
+ mask_classes[mask > 0] = 1 # Any non-zero is foreground
176
+ mask_classes[mask > 127] = 2 # Higher intensity is second class
177
+
178
+ if ALBU_AVAILABLE:
179
+ transformed = self.transform(image=image, mask=mask_classes)
180
+ image, mask = transformed["image"], transformed["mask"]
181
+ else:
182
+ image = self.transform(Image.fromarray(image))
183
+ mask = torch.from_numpy(
184
+ np.array(Image.fromarray(mask_classes.astype(np.uint8)).resize(
185
+ (self.image_size, self.image_size), Image.NEAREST
186
+ ))
187
+ ).long()
188
+
189
+ return {
190
+ "pixel_values": image,
191
+ "seg_labels": mask,
192
+ "plane_labels": torch.tensor(1, dtype=torch.long) # Standard plane
193
+ }
194
+
195
+
196
+ class SegmentationDecoder(nn.Module):
197
+ """Decoder for upsampling vision features to segmentation mask"""
198
+
199
+ def __init__(self, input_dim: int, num_classes: int, decoder_channels=[512, 256, 128, 64]):
200
+ super().__init__()
201
+
202
+ self.input_proj = nn.Conv2d(input_dim, decoder_channels[0], 1)
203
+
204
+ self.up_blocks = nn.ModuleList()
205
+ in_ch = decoder_channels[0]
206
+ for out_ch in decoder_channels[1:]:
207
+ self.up_blocks.append(nn.Sequential(
208
+ nn.ConvTranspose2d(in_ch, out_ch, 4, stride=2, padding=1),
209
+ nn.BatchNorm2d(out_ch),
210
+ nn.GELU()
211
+ ))
212
+ in_ch = out_ch
213
+
214
+ # Final upsampling to full resolution
215
+ self.final_up = nn.Sequential(
216
+ nn.ConvTranspose2d(decoder_channels[-1], 32, 4, stride=2, padding=1),
217
+ nn.BatchNorm2d(32),
218
+ nn.GELU(),
219
+ nn.ConvTranspose2d(32, 32, 4, stride=2, padding=1),
220
+ nn.BatchNorm2d(32),
221
+ nn.GELU(),
222
+ )
223
+
224
+ self.classifier = nn.Conv2d(32, num_classes, 1)
225
+
226
+ def forward(self, x, target_size=None):
227
+ B = x.shape[0]
228
+
229
+ # Handle different input shapes
230
+ if x.dim() == 3:
231
+ # [B, num_patches, hidden_dim] -> [B, hidden_dim, H, W]
232
+ num_patches = x.shape[1]
233
+ H = W = int(num_patches ** 0.5)
234
+ x = x.transpose(1, 2).reshape(B, -1, H, W)
235
+
236
+ x = self.input_proj(x)
237
+
238
+ for block in self.up_blocks:
239
+ x = block(x)
240
+
241
+ x = self.final_up(x)
242
+ x = self.classifier(x)
243
+
244
+ if target_size:
245
+ x = F.interpolate(x, size=target_size, mode='bilinear', align_corners=False)
246
+
247
+ return x
248
+
249
+
250
+ class LaborViewMedSigLIP(nn.Module):
251
+ """LaborView model with MedSigLIP vision encoder"""
252
+
253
+ def __init__(self, config: Config):
254
+ super().__init__()
255
+ self.config = config
256
+
257
+ # Load MedSigLIP
258
+ print(f"Loading MedSigLIP from {config.encoder_pretrained}...")
259
+ from transformers import AutoModel
260
+
261
+ self.encoder = AutoModel.from_pretrained(
262
+ config.encoder_pretrained,
263
+ trust_remote_code=True
264
+ )
265
+
266
+ # Get vision model from SigLIP
267
+ if hasattr(self.encoder, 'vision_model'):
268
+ self.vision_encoder = self.encoder.vision_model
269
+ else:
270
+ self.vision_encoder = self.encoder
271
+
272
+ # Get hidden dimension from config
273
+ if hasattr(self.vision_encoder.config, 'hidden_size'):
274
+ hidden_dim = self.vision_encoder.config.hidden_size
275
+ else:
276
+ hidden_dim = config.encoder_hidden_dim
277
+
278
+ print(f"Vision encoder hidden dim: {hidden_dim}")
279
+
280
+ # Projector for classification
281
+ self.projector = nn.Sequential(
282
+ nn.Linear(hidden_dim, config.projection_dim),
283
+ nn.LayerNorm(config.projection_dim),
284
+ nn.GELU(),
285
+ nn.Linear(config.projection_dim, config.projection_dim)
286
+ )
287
+
288
+ # Classification head
289
+ self.cls_head = nn.Linear(config.projection_dim, config.num_plane_classes)
290
+
291
+ # Segmentation decoder
292
+ self.seg_decoder = SegmentationDecoder(hidden_dim, config.num_seg_classes)
293
+
294
+ def forward(self, pixel_values):
295
+ # Get vision features
296
+ if hasattr(self, 'vision_encoder'):
297
+ outputs = self.vision_encoder(pixel_values)
298
+ else:
299
+ outputs = self.encoder.get_image_features(pixel_values, return_dict=True)
300
+
301
+ # Get hidden states
302
+ if hasattr(outputs, 'last_hidden_state'):
303
+ hidden = outputs.last_hidden_state
304
+ elif hasattr(outputs, 'pooler_output'):
305
+ hidden = outputs.pooler_output
306
+ else:
307
+ hidden = outputs
308
+
309
+ # Handle different output formats
310
+ if hidden.dim() == 2:
311
+ # [B, hidden_dim] - pooled output
312
+ pooled = hidden
313
+ # Create spatial features for segmentation
314
+ B, D = hidden.shape
315
+ seq = hidden.unsqueeze(1).expand(B, 32*32, D)
316
+ elif hidden.dim() == 3:
317
+ # [B, num_patches, hidden_dim]
318
+ pooled = hidden.mean(dim=1)
319
+ seq = hidden
320
+ else:
321
+ # [B, D, H, W]
322
+ B, D, H, W = hidden.shape
323
+ pooled = hidden.mean(dim=[2, 3])
324
+ seq = hidden.flatten(2).transpose(1, 2)
325
+
326
+ # Classification
327
+ projected = self.projector(pooled)
328
+ plane_logits = self.cls_head(projected)
329
+
330
+ # Segmentation
331
+ seg_masks = self.seg_decoder(seq, target_size=pixel_values.shape[-2:])
332
+
333
+ return plane_logits, seg_masks
334
+
335
+ def compute_loss(self, plane_logits, seg_masks, plane_labels, seg_labels):
336
+ losses = {}
337
+
338
+ # Classification loss
339
+ if plane_labels is not None:
340
+ losses["cls"] = F.cross_entropy(plane_logits, plane_labels)
341
+
342
+ # Segmentation loss (Dice + CE)
343
+ if seg_labels is not None:
344
+ # Cross entropy
345
+ ce_loss = F.cross_entropy(seg_masks, seg_labels.long())
346
+
347
+ # Dice loss
348
+ seg_probs = F.softmax(seg_masks, dim=1)
349
+ target_oh = F.one_hot(seg_labels.long(), self.config.num_seg_classes).permute(0, 3, 1, 2).float()
350
+
351
+ intersection = (seg_probs * target_oh).sum(dim=(2, 3))
352
+ union = seg_probs.sum(dim=(2, 3)) + target_oh.sum(dim=(2, 3))
353
+ dice_loss = 1 - ((2 * intersection + 1e-6) / (union + 1e-6)).mean()
354
+
355
+ losses["seg"] = dice_loss + ce_loss
356
+
357
+ return sum(losses.values()), losses
358
+
359
+ def freeze_encoder(self):
360
+ """Freeze the vision encoder"""
361
+ for param in self.vision_encoder.parameters():
362
+ param.requires_grad = False
363
+ print("Encoder frozen")
364
+
365
+ def unfreeze_encoder(self):
366
+ """Unfreeze the vision encoder"""
367
+ for param in self.vision_encoder.parameters():
368
+ param.requires_grad = True
369
+ print("Encoder unfrozen")
370
+
371
+
372
+ def train_epoch(model, loader, optimizer, scheduler, scaler, device, config, epoch):
373
+ model.train()
374
+ total_loss, num_batches = 0, 0
375
+
376
+ pbar = tqdm(loader, desc=f"Epoch {epoch+1} Training")
377
+ for batch_idx, batch in enumerate(pbar):
378
+ pixel_values = batch["pixel_values"].to(device)
379
+ seg_labels = batch["seg_labels"].to(device)
380
+ plane_labels = batch["plane_labels"].to(device)
381
+
382
+ with autocast("cuda", enabled=True):
383
+ plane_logits, seg_masks = model(pixel_values)
384
+ loss, _ = model.compute_loss(plane_logits, seg_masks, plane_labels, seg_labels)
385
+
386
+ loss = loss / config.gradient_accumulation
387
+ scaler.scale(loss).backward()
388
+
389
+ if (batch_idx + 1) % config.gradient_accumulation == 0:
390
+ scaler.step(optimizer)
391
+ scaler.update()
392
+ optimizer.zero_grad()
393
+ scheduler.step()
394
+
395
+ total_loss += loss.item() * config.gradient_accumulation
396
+ num_batches += 1
397
+ pbar.set_postfix({"loss": f"{loss.item() * config.gradient_accumulation:.4f}"})
398
+
399
+ return total_loss / num_batches
400
+
401
+
402
+ @torch.no_grad()
403
+ def validate(model, loader, device):
404
+ model.eval()
405
+ total_loss, total_iou, num_batches = 0, 0, 0
406
+
407
+ for batch in tqdm(loader, desc="Validating"):
408
+ pixel_values = batch["pixel_values"].to(device)
409
+ seg_labels = batch["seg_labels"].to(device)
410
+ plane_labels = batch["plane_labels"].to(device)
411
+
412
+ plane_logits, seg_masks = model(pixel_values)
413
+ loss, _ = model.compute_loss(plane_logits, seg_masks, plane_labels, seg_labels)
414
+
415
+ # Compute IoU
416
+ seg_preds = seg_masks.argmax(dim=1)
417
+ intersection = ((seg_preds == 1) & (seg_labels == 1)).sum().item()
418
+ union = ((seg_preds == 1) | (seg_labels == 1)).sum().item()
419
+
420
+ total_loss += loss.item()
421
+ total_iou += intersection / (union + 1e-6)
422
+ num_batches += 1
423
+
424
+ return total_loss / num_batches, total_iou / num_batches
425
+
426
+
427
+ def download_dataset(config):
428
+ """Download and extract dataset"""
429
+ config.data_dir.mkdir(parents=True, exist_ok=True)
430
+ zip_path = config.data_dir / "dataset.zip"
431
+
432
+ if not (config.data_dir / "train").exists():
433
+ print(f"Downloading dataset from {config.data_url}...")
434
+ urllib.request.urlretrieve(config.data_url, zip_path)
435
+
436
+ print("Extracting...")
437
+ with zipfile.ZipFile(zip_path, 'r') as z:
438
+ z.extractall(config.data_dir)
439
+
440
+ # Handle nested zips
441
+ inner_zip = config.data_dir / "DatasetV3.zip"
442
+ if inner_zip.exists():
443
+ with zipfile.ZipFile(inner_zip, 'r') as z:
444
+ z.extractall(config.data_dir)
445
+
446
+ # Extract split zips
447
+ dataset_dir = config.data_dir / "DatasetV3"
448
+ if dataset_dir.exists():
449
+ for split in ["train", "val", "test"]:
450
+ for sz in dataset_dir.glob(f"{split}*.zip"):
451
+ print(f"Extracting {sz.name}...")
452
+ with zipfile.ZipFile(sz, 'r') as z:
453
+ z.extractall(dataset_dir)
454
+
455
+ # Cleanup
456
+ zip_path.unlink(missing_ok=True)
457
+ inner_zip.unlink(missing_ok=True)
458
+
459
+ # Return the correct data directory
460
+ dataset_v3 = config.data_dir / "DatasetV3"
461
+ if dataset_v3.exists():
462
+ return dataset_v3
463
+ return config.data_dir
464
+
465
+
466
+ def main():
467
+ config = Config()
468
+
469
+ # Set seeds
470
+ torch.manual_seed(config.seed)
471
+ np.random.seed(config.seed)
472
+
473
+ # Device
474
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
475
+ print(f"Device: {device}")
476
+ if device.type == "cuda":
477
+ print(f"GPU: {torch.cuda.get_device_name(0)}")
478
+ print(f"Memory: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB")
479
+
480
+ # Download dataset
481
+ data_dir = download_dataset(config)
482
+ print(f"Data directory: {data_dir}")
483
+
484
+ # Create datasets
485
+ train_dataset = UltrasoundDataset(data_dir, "train", config.image_size, augment=True)
486
+ val_dataset = UltrasoundDataset(data_dir, "val", config.image_size, augment=False)
487
+
488
+ if len(val_dataset) == 0:
489
+ print("No validation data, using 10% of train")
490
+ train_size = int(0.9 * len(train_dataset))
491
+ train_dataset, val_dataset = torch.utils.data.random_split(
492
+ train_dataset, [train_size, len(train_dataset) - train_size]
493
+ )
494
+
495
+ train_loader = DataLoader(
496
+ train_dataset, batch_size=config.batch_size, shuffle=True,
497
+ num_workers=4, pin_memory=True, drop_last=True
498
+ )
499
+ val_loader = DataLoader(
500
+ val_dataset, batch_size=config.batch_size, shuffle=False,
501
+ num_workers=4, pin_memory=True
502
+ )
503
+
504
+ print(f"Train: {len(train_dataset)}, Val: {len(val_dataset)}")
505
+
506
+ # Create model
507
+ print(f"Creating model with {config.encoder_name} encoder...")
508
+ model = LaborViewMedSigLIP(config).to(device)
509
+
510
+ # Count parameters
511
+ total_params = sum(p.numel() for p in model.parameters())
512
+ trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
513
+ print(f"Total parameters: {total_params:,}")
514
+ print(f"Trainable parameters: {trainable_params:,}")
515
+
516
+ # Freeze encoder initially for stable training
517
+ model.freeze_encoder()
518
+
519
+ # Optimizer
520
+ optimizer = AdamW(
521
+ filter(lambda p: p.requires_grad, model.parameters()),
522
+ lr=config.learning_rate,
523
+ weight_decay=config.weight_decay
524
+ )
525
+
526
+ # Scheduler
527
+ total_steps = len(train_loader) * config.num_epochs
528
+ scheduler = OneCycleLR(
529
+ optimizer,
530
+ max_lr=config.learning_rate,
531
+ total_steps=total_steps,
532
+ pct_start=config.warmup_epochs / config.num_epochs
533
+ )
534
+
535
+ # Scaler for mixed precision
536
+ scaler = GradScaler("cuda")
537
+
538
+ # Output directory
539
+ config.output_dir.mkdir(parents=True, exist_ok=True)
540
+
541
+ # Training
542
+ best_val_loss = float("inf")
543
+ print("Starting training")
544
+
545
+ for epoch in range(config.num_epochs):
546
+ # Unfreeze encoder after initial epochs
547
+ if epoch == config.freeze_encoder_epochs:
548
+ model.unfreeze_encoder()
549
+ # Recreate optimizer with all parameters
550
+ optimizer = AdamW(
551
+ model.parameters(),
552
+ lr=config.learning_rate * 0.1, # Lower LR for encoder
553
+ weight_decay=config.weight_decay
554
+ )
555
+ scheduler = OneCycleLR(
556
+ optimizer,
557
+ max_lr=config.learning_rate * 0.1,
558
+ total_steps=len(train_loader) * (config.num_epochs - epoch),
559
+ pct_start=0.1
560
+ )
561
+
562
+ train_loss = train_epoch(model, train_loader, optimizer, scheduler, scaler, device, config, epoch)
563
+ val_loss, val_iou = validate(model, val_loader, device)
564
+
565
+ print(f"Epoch {epoch+1}/{config.num_epochs}")
566
+ print(f" Train: {train_loss:.4f}, Val: {val_loss:.4f}, IoU: {val_iou:.4f}")
567
+
568
+ if val_loss < best_val_loss:
569
+ best_val_loss = val_loss
570
+ torch.save({
571
+ "epoch": epoch,
572
+ "model_state_dict": model.state_dict(),
573
+ "val_loss": val_loss,
574
+ "val_iou": val_iou,
575
+ "config": vars(config)
576
+ }, config.output_dir / "best.pt")
577
+ print(" >>> New best!")
578
+
579
+ # Save final model
580
+ torch.save({
581
+ "model_state_dict": model.state_dict(),
582
+ "config": vars(config)
583
+ }, config.output_dir / "final.pt")
584
+
585
+ # Push to Hub
586
+ if config.push_to_hub:
587
+ try:
588
+ from huggingface_hub import HfApi, create_repo
589
+ print(f"Pushing to Hub: {config.hub_model_id}")
590
+ create_repo(config.hub_model_id, exist_ok=True)
591
+ HfApi().upload_folder(
592
+ folder_path=str(config.output_dir),
593
+ repo_id=config.hub_model_id,
594
+ commit_message=f"LaborView MedSigLIP v1 - IoU: {val_iou:.4f}"
595
+ )
596
+ print(f"Uploaded to https://huggingface.co/{config.hub_model_id}")
597
+ except Exception as e:
598
+ print(f"Hub upload failed: {e}")
599
+
600
+ print(f"Training complete! Best Val Loss: {best_val_loss:.4f}")
601
+
602
+
603
+ if __name__ == "__main__":
604
+ main()