Repository navigation
Expand file tree
/
Copy pathm2f_train_cluster_working_backup.py
More file actions
734 lines (600 loc) · 27.8 KB
/
Copy pathm2f_train_cluster_working_backup.py
File metadata and controls
734 lines (600 loc) · 27.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
"""
Training script for Mask2Former Panoptic Segmentation Head ONLY (Cluster Version) - FIXED
Optimized for GPU Cluster (16GB VRAM)
CRITICAL FIXES APPLIED:
- ✅ Added proper data augmentations (multi-scale resize + random flip)
- ✅ Increased CLASS_WEIGHT from 2.0 to 5.0 (balance classification vs mask loss)
- ✅ Fixed LR schedule: Single decay at 70k instead of 60k+80k
- ✅ Added 1000-iter warmup for stable training start
- ✅ Improved projection layers (3-layer semantic alignment adapters)
- ✅ Increased eval/checkpoint frequency (5000 instead of 10000)
- ✅ ARCHITECTURAL FIX: Corrected DPT channel dimensions (uniform 256, not [256,512,1024,2048])
- ✅ Added shape verification debugging for feature extraction
"""
import warnings
# Filter specifically by the content of the message
warnings.filterwarnings("ignore", message=".*torch.cuda.amp.autocast.*", category=FutureWarning)
import torch
import torch.nn as nn
import numpy as np
import os
import sys
from typing import Dict
from PIL import Image
import cv2
import copy
from detectron2.layers import ShapeSpec
from detectron2.config import CfgNode as CN
from detectron2.engine import launch, default_argument_parser
# Detectron2 imports
import detectron2
from detectron2.config import get_cfg
from detectron2.engine import DefaultTrainer, HookBase
from detectron2.data import DatasetCatalog, MetadataCatalog
from detectron2.data import build_detection_train_loader, build_detection_test_loader
from detectron2.data import transforms as T
from detectron2.evaluation import COCOPanopticEvaluator
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.modeling import build_model
from detectron2.modeling import Backbone
import detectron2.utils.comm as comm
# Ensure local mask2former is importable
# Assuming script is run from the project root where 'mask2former' package exists
sys.path.insert(0, os.getcwd())
from mask2former import add_maskformer2_config
from mask2former.modeling.meta_arch.mask_former_head import MaskFormerHead
# MapAnything imports
from mapanything.models import MapAnything
# ============================================================
# NAN CHECK HOOK
# ============================================================
class NaNLossCheckHook(HookBase):
"""
Hook to check for NaN losses during training and exit early if found.
"""
def after_step(self):
if self.trainer.storage.latest().get("total_loss") is None:
return
loss_value = self.trainer.storage.latest()["total_loss"][0]
if torch.isnan(torch.tensor(loss_value)) or torch.isinf(torch.tensor(loss_value)):
raise FloatingPointError(f"Loss became {loss_value} at iteration {self.trainer.iter}. Exiting early.")
# ============================================================
# FROZEN MAPANYTHING BACKBONE (Detectron2-compatible)
# ============================================================
class FrozenMapAnythingBackbone(Backbone):
"""
Detectron2-compatible wrapper for frozen MapAnything backbone.
Extracts multi-scale features from MapAnything's DPT refinenet layers.
"""
def __init__(self, cfg, input_shape):
super().__init__()
# Load pre-trained MapAnything model
mapanything_path = cfg.MODEL.MAPANYTHING.CHECKPOINT_PATH
print(f"Loading frozen MapAnything from: {mapanything_path}")
if not os.path.exists(mapanything_path):
# Fallback for relative path if absolute path fails
if os.path.exists(os.path.abspath(mapanything_path)):
mapanything_path = os.path.abspath(mapanything_path)
else:
raise FileNotFoundError(f"MapAnything checkpoint not found at: {mapanything_path}")
self.mapanything = MapAnything.from_pretrained(
mapanything_path,
local_files_only=True
)
# FREEZE all MapAnything parameters
self.mapanything.eval()
for param in self.mapanything.parameters():
param.requires_grad = False
print("MapAnything loaded and FROZEN")
print(f" Total frozen parameters: {sum(p.numel() for p in self.mapanything.parameters()):,}")
# Storage for features
self.features = {}
self.hooks = []
# Register hooks on DPT refinenet layers
self._register_dpt_hooks()
# Define output feature channels and strides for Detectron2
# CRITICAL FIX: DPT outputs 256 channels for ALL levels (not progressive like ResNet)
# MapAnything uses uniform 256-dim features across all refinenet layers
self._out_feature_channels = {
'res2': 256, # refinenet4 - H/4 - DPT outputs 256
'res3': 256, # refinenet3 - H/8 - DPT outputs 256 (was incorrectly 512)
'res4': 256, # refinenet2 - H/16 - DPT outputs 256 (was incorrectly 1024)
'res5': 256, # refinenet1 - H/32 - DPT outputs 256 (was incorrectly 2048)
}
self._out_feature_strides = {
'res2': 4,
'res3': 8,
'res4': 16,
'res5': 32,
}
self._out_features = ['res2', 'res3', 'res4', 'res5']
# Create trainable projection layers
self._create_projection_layers()
def _create_projection_layers(self):
"""
Create projection layers for channel adaptation.
Since DPT outputs uniform 256 channels, most features just need Identity.
Deep adapters help learn semantic patterns from geometric features.
"""
self.projections = nn.ModuleDict()
dpt_channels = 256
for feat_name, target_channels in self._out_feature_channels.items():
if target_channels != dpt_channels:
# Use 3-layer adapter for non-matching channels
self.projections[feat_name] = nn.Sequential(
# Layer 1: 3x3 conv with same channels
nn.Conv2d(dpt_channels, dpt_channels, kernel_size=3, padding=1),
nn.GroupNorm(32, dpt_channels),
nn.ReLU(inplace=True),
# Layer 2: 3x3 conv to target channels
nn.Conv2d(dpt_channels, target_channels, kernel_size=3, padding=1),
nn.GroupNorm(32, target_channels),
nn.ReLU(inplace=True),
# Layer 3: 1x1 conv for final refinement
nn.Conv2d(target_channels, target_channels, kernel_size=1)
)
else:
# For uniform 256→256, use semantic alignment instead of Identity
# This helps adapt geometric features to semantic features
self.projections[feat_name] = nn.Sequential(
nn.Conv2d(dpt_channels, dpt_channels, kernel_size=3, padding=1),
nn.GroupNorm(32, dpt_channels),
nn.ReLU(inplace=True),
nn.Conv2d(dpt_channels, dpt_channels, kernel_size=3, padding=1),
nn.GroupNorm(32, dpt_channels),
nn.ReLU(inplace=True),
nn.Conv2d(dpt_channels, dpt_channels, kernel_size=1)
)
# Count trainable parameters
total_params = sum(p.numel() for module in self.projections.values()
if not isinstance(module, nn.Identity)
for p in module.parameters())
print(f"Created semantic alignment adapters with {total_params:,} trainable parameters")
print(f" All DPT features are 256-dim → projecting to {list(self._out_feature_channels.values())}")
def _register_dpt_hooks(self):
"""Register hooks on MapAnything's DPT refinenet layers."""
print("\nRegistering hooks on DPT refinenet layers...")
print("Inspecting MapAnything DPT architecture...")
# Debug: Print DPT structure to verify layers
if hasattr(self.mapanything, 'dpt_feature_head'):
print("\nDPT Feature Head structure:")
for name, module in self.mapanything.dpt_feature_head.named_modules():
if 'refinenet' in name and len(list(module.children())) == 0:
print(f" {name}: {module.__class__.__name__}")
mapping = {
'refinenet4': 'res2',
'refinenet3': 'res3',
'refinenet2': 'res4',
'refinenet1': 'res5'
}
self._first_forward = True # Flag for shape debugging
def get_hook(name):
def hook(model, input, output):
self.features[name] = output
# Debug: Print shape on first forward pass
if self._first_forward:
print(f" Captured {name}: shape={output.shape} (C={output.shape[1]})")
return hook
try:
if hasattr(self.mapanything, 'dpt_feature_head'):
scratch = self.mapanything.dpt_feature_head.scratch
for dpt_name, res_name in mapping.items():
if hasattr(scratch, dpt_name):
layer = getattr(scratch, dpt_name)
self.hooks.append(layer.register_forward_hook(get_hook(res_name)))
print(f" Registered hook for {res_name} on {dpt_name}")
if len(self.hooks) == 0:
print(" WARNING: No hooks were registered!")
else:
print(f" Successfully registered {len(self.hooks)} hooks")
else:
print("WARNING: dpt_feature_head not found! Check MapAnything structure.")
except AttributeError as e:
print(f"Error accessing DPT layers: {e}. Check model structure.")
def forward(self, x):
"""Forward pass compatible with Detectron2."""
self.features = {}
batch_size, _, orig_h, orig_w = x.shape
# Debug: Print input shape on first forward
if self._first_forward:
print(f"\nMapAnything Backbone Forward Pass:")
print(f" Input shape: {x.shape}")
# DINOv2 requires dimensions divisible by patch_size (14)
patch_size = 14
pad_h = (patch_size - orig_h % patch_size) % patch_size
pad_w = (patch_size - orig_w % patch_size) % patch_size
if pad_h > 0 or pad_w > 0:
x = torch.nn.functional.pad(x, (0, pad_w, 0, pad_h), mode='constant', value=0)
if self._first_forward:
print(f" Padded to: {x.shape} (for DINOv2 patch_size={patch_size})")
views = []
for i in range(batch_size):
view = {
'img': x[i:i+1],
'data_norm_type': ['dinov2'],
'instance': [f'view_{i}'],
'idx': [i],
}
views.append(view)
with torch.no_grad():
try:
_ = self.mapanything(views)
except torch.cuda.OutOfMemoryError as e:
# If OOM in dense head, that's okay - hooks already captured features
torch.cuda.empty_cache()
except Exception as e:
print(f"Warning: MapAnything forward failed: {e}")
output_features = {}
if not self.features:
raise RuntimeError("No features were captured from MapAnything!")
if self._first_forward:
print(f"\n DPT Features Captured:")
for feat_name in self._out_features:
if feat_name not in self.features:
continue
feat = self.features[feat_name]
if pad_h > 0 or pad_w > 0:
stride = self._out_feature_strides[feat_name]
target_h = orig_h // stride
target_w = orig_w // stride
feat = feat[:, :, :target_h, :target_w]
feat = self.projections[feat_name](feat)
output_features[feat_name] = feat
if self._first_forward:
print(f" {feat_name}: {feat.shape} (stride={self._out_feature_strides[feat_name]})")
if not output_features:
raise RuntimeError("No output features produced!")
if self._first_forward:
print(f" ✓ All features extracted successfully\n")
self._first_forward = False
return output_features
def output_shape(self):
return {
name: ShapeSpec(
channels=self._out_feature_channels[name],
stride=self._out_feature_strides[name]
)
for name in self._out_features
}
def train(self, mode=True):
super().train(mode)
self.mapanything.eval()
for proj in self.projections.values():
if not isinstance(proj, nn.Identity):
proj.train(mode)
return self
@property
def size_divisibility(self):
return 32
# ============================================================
# REGISTER MAPANYTHING BACKBONE TO DETECTRON2
# ============================================================
from detectron2.modeling.backbone import BACKBONE_REGISTRY
@BACKBONE_REGISTRY.register()
def build_mapanything_backbone(cfg, input_shape):
return FrozenMapAnythingBackbone(cfg, input_shape)
# ============================================================
# CUSTOM TRAINER FOR PANOPTIC SEGMENTATION
# ============================================================
class Mask2FormerPanopticTrainer(DefaultTrainer):
"""
Custom trainer for Mask2Former panoptic segmentation.
"""
def build_hooks(self):
"""Add custom hooks"""
hooks = super().build_hooks()
hooks.append(NaNLossCheckHook())
return hooks
@classmethod
def build_evaluator(cls, cfg, dataset_name, output_folder=None):
if output_folder is None:
output_folder = os.path.join(cfg.OUTPUT_DIR, "inference")
return COCOPanopticEvaluator(dataset_name, output_folder)
@classmethod
def build_train_loader(cls, cfg):
from mask2former.data.dataset_mappers.mask_former_panoptic_dataset_mapper import (
MaskFormerPanopticDatasetMapper,
)
# CRITICAL FIX: Add proper data augmentations!
augmentations = [
T.ResizeShortestEdge(
short_edge_length=(640, 672, 704, 736, 768, 800),
max_size=1333,
sample_style="choice"
),
T.RandomFlip(prob=0.5, horizontal=True, vertical=False),
]
print("="*60)
print("DATA AUGMENTATIONS ENABLED:")
print(" - Multi-scale resize: [640-800] -> max 1333")
print(" - Random horizontal flip: 50% probability")
print("="*60)
mapper = MaskFormerPanopticDatasetMapper(
is_train=True,
augmentations=augmentations, # ← FIXED: No longer empty!
image_format=cfg.INPUT.FORMAT,
ignore_label=cfg.MODEL.SEM_SEG_HEAD.IGNORE_VALUE,
size_divisibility=cfg.MODEL.MASK_FORMER.SIZE_DIVISIBILITY,
)
return build_detection_train_loader(cfg, mapper=mapper)
@classmethod
def build_test_loader(cls, cfg, dataset_name):
return build_detection_test_loader(cfg, dataset_name)
def resume_or_load(self, resume=True):
super().resume_or_load(resume=resume)
model = self.model
if isinstance(model, (torch.nn.parallel.DistributedDataParallel, torch.nn.parallel.DataParallel)):
model = model.module
if hasattr(model, "backbone") and isinstance(model.backbone, FrozenMapAnythingBackbone):
print("Re-freezing MapAnything backbone parameters...")
model.backbone.mapanything.eval()
for param in model.backbone.mapanything.parameters():
param.requires_grad = False
for proj in model.backbone.projections.values():
if not isinstance(proj, nn.Identity):
proj.train()
for param in proj.parameters():
param.requires_grad = True
print("Backbone re-frozen, deep adapters trainable.")
# ============================================================
# SETUP CONFIGURATION
# ============================================================
def setup_cfg(
mapanything_checkpoint_path: str,
coco_root: str,
output_dir: str,
num_gpus: int = 1,
batch_size: int = 2,
learning_rate: float = 1e-4,
max_iter: int = 90000,
):
cfg = get_cfg()
add_maskformer2_config(cfg)
# ===== MODEL ARCHITECTURE =====
cfg.MODEL.META_ARCHITECTURE = "MaskFormer"
cfg.MODEL.WEIGHTS = ""
cfg.MODEL.PIXEL_MEAN = [123.675, 116.280, 103.530]
cfg.MODEL.PIXEL_STD = [58.395, 57.120, 57.375]
# ===== BACKBONE CONFIGURATION =====
cfg.MODEL.BACKBONE.NAME = "build_mapanything_backbone"
cfg.MODEL.BACKBONE.FREEZE_AT = 0
cfg.MODEL.MAPANYTHING = CN()
cfg.MODEL.MAPANYTHING.CHECKPOINT_PATH = mapanything_checkpoint_path
cfg.MODEL.BACKBONE.OUT_FEATURES = ["res2", "res3", "res4", "res5"]
# ===== MASK2FORMER HEAD CONFIGURATION =====
cfg.MODEL.SEM_SEG_HEAD.NAME = "MaskFormerHead"
cfg.MODEL.SEM_SEG_HEAD.IGNORE_VALUE = 255
cfg.MODEL.SEM_SEG_HEAD.NUM_CLASSES = 133
cfg.MODEL.SEM_SEG_HEAD.LOSS_WEIGHT = 1.0
cfg.MODEL.SEM_SEG_HEAD.CONVS_DIM = 256
cfg.MODEL.SEM_SEG_HEAD.MASK_DIM = 256
cfg.MODEL.SEM_SEG_HEAD.NORM = "GN"
# ===== PIXEL DECODER CONFIGURATION =====
cfg.MODEL.SEM_SEG_HEAD.PIXEL_DECODER_NAME = "MSDeformAttnPixelDecoder"
cfg.MODEL.SEM_SEG_HEAD.IN_FEATURES = ["res2", "res3", "res4", "res5"]
cfg.MODEL.SEM_SEG_HEAD.DEFORMABLE_TRANSFORMER_ENCODER_IN_FEATURES = ["res3", "res4", "res5"]
cfg.MODEL.SEM_SEG_HEAD.COMMON_STRIDE = 4
cfg.MODEL.SEM_SEG_HEAD.TRANSFORMER_ENC_LAYERS = 6
# ===== MASK FORMER DECODER CONFIGURATION =====
cfg.MODEL.MASK_FORMER.TRANSFORMER_DECODER_NAME = "MultiScaleMaskedTransformerDecoder"
cfg.MODEL.MASK_FORMER.TRANSFORMER_IN_FEATURE = "multi_scale_pixel_decoder"
cfg.MODEL.MASK_FORMER.DEEP_SUPERVISION = True
cfg.MODEL.MASK_FORMER.NO_OBJECT_WEIGHT = 0.1
cfg.MODEL.MASK_FORMER.CLASS_WEIGHT = 5.0 # ← FIXED: Increased from 2.0 to 5.0
cfg.MODEL.MASK_FORMER.MASK_WEIGHT = 5.0
cfg.MODEL.MASK_FORMER.DICE_WEIGHT = 5.0
cfg.MODEL.MASK_FORMER.HIDDEN_DIM = 256
cfg.MODEL.MASK_FORMER.NUM_OBJECT_QUERIES = 100
cfg.MODEL.MASK_FORMER.NHEADS = 8
cfg.MODEL.MASK_FORMER.DROPOUT = 0.0
cfg.MODEL.MASK_FORMER.DIM_FEEDFORWARD = 2048
cfg.MODEL.MASK_FORMER.ENC_LAYERS = 0
cfg.MODEL.MASK_FORMER.DEC_LAYERS = 9
cfg.MODEL.MASK_FORMER.PRE_NORM = False
cfg.MODEL.MASK_FORMER.ENFORCE_INPUT_PROJ = False
cfg.MODEL.MASK_FORMER.SIZE_DIVISIBILITY = 32
cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON = True
cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON = True
cfg.MODEL.MASK_FORMER.TEST.PANOPTIC_ON = True
cfg.MODEL.MASK_FORMER.TEST.OBJECT_MASK_THRESHOLD = 0.8
cfg.MODEL.MASK_FORMER.TEST.OVERLAP_THRESHOLD = 0.8
cfg.MODEL.MASK_FORMER.TEST.SEM_SEG_POSTPROCESSING_BEFORE_INFERENCE = False
# ===== INPUT CONFIGURATION =====
cfg.INPUT.IMAGE_SIZE = 1024
cfg.INPUT.MIN_SCALE = 0.1
cfg.INPUT.MAX_SCALE = 2.0
cfg.INPUT.FORMAT = "RGB"
cfg.INPUT.DATASET_MAPPER_NAME = "mask_former_panoptic"
# ===== DATASET CONFIGURATION =====
cfg.DATASETS.TRAIN = ("coco_2017_train_panoptic",)
cfg.DATASETS.TEST = ("coco_2017_val_panoptic",)
# ===== TRAINING CONFIGURATION =====
cfg.SOLVER.IMS_PER_BATCH = batch_size * num_gpus
cfg.SOLVER.BASE_LR = learning_rate
cfg.SOLVER.MAX_ITER = max_iter
# FIXED LR schedule: Single decay at 70k instead of 60k+80k
cfg.SOLVER.STEPS = (70000,) # ← FIXED: Single step at 70k
cfg.SOLVER.GAMMA = 0.1
cfg.SOLVER.OPTIMIZER = "ADAMW"
cfg.SOLVER.WEIGHT_DECAY = 0.05
cfg.SOLVER.BACKBONE_MULTIPLIER = 0.1
# Add warmup for stable training start
cfg.SOLVER.WARMUP_ITERS = 1000 # ← NEW: 1000 iteration warmup
cfg.SOLVER.WARMUP_FACTOR = 0.001 # ← NEW: Start from LR/1000
cfg.SOLVER.WARMUP_METHOD = "linear"
cfg.SOLVER.CLIP_GRADIENTS.ENABLED = True
cfg.SOLVER.CLIP_GRADIENTS.CLIP_TYPE = "norm"
cfg.SOLVER.CLIP_GRADIENTS.CLIP_VALUE = 1.0
cfg.SOLVER.CLIP_GRADIENTS.NORM_TYPE = 2.0
cfg.SOLVER.AMP.ENABLED = True
# ===== EVALUATION CONFIGURATION =====
cfg.TEST.EVAL_PERIOD = 5000 # ← More frequent eval to monitor progress
# ===== OUTPUT CONFIGURATION =====
cfg.OUTPUT_DIR = output_dir
os.makedirs(cfg.OUTPUT_DIR, exist_ok=True)
cfg.SOLVER.CHECKPOINT_PERIOD = 5000 # ← More frequent checkpoints
cfg.DATALOADER.NUM_WORKERS = 16 # Increased for cluster
cfg.DATALOADER.FILTER_EMPTY_ANNOTATIONS = False
cfg.MODEL.DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
cfg.VERSION = 2
print("\n" + "="*60)
print("IMPROVED HYPERPARAMETERS APPLIED:")
print(f" CLASS_WEIGHT: 5.0 (was 2.0) - Better classification")
print(f" LR Schedule: Decay at 70k (was 60k+80k)")
print(f" Warmup: 1000 iters from LR={learning_rate*0.001:.2e}")
print(f" Eval Period: 5000 (was 10000)")
print(f" Checkpoint Period: 5000 (was 10000)")
print(f" Semantic Alignment: 3-layer adapters for all features")
print(f" ⚠️ ARCHITECTURAL FIX: DPT uniform 256-dim channels")
print("="*60 + "\n")
return cfg
# ============================================================
# REGISTER COCO PANOPTIC DATASET
# ============================================================
def register_coco_panoptic(coco_root: str):
"""Register COCO panoptic dataset with Detectron2."""
from detectron2.data.datasets import register_coco_panoptic
coco_root = os.path.abspath(coco_root)
train_images = os.path.join(coco_root, "train2017")
val_images = os.path.join(coco_root, "val2017")
if not os.path.exists(train_images):
raise FileNotFoundError(f"Training images not found: {train_images}")
if not os.path.exists(val_images):
raise FileNotFoundError(f"Validation images not found: {val_images}")
print(f"Found training images: {train_images}")
print(f"Found validation images: {val_images}")
# Register training set
if "coco_2017_train_panoptic" not in DatasetCatalog:
register_coco_panoptic(
name="coco_2017_train_panoptic",
metadata={},
image_root=train_images,
panoptic_root=os.path.join(coco_root, "panoptic_train2017"),
panoptic_json=os.path.join(coco_root, "annotations/panoptic_train2017.json"),
instances_json=os.path.join(coco_root, "annotations/instances_train2017.json"),
)
# Register validation set
if "coco_2017_val_panoptic" not in DatasetCatalog:
register_coco_panoptic(
name="coco_2017_val_panoptic",
metadata={},
image_root=val_images,
panoptic_root=os.path.join(coco_root, "panoptic_val2017"),
panoptic_json=os.path.join(coco_root, "annotations/panoptic_val2017.json"),
instances_json=os.path.join(coco_root, "annotations/instances_val2017.json"),
)
print("COCO panoptic dataset registered")
# ============================================================
# MAIN TRAINING FUNCTION
# ============================================================
def train_panoptic_segmentation_head(
mapanything_checkpoint: str,
coco_root: str,
output_dir: str = "./output_panoptic",
num_gpus: int = 1,
batch_size: int = 2,
learning_rate: float = 1e-4,
max_iter: int = 90000,
resume: bool = False,
):
print("="*80)
print("MASK2FORMER PANOPTIC SEGMENTATION HEAD TRAINING - FIXED VERSION")
print("="*80)
print(f"\nConfiguration:")
print(f" MapAnything checkpoint: {mapanything_checkpoint}")
print(f" COCO root: {coco_root}")
print(f" Output directory: {output_dir}")
print(f" GPUs: {num_gpus}")
print(f" Batch size: {batch_size}")
print(f" Learning rate: {learning_rate}")
print(f" Max iterations: {max_iter}")
# Register COCO panoptic dataset
register_coco_panoptic(coco_root)
# Setup config
cfg = setup_cfg(
mapanything_checkpoint_path=mapanything_checkpoint,
coco_root=coco_root,
output_dir=output_dir,
num_gpus=num_gpus,
batch_size=batch_size,
learning_rate=learning_rate,
max_iter=max_iter,
)
# Build model
print("\nBuilding model...")
model = build_model(cfg)
# Create trainer
print("\nStarting training...")
trainer = Mask2FormerPanopticTrainer(cfg)
trainer.resume_or_load(resume=resume)
# Train!
trainer.train()
print("\n" + "="*80)
print("TRAINING COMPLETE!")
print("="*80)
# ============================================================
# MAIN ENTRY POINT
# ============================================================
def main(args):
"""Wrapper function for multi-GPU launch"""
train_panoptic_segmentation_head(
mapanything_checkpoint=args.map_anything_checkpoint,
coco_root=args.coco_root,
output_dir=args.output_dir,
num_gpus=args.num_gpus,
batch_size=args.batch_size,
learning_rate=args.learning_rate,
max_iter=args.max_iter,
)
if __name__ == "__main__":
# ===== RELATIVE PATH CONFIGURATION =====
# Assumes script is run from project root
BASE_DIR = os.getcwd()
# 1. MapAnything Checkpoint
# Expected: ./pretrained_models/map_anything/test
MAPANYTHING_CHECKPOINT = os.path.join(BASE_DIR, "pretrained_models", "map_anything", "test")
# 2. COCO Dataset
# Expected: ./datasets/coco
COCO_ROOT = os.path.join(BASE_DIR, "datasets", "coco")
# 3. Output Directory
OUTPUT_DIR = os.path.join(BASE_DIR, "output_cluster")
# ===== CLUSTER HYPERPARAMETERS =====
# Optimized for 16GB VRAM (Nvidia V100)
# NUM_GPUS = torch.cuda.device_count()
# Batch size logic based on GPU type
# V100 (16GB): Batch size 2 per GPU
# A100 (80GB): Batch size 8-10 per GPU
gpu_name = torch.cuda.get_device_name(0) if torch.cuda.is_available() else "CPU"
print(f"Detected GPU: {gpu_name}")
if "A100" in gpu_name:
BATCH_SIZE = 8 # Aggressive batch size for 80GB A100
print(f"Configuring for A100 (80GB): Batch size {BATCH_SIZE}")
else:
BATCH_SIZE = 4 # Conservative batch size for V100 (16GB)
print(f"Configuring for V100 (16GB): Batch size {BATCH_SIZE}")
LEARNING_RATE = 1e-4
MAX_ITER = 90000
# Check if paths exist
if not os.path.exists(MAPANYTHING_CHECKPOINT):
print(f"WARNING: MapAnything checkpoint not found at {MAPANYTHING_CHECKPOINT}")
print(" Please ensure 'pretrained_models/map_anything/test' exists.")
if not os.path.exists(COCO_ROOT):
print(f"WARNING: COCO dataset not found at {COCO_ROOT}")
print(" Please ensure 'datasets/coco' exists.")
args = default_argument_parser().parse_args()
args.coco_root = COCO_ROOT
args.output_dir = OUTPUT_DIR
args.batch_size = BATCH_SIZE
args.learning_rate = LEARNING_RATE
args.max_iter = MAX_ITER
args.map_anything_checkpoint = MAPANYTHING_CHECKPOINT
print("Command Line Args:", args)
# Launch multi-GPU training
launch(
main, # Function to run
args.num_gpus, # Number of GPUs
num_machines=1, # Number of machines (1 for single node)
machine_rank=0, # This machine's rank (0 for single node)
dist_url="auto", # Automatically find a free port
args=(args,), # Pass args to main()
)