devyggdramir commited on
Commit
0d009bf
·
verified ·
1 Parent(s): 65d1f61

Task 1.1 (Image-based) Modal Mask -> Amodal Mask

Browse files

Last change to be made soon: Make a better filter at the beginning of the model to optimize training and testing data

Files changed (2) hide show
  1. Task1_1/Tast1_1.py +589 -0
  2. Task1_1/best_model.pth +3 -0
Task1_1/Tast1_1.py ADDED
@@ -0,0 +1,589 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Standard Library Imports
2
+ import os #
3
+ import shutil # provides high level file operations (copying, deleting, moving files/directories)
4
+ import tarfile # allows working with tar archives (compressed or uncompressed)
5
+ import random # provides functions for generating random numbers, shuffling squences, etc.
6
+ import cv2 # imports OpenCV Library functions used to read, display, or capture video (Face detection, object tracking, image processing)
7
+ import glob # Finds files/paths matching specified patterns (like *.jpg)
8
+ # ---------------------------------------------------------------------------------------------------------------------------------------------------------------------
9
+ # Hugging Face Hub
10
+ from huggingface_hub import HfApi, hf_hub_download # the api allows allows interaction with hugging face hub (upload/download models, datasets)
11
+ # the hub_download lets you download files from Hugging Face hub (model weights, datasets)
12
+ # ---------------------------------------------------------------------------------------------------------------------------------------------------------------------
13
+ # PyTorch Ecosystem
14
+ import torch # Core PyTorch Library for tensor operations and nueral networks
15
+ from torch import nn # contains nueral network layers, loss functions, and utilities (nn.Linear, nn.ReLU)
16
+ from torch.utils.data import Dataset, DataLoader # Dataset: Abstract class for Custom Datasets // DataLoader: Efficient data loading/batching(supports multiprocessing)
17
+ import torchvision.transforms as transforms # preprocessing utilities for images (resizing, normalization, augmentation)
18
+ from torchvision.utils import make_grid # creates a grid of images (useful for visualing grids)
19
+ import torch.nn.functional as F # PyTorches functional interface for neural network operations
20
+ # ---------------------------------------------------------------------------------------------------------------------------------------------------------------------
21
+ # Image and Numerical Processing
22
+ from PIL import Image # Python Imaging Library (Pillow) for image manipulation (open, save, resize, etc.)
23
+ import numpy as np # NumPy for numerical operations (arrays, linear algebra, etc.)
24
+ # ---------------------------------------------------------------------------------------------------------------------------------------------------------------------
25
+ # Visualization
26
+ import matplotlib.pyplot as plt # Matplotlib for plotting graphs and displaying Images
27
+ from tabulate import tabulate # Pretty-print tabular data
28
+ # ---------------------------------------------------------------------------------------------------------------------------------------------------------------------
29
+
30
+ def compute_occlusion(rgba_path, seg_path):
31
+ """Calculate precise occlusion percentage (0-1) between modal and amodal masks"""
32
+ try:
33
+ # Load masks with validation
34
+ seg = cv2.imread(seg_path, cv2.IMREAD_GRAYSCALE)
35
+ rgba = cv2.imread(rgba_path, cv2.IMREAD_UNCHANGED)
36
+
37
+ if seg is None or rgba is None or rgba.shape[2] != 4:
38
+ return None
39
+
40
+ # Create binary masks
41
+ modal_mask = (seg > 0).astype(np.uint8)
42
+ amodal_mask = (rgba[:,:,3] > 0).astype(np.uint8)
43
+
44
+ # Calculate occlusion ratio with edge case handling
45
+ visible_pixels = np.sum(modal_mask)
46
+ total_pixels = np.sum(amodal_mask)
47
+
48
+ if total_pixels == 0: # Invalid case (no object)
49
+ return None
50
+
51
+ occlusion = 1 - (visible_pixels / total_pixels)
52
+
53
+ # Special handling for boundary cases
54
+ if visible_pixels == 0:
55
+ return 1.0 # 100% occluded
56
+ if visible_pixels == total_pixels:
57
+ return 0.0 # 0% occluded
58
+
59
+ return occlusion
60
+
61
+ except Exception as e:
62
+ print(f"Error processing {seg_path}: {str(e)}")
63
+ return None
64
+
65
+ def filter_scenes(root_dir, min_occ=0.25, max_occ=0.75):
66
+ """Strictly filter scenes to only keep 25%-75% occlusion"""
67
+ kept = removed = invalid = empty = 0
68
+
69
+ for scene_dir in glob.glob(os.path.join(root_dir, "*")):
70
+ if not os.path.isdir(scene_dir):
71
+ continue
72
+
73
+ scene_valid = True
74
+ camera_dirs = list(glob.glob(os.path.join(scene_dir, "camera_*")))
75
+
76
+ for cam_dir in camera_dirs:
77
+ if not os.path.isdir(cam_dir):
78
+ continue
79
+
80
+ rgba_files = sorted(glob.glob(os.path.join(cam_dir, "rgba_*.png")))
81
+ seg_files = sorted(glob.glob(os.path.join(cam_dir, "segmentation_*.png")))
82
+
83
+ if not rgba_files or not seg_files:
84
+ invalid += 1
85
+ scene_valid = False
86
+ break
87
+
88
+ # Check multiple frames
89
+ valid_frames = 0
90
+ for rgba, seg in zip(rgba_files[:3], seg_files[:3]):
91
+ seg_img = cv2.imread(seg, cv2.IMREAD_GRAYSCALE)
92
+ rgba_img = cv2.imread(rgba, cv2.IMREAD_UNCHANGED)
93
+
94
+ # Skip empty masks
95
+ if np.sum(seg_img > 0) == 0 or np.sum(rgba_img[..., 3] > 0) == 0:
96
+ empty += 1
97
+ continue
98
+
99
+ occ = compute_occlusion(rgba, seg)
100
+ if occ is None or not (min_occ <= occ <= max_occ):
101
+ continue
102
+
103
+ valid_frames += 1
104
+
105
+ # Require at least 2 valid frames per camera
106
+ if valid_frames < 2:
107
+ scene_valid = False
108
+ break
109
+
110
+ if scene_valid:
111
+ kept += len(camera_dirs)
112
+ else:
113
+ removed += len(camera_dirs)
114
+ shutil.rmtree(scene_dir)
115
+
116
+ print(f"\n=== Filter Results ===")
117
+ print(f"Kept: {kept} cameras in valid scenes")
118
+ print(f"Removed: {removed} cameras")
119
+ print(f"Invalid: {invalid} (missing files)")
120
+ print(f"Empty: {empty} (zero-pixel masks)")
121
+
122
+ def download_and_process(sample_pct=0.0125, min_occ=0.25, max_occ=0.75):
123
+ """Download and process dataset with strict occlusion filtering"""
124
+ api = HfApi()
125
+ repo_id = "Amar-S/MOVi-MC-AC"
126
+ os.makedirs("/content/data/train", exist_ok=True)
127
+ os.makedirs("/content/data/test", exist_ok=True)
128
+
129
+ def process_files(files, dest):
130
+ for f in random.sample(files, max(1, int(len(files) * sample_pct))):
131
+ try:
132
+ path = hf_hub_download(repo_id=repo_id, filename=f, repo_type="dataset")
133
+ dest_path = os.path.join(dest, os.path.basename(f))
134
+ shutil.copy(path, dest_path)
135
+ with tarfile.open(dest_path, 'r:gz') as tar:
136
+ tar.extractall(dest)
137
+ os.remove(dest_path)
138
+ except Exception as e:
139
+ print(f"Error processing {f}: {e}")
140
+
141
+ files = api.list_repo_files(repo_id=repo_id, repo_type="dataset")
142
+ train_files = [f for f in files if f.startswith("train/") and f.endswith(".tar.gz")]
143
+ test_files = [f for f in files if f.startswith("test/") and f.endswith(".tar.gz")]
144
+
145
+ process_files(train_files, "/content/data/train")
146
+ process_files(test_files, "/content/data/test")
147
+
148
+ print("Filtering training data...")
149
+ filter_scenes("/content/data/train", min_occ, max_occ)
150
+
151
+ print("\nFiltering test data...")
152
+ filter_scenes("/content/data/test", min_occ, max_occ)
153
+
154
+ download_and_process(min_occ=0.25, max_occ=0.75)
155
+
156
+ # Load checkpoint
157
+ def load_checkpoint(filename, model, optimizer=None, device='cuda'):
158
+ """Load model checkpoint"""
159
+ checkpoint = torch.load(filename, map_location=device)
160
+ model.load_state_dict(checkpoint['model_state_dict'])
161
+
162
+ if optimizer is not None:
163
+ optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
164
+
165
+ epoch = checkpoint['epoch']
166
+ train_metrics = checkpoint['train_metrics']
167
+ val_metrics = checkpoint['val_metrics']
168
+
169
+ print(f"Loaded checkpoint from epoch {epoch + 1}")
170
+ return model, optimizer, epoch, train_metrics, val_metrics
171
+
172
+ # get_img_dict
173
+ # 1. Takes a list of images
174
+ # 2. Groups them by the first part of their filename (before the first underscore)
175
+ # 3. Stores these groups in a dictionary where:
176
+ # - Keys are the image types (prefixes)
177
+ # - Values are lists of all files sharing that prefix
178
+ # essentially sorting them alphebetically
179
+
180
+ def get_img_dict(img_dir): # Function call
181
+ img_files = [x for x in img_dir.iterdir() if x.name.endswith('.png') or x.name.endswith('.tiff')] # img_files is the goes through the image directory and adds any .png or .tiff files into the img_files variables
182
+ img_files.sort() # sorts to ensure consistent ordering
183
+
184
+ img_dict = {} # dictionary to store grouped images by prefix
185
+
186
+ for img_file in img_files:
187
+ img_type = img_file.name.split('_')[0] # splits file names from cat_123 to cat 123 and takes the first index = cat and assigns it to img_type, in all cat_123.jpg becomes cat
188
+ if img_type not in img_dict: # checks the dictionary to see if it is already in the dictionary
189
+ img_dict[img_type] = [] # if not, it initializes it with an empty list as its value
190
+ img_dict[img_type].append(img_file) # if it is, it adds to that associated list with its img_type in the dictionary
191
+
192
+ return img_dict # returns the dictionary as output
193
+
194
+ # get_sample_dict
195
+
196
+ def get_sample_dict(sample_dir): # Function call
197
+
198
+
199
+ camera_dirs = [x for x in sample_dir.iterdir() if 'camera' in x.name] # get all directories with camera in their name only (camera1, camera2, ...)
200
+ camera_dirs.sort() # again, sorts for consistent ordering
201
+
202
+ sample_dict = {} # Top level dictionary to story camera-wise data
203
+
204
+ for cam_dir in camera_dirs: # for each cam_directory in camera directories
205
+ cam_dict = {} # Dictionary for this specific camera
206
+ cam_dict['scene'] = get_img_dict(cam_dir) # groups scene images by prefix
207
+
208
+ obj_dirs = [x for x in cam_dir.iterdir() if 'obj_' in x.name] # get all object directories (obj_0001, obj_0002, ...)
209
+ obj_dirs.sort() # sorts for consistent ordering
210
+
211
+ for obj_dir in obj_dirs: # for each object directory in object directories
212
+ cam_dict[obj_dir.name] = get_img_dict(obj_dir) # group images in this object directory by prefix and store under the objects name
213
+
214
+ sample_dict[cam_dir.name] = cam_dict # add this cameras data to the sample_dict
215
+
216
+ return sample_dict # returns a nested dictionary like: {'camera': {'scene': {...}, 'obj_1': ...}}
217
+
218
+ # make_obj_viz --> Video
219
+ # make_vid --> Video
220
+ class ModalAmodalDataset(Dataset):
221
+ @staticmethod
222
+ def get_default_transform(img_size):
223
+ return transforms.Compose([transforms.Resize(img_size), transforms.ToTensor(),])
224
+
225
+ def __init__(self, root_dir, split, transform=None, img_size=(256, 256)):
226
+ self.root_dir = root_dir
227
+ self.split = split
228
+ self.img_size = img_size
229
+ self.transform = transform or self.get_default_transform(img_size)
230
+ self.samples = self._build_sample_index()
231
+
232
+ def _build_sample_index(self):
233
+ samples = []
234
+ split_dir = os.path.join(self.root_dir, self.split)
235
+
236
+ with os.scandir(split_dir) as scene_entries:
237
+ for scene_entry in scene_entries:
238
+ if not scene_entry.is_dir():
239
+ continue
240
+
241
+ with os.scandir(scene_entry.path) as camera_entries:
242
+ for camera_entry in camera_entries:
243
+ if not camera_entry.is_dir() or not camera_entry.name.startswith('camera_'):
244
+ continue
245
+
246
+ # Get all RGBA images
247
+ rgba_files = [f.path for f in os.scandir(camera_entry.path)
248
+ if f.name.startswith('rgba_') and f.name.endswith('.png')]
249
+
250
+ for obj_entry in os.scandir(camera_entry.path):
251
+ if not obj_entry.is_dir() or not obj_entry.name.startswith('obj_'):
252
+ continue
253
+
254
+ try:
255
+ obj_id = int(obj_entry.name.split('_')[1])
256
+ except:
257
+ continue
258
+
259
+ for rgba_file in rgba_files:
260
+ frame_name = os.path.basename(rgba_file)[5:-4] # removes 'rgba_' and '.png'
261
+ seg_file = os.path.join(camera_entry.path, f'segmentation_{frame_name}.png')
262
+ amodal_file = os.path.join(obj_entry.path, f'segmentation_{frame_name}.png')
263
+
264
+ if os.path.exists(seg_file) and os.path.exists(amodal_file):
265
+ samples.append({
266
+ 'rgb_path': rgba_file,
267
+ 'segmentation_path': seg_file,
268
+ 'amodal_path': amodal_file,
269
+ 'object_id': obj_id,
270
+ 'frame_id': frame_name,
271
+ 'scene': scene_entry.name,
272
+ 'camera': camera_entry.name
273
+ })
274
+ return samples
275
+
276
+ def __len__(self):
277
+ return len(self.samples)
278
+
279
+ def __getitem__(self, idx):
280
+ max_attempts = 5 # Maximum tries to find valid sample
281
+ attempt = 0
282
+
283
+ while attempt < max_attempts:
284
+ sample = self.samples[idx]
285
+
286
+ # Load images
287
+ rgb_image = Image.open(sample['rgb_path']).convert('RGB')
288
+ panoptic_seg = Image.open(sample['segmentation_path'])
289
+
290
+ # Create modal mask
291
+ modal_mask = (np.array(panoptic_seg) == sample['object_id']).astype(np.uint8) * 255
292
+ modal_mask = Image.fromarray(modal_mask)
293
+
294
+ # Load amodal mask
295
+ amodal_mask = Image.open(sample['amodal_path']).convert('L')
296
+ amodal_mask = amodal_mask.point(lambda x: 255 if x > 128 else 0)
297
+
298
+ # Apply transforms
299
+ rgb_tensor = self.transform(rgb_image)
300
+ modal_tensor = self.transform(modal_mask)[:1]
301
+ amodal_tensor = self.transform(amodal_mask)[:1]
302
+
303
+ # Check for empty masks
304
+ modal_pixels = torch.sum(modal_tensor > 0.5)
305
+ amodal_pixels = torch.sum(amodal_tensor > 0.5)
306
+
307
+ if modal_pixels == 0 and amodal_pixels == 0:
308
+ # Skip this sample and try another
309
+ idx = random.randint(0, len(self)-1)
310
+ attempt += 1
311
+ continue
312
+
313
+ return {
314
+ 'rgb': rgb_tensor,
315
+ 'modal_mask': modal_tensor,
316
+ 'amodal_mask': amodal_tensor,
317
+ 'object_id': sample['object_id'],
318
+ 'frame_id': sample['frame_id'],
319
+ 'scene': sample['scene'],
320
+ 'camera': sample['camera'],
321
+ 'amodal_path': sample['amodal_path']
322
+ }
323
+
324
+ # If all attempts fail, return first sample
325
+ return self.__getitem__(0)
326
+
327
+ def create_dataloader(root_dir, split, batch_size=4, shuffle=True, num_workers=4, img_size=(224, 224)):
328
+ dataset = ModalAmodalDataset(root_dir=root_dir, split=split, img_size=img_size)
329
+ return DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers, pin_memory=torch.cuda.is_available())
330
+ class conv2d_inplace_spatial(nn.Module):
331
+ """Double convolution block with optional pooling"""
332
+ def __init__(self, in_channels, out_channels, pooling_function=None, activation=nn.GELU(), kernel_size=3, padding=1):
333
+ super().__init__()
334
+ self.double_conv = nn.Sequential(
335
+ nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, padding=padding),
336
+ nn.BatchNorm2d(out_channels),
337
+ activation,
338
+ nn.Conv2d(out_channels, out_channels, kernel_size=kernel_size, padding=padding),
339
+ nn.BatchNorm2d(out_channels),
340
+ activation,
341
+ )
342
+ self.pooling = pooling_function if isinstance(pooling_function, nn.Module) else None
343
+
344
+ def forward(self, x):
345
+ x = self.double_conv(x)
346
+ if self.pooling is not None:
347
+ x = self.pooling(x)
348
+ return x
349
+
350
+ class Upscale(nn.Module):
351
+ def __init__(self, scale_factor=2, mode='bilinear', align_corners=False):
352
+ super().__init__()
353
+ self.scale_factor = scale_factor
354
+ self.mode = mode
355
+ self.align_corners = align_corners
356
+
357
+ def forward(self, x):
358
+ return F.interpolate(x, scale_factor=self.scale_factor,
359
+ mode=self.mode, align_corners=self.align_corners)
360
+
361
+ class Unet_Image(nn.Module):
362
+ def __init__(self, in_channels=4):
363
+ super().__init__()
364
+ # Encoder Path
365
+ self.mpool_2 = nn.MaxPool2d(2)
366
+ self.down1 = conv2d_inplace_spatial(in_channels, 32, self.mpool_2)
367
+ self.down2 = conv2d_inplace_spatial(32, 64, self.mpool_2)
368
+ self.down3 = conv2d_inplace_spatial(64, 128, self.mpool_2)
369
+ self.down4 = conv2d_inplace_spatial(128, 256, self.mpool_2)
370
+ self.down5 = conv2d_inplace_spatial(256, 512) # Bottleneck
371
+
372
+ # Decoder Path with Upscale
373
+ self.upscale_2 = Upscale(scale_factor=2)
374
+ self.up1 = conv2d_inplace_spatial(512 + 256, 256, self.upscale_2)
375
+ self.up2 = conv2d_inplace_spatial(256 + 128, 128, self.upscale_2)
376
+ self.up3 = conv2d_inplace_spatial(128 + 64, 64, self.upscale_2)
377
+ self.up4 = conv2d_inplace_spatial(64 + 32, 32, self.upscale_2)
378
+
379
+ # Final output
380
+ self.final_conv = nn.Sequential(nn.Conv2d(32, 1, kernel_size=1), nn.Sigmoid())
381
+
382
+ def encode(self, x):
383
+ """Encoder with skip connections"""
384
+ x1 = self.down1(x) # 32
385
+ x2 = self.down2(x1) # 64
386
+ x3 = self.down3(x2) # 128
387
+ x4 = self.down4(x3) # 256
388
+ x5 = self.down5(x4) # 512
389
+ return x1, x2, x3, x4, x5
390
+
391
+ def decode(self, x1, x2, x3, x4, x5):
392
+ """Decoder using Upscale module"""
393
+ x = self.up1(torch.cat([x5, x4], dim=1)) # 512+256 -> 256
394
+ x = self.up2(torch.cat([x, x3], dim=1)) # 256+128 -> 128
395
+ x = self.up3(torch.cat([x, x2], dim=1)) # 128+64 -> 64
396
+ x = self.up4(torch.cat([x, x1], dim=1)) # 64+32 -> 32
397
+ return self.final_conv(x)
398
+
399
+ def forward(self, batch, bce_weight=0.5, dice_weight=0.5):
400
+ """Forward pass with input validation and weighted losses"""
401
+ # Input validation
402
+ assert isinstance(batch, dict), "Input must be a dictionary"
403
+ assert all(k in batch for k in ['rgb', 'modal_mask', 'amodal_mask']), "Missing required keys"
404
+ assert batch['rgb'].shape[1] == 3, "RGB input must have 3 channels"
405
+ assert batch['modal_mask'].shape[1] == 1, "Modal mask must be single channel"
406
+
407
+ # Model forward pass
408
+ modal_input = torch.cat((batch['rgb'], batch['modal_mask']), dim=1)
409
+ amodal_mask_labels = batch['amodal_mask'].float()
410
+ pred_mask = self.decode(*self.encode(modal_input))
411
+
412
+ # Loss calculation
413
+ bce_loss = F.binary_cross_entropy(pred_mask, amodal_mask_labels)
414
+
415
+ # Dice loss (direct calculation)
416
+ smooth = 1.0
417
+ pred_flat = pred_mask.view(-1)
418
+ target_flat = amodal_mask_labels.view(-1)
419
+ intersection = (pred_flat * target_flat).sum()
420
+ dice_loss = 1 - (2. * intersection + smooth) / (pred_flat.sum() + target_flat.sum() + smooth)
421
+
422
+ # Weighted total loss
423
+ total_loss = bce_weight * bce_loss + dice_weight * dice_loss
424
+
425
+ # Metrics
426
+ metrics = {
427
+ 'loss': total_loss.item(),
428
+ 'bce': bce_loss.item(),
429
+ 'dice': 1 - dice_loss.item(),
430
+ 'iou': (intersection + smooth) / ((pred_flat + target_flat).sum() - intersection + smooth).item()
431
+ }
432
+
433
+ return total_loss, metrics, batch
434
+
435
+ def batch_to_device(batch, device):
436
+ return {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in batch.items()}
437
+
438
+ def aggregate_metrics(metrics_list):
439
+ return {k: sum(m[k] for m in metrics_list) / len(metrics_list) for k in metrics_list[0]}
440
+
441
+ def train_step(batch, model, optimizer, bce_weight=0.5, dice_weight=0.5):
442
+ model.train()
443
+ optimizer.zero_grad()
444
+ total_loss, metrics, _ = model(batch, bce_weight=bce_weight, dice_weight=dice_weight) # Updated
445
+ total_loss.backward()
446
+ optimizer.step()
447
+ return total_loss, metrics
448
+
449
+ def val_step(batch, model, bce_weight=0.5, dice_weight=0.5):
450
+ model.eval()
451
+ with torch.no_grad():
452
+ total_loss, metrics, batch = model(batch, bce_weight=bce_weight, dice_weight=dice_weight) # Updated
453
+ return total_loss, metrics, batch
454
+
455
+ def run_epoch(model, dataloader, device, optimizer=None, bce_weight=0.5, dice_weight=0.5): # Added params
456
+ metrics_list = []
457
+ sample_batch = None
458
+
459
+ for i, batch in enumerate(dataloader):
460
+ batch = batch_to_device(batch, device)
461
+
462
+ if optimizer is not None:
463
+ loss, metrics = train_step(batch, model, optimizer, bce_weight, dice_weight) # Updated
464
+ else:
465
+ loss, metrics, batch = val_step(batch, model, bce_weight, dice_weight) # Updated
466
+ if i == 0:
467
+ sample_batch = batch
468
+
469
+ metrics_list.append(metrics)
470
+
471
+ return aggregate_metrics(metrics_list), sample_batch
472
+
473
+ def visualize_results(sample, model, epoch):
474
+ model.eval()
475
+ with torch.no_grad():
476
+ # Prepare sample batch as dictionary (consistent with forward())
477
+ sample_dict = {
478
+ 'rgb': sample['rgb'][0].unsqueeze(0).to(device),
479
+ 'modal_mask': sample['modal_mask'][0].unsqueeze(0).to(device),
480
+ 'amodal_mask': sample['amodal_mask'][0].unsqueeze(0).to(device)
481
+ }
482
+
483
+ # Create 4-channel input (RGB + modal mask)
484
+ model_input = torch.cat([sample_dict['rgb'], sample_dict['modal_mask']], dim=1)
485
+
486
+ # Get encoder features (x1-x5)
487
+ x1, x2, x3, x4, x5 = model.encode(model_input)
488
+
489
+ # Decode with skip connections
490
+ pred_mask = model.decode(x1, x2, x3, x4, x5)
491
+
492
+ # Prepare visualization
493
+ rgb = sample_dict['rgb'].squeeze().permute(1,2,0).cpu().numpy()
494
+ modal = sample_dict['modal_mask'].squeeze().cpu().numpy()
495
+ pred = pred_mask.squeeze().cpu().numpy() > 0.5 # Apply threshold
496
+ gt = sample_dict['amodal_mask'].squeeze().cpu().numpy()
497
+
498
+ # Visualization
499
+ fig, ax = plt.subplots(2, 2, figsize=(5, 5))
500
+ titles = ['RGB Input', 'Modal Mask', 'Predicted Amodal', 'Ground Truth']
501
+ images = [rgb, modal, pred, gt]
502
+
503
+ for i, (ax, title, img) in enumerate(zip(ax.flat, titles, images)):
504
+ ax.imshow(img, cmap='gray' if i > 0 else None)
505
+ ax.set_title(title)
506
+ ax.axis('off')
507
+
508
+ plt.suptitle(f'Epoch {epoch+1} Results')
509
+ plt.tight_layout()
510
+ plt.show()
511
+
512
+ def train(model, optimizer, train_loader, val_loader, epochs, device, bce_weight=0.5, dice_weight=0.5, save_path='model_checkpoint.pth'):
513
+ train_metrics = {'loss': [], 'iou': [], 'dice': []}
514
+ val_metrics = {'loss': [], 'iou': [], 'dice': []}
515
+
516
+ for epoch in range(epochs):
517
+ print(f"Epoch {epoch + 1} / {epochs}")
518
+
519
+ # Training
520
+ model.train()
521
+ train_epoch_metrics, _ = run_epoch(model, train_loader, device, optimizer, bce_weight, dice_weight)
522
+
523
+ # Validation
524
+ model.eval()
525
+ val_epoch_metrics, sample_batch = run_epoch(model, val_loader, device, None, bce_weight, dice_weight)
526
+
527
+ # Store metrics
528
+ for k in train_metrics:
529
+ train_metrics[k].append(train_epoch_metrics[k])
530
+ val_metrics[k].append(val_epoch_metrics[k])
531
+
532
+ print(f"Train Loss: {train_epoch_metrics['loss']:.4f} | Val Loss: {val_epoch_metrics['loss']:.4f}")
533
+ print(f"Train IOU: {train_epoch_metrics['iou']:.4f} | Val IOU: {val_epoch_metrics['iou']:.4f}")
534
+ print(f"Train Dice: {train_epoch_metrics['dice']:.4f} | Val Dice: {val_epoch_metrics['dice']:.4f}")
535
+
536
+ if epoch % 1 == 0:
537
+ visualize_results(sample_batch, model, epoch)
538
+
539
+ # Save checkpoint every epoch (or adjust frequency as needed)
540
+ save_checkpoint(model, optimizer, epoch, train_metrics, val_metrics, save_path)
541
+
542
+ return train_metrics, val_metrics
543
+
544
+ # Arguments
545
+ learning_rate = 3e-4
546
+ batch_size = 64
547
+ n_workers = 2
548
+ n_epochs = 20
549
+ img_size = (256, 256)
550
+ bce_weight = 0.5
551
+ dice_weight = 0.5
552
+
553
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
554
+ print(f"Using device: {device}")
555
+
556
+ # Data
557
+ train_loader = create_dataloader(root_dir='/content/data', split='train', batch_size=batch_size, num_workers=n_workers, img_size=img_size)
558
+ val_loader = create_dataloader(root_dir='/content/data', split='test', batch_size=batch_size, num_workers=n_workers, img_size=img_size)
559
+
560
+ # save function to .pth file
561
+ def save_checkpoint(model, optimizer, epoch, train_metrics, val_metrics, filename):
562
+ """Save model checkpoint with all relevant information"""
563
+ checkpoint = {
564
+ 'epoch': epoch,
565
+ 'model_state_dict': model.state_dict(),
566
+ 'optimizer_state_dict': optimizer.state_dict(),
567
+ 'train_metrics': train_metrics,
568
+ 'val_metrics': val_metrics,
569
+ 'model_config': {'in_channels': model.in_channels if hasattr(model, 'in_channels') else 4,}
570
+ }
571
+ torch.save(checkpoint, filename)
572
+ print(f"Checkpoint saved to {filename}")
573
+
574
+ # Model
575
+ model = Unet_Image(in_channels=4).to(device)
576
+ optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
577
+
578
+ # Train
579
+ train_metrics, val_metrics = train(
580
+ model=model,
581
+ optimizer=optimizer,
582
+ train_loader=train_loader,
583
+ val_loader=val_loader,
584
+ epochs=n_epochs,
585
+ device=device,
586
+ bce_weight=bce_weight,
587
+ dice_weight=dice_weight,
588
+ save_path='best_model.pth'
589
+ )
Task1_1/best_model.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:95fa2706fb01d7bd89cc9223493b4a7a486c9e17037a6ecfc6cb29eb5db40218
3
+ size 94376452