Groovyfaun commited on
Commit
2e6ce97
·
verified ·
1 Parent(s): e8ad258

Upload 2 files

Browse files
Task_2_1/Task_2_1.py ADDED
@@ -0,0 +1,533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pip install torch torchvision matplotlib av pytorch_msssim
2
+
3
+ # PyTorch, Torchvision
4
+ import torch
5
+ from torch import nn
6
+ import torchvision
7
+ from torchvision.transforms import ToPILImage, ToTensor
8
+ from torchvision.utils import make_grid
9
+ from torchvision.io import write_video
10
+ from torch.utils.data import Dataset
11
+ import torch.nn.functional as F
12
+ from torch.utils.data import DataLoader, random_split
13
+ from torchvision import transforms, utils
14
+ from PIL import Image
15
+
16
+ # Common
17
+ from pathlib import Path
18
+ from PIL import Image
19
+ import numpy as np
20
+ import matplotlib.pyplot as plt
21
+ import random
22
+ import json
23
+ from IPython.display import Video
24
+ import tarfile
25
+ import glob
26
+ from tqdm import tqdm
27
+ from PIL import Image
28
+ import io
29
+ import cv2
30
+
31
+ # Utils from Torchvision
32
+ tensor_to_image = ToPILImage()
33
+ image_to_tensor = ToTensor()
34
+
35
+ def get_img_dict(img_dir):
36
+ img_files = [x for x in img_dir.iterdir() if x.name.endswith('.png') or x.name.endswith('.tiff')]
37
+ img_files.sort()
38
+
39
+ img_dict = {}
40
+ for img_file in img_files:
41
+ img_type = img_file.name.split('_')[0]
42
+ if img_type not in img_dict:
43
+ img_dict[img_type] = []
44
+ img_dict[img_type].append(img_file)
45
+ return img_dict
46
+
47
+
48
+ def get_sample_dict(sample_dir):
49
+
50
+ camera_dirs = [x for x in sample_dir.iterdir() if 'camera' in x.name]
51
+ camera_dirs.sort()
52
+
53
+ sample_dict = {}
54
+
55
+ for cam_dir in camera_dirs:
56
+ cam_dict = {}
57
+ cam_dict['scene'] = get_img_dict(cam_dir)
58
+
59
+ obj_dirs = [x for x in cam_dir.iterdir() if 'obj_' in x.name]
60
+ obj_dirs.sort()
61
+
62
+ for obj_dir in obj_dirs:
63
+ cam_dict[obj_dir.name] = get_img_dict(obj_dir)
64
+
65
+ sample_dict[cam_dir.name] = cam_dict
66
+
67
+ return sample_dict
68
+
69
+
70
+ def make_obj_viz(cam_dict, cam_num=0):
71
+
72
+ n_frames = 24
73
+ n_cols = 6
74
+
75
+ all_obj_ids = [x for x in sample_dict['camera_0000'].keys() if 'obj_' in x]
76
+ obj_id_str = random.sample(all_obj_ids, k=1)[0]
77
+ obj_id_int = int(obj_id_str.split('_')[1])
78
+
79
+ grid_tensors = []
80
+ for i in range(n_frames):
81
+ grid = []
82
+ scene_rgb_tensor = image_to_tensor(Image.open(cam_dict['scene']['rgba'][i]).convert('RGB'))
83
+ grid.append(scene_rgb_tensor)
84
+ scene_masks_tensor = image_to_tensor(Image.open(cam_dict['scene']['segmentation'][i]).convert('RGB'))
85
+ grid.append(scene_masks_tensor)
86
+
87
+ scene_masks_p = Image.open(cam_dict['scene']['segmentation'][i])
88
+ scene_masks_p_tensor = torch.tensor(np.array(scene_masks_p))
89
+ obj_modal_tensor = (scene_masks_p_tensor==obj_id_int)
90
+ blended_obj_modal_tensor = scene_masks_tensor*obj_modal_tensor
91
+ grid.append(blended_obj_modal_tensor)
92
+
93
+ obj_amodal_tensor = image_to_tensor(Image.open(cam_dict[obj_id_str]['segmentation'][i]).convert('RGB'))
94
+ blended_obj_amodal_tensor = blended_obj_modal_tensor + (obj_amodal_tensor != obj_modal_tensor)
95
+ grid.append(blended_obj_amodal_tensor)
96
+
97
+ obj_rgb_tensor = image_to_tensor(Image.open(cam_dict[obj_id_str]['rgba'][i]).convert('RGB'))
98
+ grid.append(obj_rgb_tensor)
99
+
100
+ blended_scene_obj_tensor = (scene_rgb_tensor/3 + 2*blended_obj_amodal_tensor/3)
101
+ grid.append(blended_scene_obj_tensor)
102
+
103
+ grid_tensors.append(make_grid(grid, nrow=n_cols, padding=2, pad_value=127))
104
+
105
+ return grid_tensors
106
+
107
+
108
+ def make_vid(grid_tensors, save_path):
109
+ vid_tensor = torch.stack(grid_tensors, dim=1).permute(1, 2, 3, 0)
110
+ vid_tensor = (vid_tensor*255).long()
111
+ write_video(save_path, vid_tensor, fps=5, options={'crf':'20'})
112
+
113
+
114
+ ''' Code to download files from the MOVi-MC-AC Dataset
115
+ !wget https://huggingface.co/datasets/Amar-S/MOVi-MC-AC/resolve/main/test_obj_descriptors.json
116
+ #Download Descriptors, Readme, etc.
117
+ !wget https://huggingface.co/datasets/Amar-S/MOVi-MC-AC/resolve/main/train_obj_descriptors.json
118
+ !wget https://huggingface.co/datasets/Amar-S/MOVi-MC-AC/resolve/main/ex_vis.mp4
119
+ !wget https://huggingface.co/datasets/Amar-S/MOVi-MC-AC/resolve/main/README.md
120
+ !wget "https://huggingface.co/datasets/Amar-S/MOVi-MC-AC/resolve/main/Notice%201%20-%20Unlimited_datasets.pdf"
121
+ !wget https://huggingface.co/datasets/Amar-S/MOVi-MC-AC/resolve/main/.gitattributes
122
+ #Test to see if you are on the right huggingface repo
123
+ from huggingface_hub import HfApi, hf_hub_download
124
+ import random, os
125
+ api = HfApi()
126
+ repo_id = "Amar-S/MOVi-MC-AC"
127
+ # # List all files in the repo
128
+ files = api.list_repo_files(repo_id=repo_id, repo_type="dataset")
129
+ # # Separate train and test files
130
+ train_files = [f for f in files if f.startswith("train/") and not f.endswith(".json")]
131
+ test_files = [f for f in files if f.startswith("test/") and not f.endswith(".json")]
132
+ print(f"Found {len(train_files)} train files and {len(test_files)} test files.")
133
+ #Download 4% of Train/Test files
134
+ import os
135
+ import random
136
+ import shutil
137
+ from huggingface_hub import hf_hub_download
138
+ os.makedirs("/content/data/train", exist_ok=True)
139
+ os.makedirs("/content/data/test", exist_ok=True)
140
+ # # Sample 4% of each split (as you were doing)
141
+ subset_train = random.sample(train_files, int(len(train_files) * 0.015))
142
+ subset_test = random.sample(test_files, int(len(test_files) * 0.015))
143
+ # # Download the training files (uncomment and fix)
144
+ for file in subset_train:
145
+ out_path = hf_hub_download(repo_id=repo_id, repo_type="dataset", filename=file)
146
+ dest_path = f"/content/data/train/{os.path.basename(file)}"
147
+ shutil.copyfile(out_path, dest_path) # COPY the actual file content instead of renaming symlink
148
+ # # Download the test files
149
+ for file in subset_test:
150
+ out_path = hf_hub_download(repo_id=repo_id, repo_type="dataset", filename=file)
151
+ dest_path = f"/content/data/test/{os.path.basename(file)}"
152
+ shutil.copyfile(out_path, dest_path) # COPY the actual file content here as well
153
+
154
+
155
+
156
+ def extract_files(path=''):
157
+ root = Path(path)
158
+ for archive in root.rglob("*.tar.gz"):
159
+ extract_path = archive.parent / archive.stem.replace(".tar", "")
160
+ with tarfile.open(archive, "r:gz") as tar:
161
+ tar.extractall(path=extract_path)
162
+ '''
163
+
164
+
165
+ def get_all_samples(root_dir):
166
+ root = Path(root_dir)
167
+ sample_dict = {}
168
+
169
+ for cam_dir in root.rglob("camera_*"):
170
+ if cam_dir.is_dir():
171
+ rgba_imgs = sorted(cam_dir.glob("rgba_*.png"))
172
+ segm_imgs = sorted(cam_dir.glob("segmentation_*.png"))
173
+
174
+ if len(rgba_imgs) == 0 or len(segm_imgs) == 0:
175
+ print(f"Skipping {cam_dir} — missing or empty rgba/segmentation folders")
176
+ continue
177
+
178
+ scene_id = cam_dir.parents[1].name # e.g. data/train/<scene>/<scene>/camera_xxxx
179
+ cam_id = cam_dir.name
180
+
181
+ if scene_id not in sample_dict:
182
+ sample_dict[scene_id] = {}
183
+
184
+ cam_dict = {
185
+ 'rgba': rgba_imgs,
186
+ 'segmentation': segm_imgs,
187
+ }
188
+
189
+ # Add all obj_XXXX folders
190
+ for obj_dir in sorted(cam_dir.glob("obj_*")):
191
+ cam_dict[obj_dir.name] = {
192
+ 'segmentation': sorted((obj_dir).glob("segmentation*.png")),
193
+ 'rgba': sorted((obj_dir).glob("rgba*.png"))
194
+ }
195
+
196
+ sample_dict[scene_id][cam_id] = cam_dict
197
+
198
+ print(f"Loaded {len(sample_dict)} scenes from {root_dir}")
199
+ return sample_dict
200
+
201
+
202
+ class WindowedModalMaskDataset(Dataset):
203
+ def __init__(self, root_dir, window_size=5):
204
+ self.sample_dict = get_all_samples(root_dir)
205
+ self.entries = []
206
+ self.window_size = window_size
207
+
208
+ for scene_id, cams in self.sample_dict.items():
209
+ for cam_id, data in cams.items():
210
+ num_frames = len(data['rgba'])
211
+ for start_idx in range(num_frames - window_size + 1):
212
+ self.entries.append((scene_id, cam_id, start_idx))
213
+
214
+ print(f"Total dataset size (windows): {len(self.entries)} samples")
215
+
216
+ def __len__(self):
217
+ return len(self.entries)
218
+
219
+ def __getitem__(self, idx):
220
+ scene_id, cam_id, start_idx = self.entries[idx]
221
+ paths = self.sample_dict[scene_id][cam_id]
222
+ T = self.window_size
223
+
224
+ scene_frames = []
225
+ amodal_frames = []
226
+
227
+ rand_obj_id = None # will be selected on first frame
228
+
229
+ for t in range(T):
230
+ frame_idx = start_idx + t
231
+
232
+ # Load RGB image
233
+ scene_img = Image.open(paths['rgba'][frame_idx]).convert('RGB')
234
+ scene_tensor = image_to_tensor(scene_img) # [3, H, W]
235
+
236
+ # Load object segmentation mask (same as used for modal)
237
+ obj_mask = np.array(Image.open(paths['segmentation'][frame_idx]))
238
+ obj_mask_tensor = torch.tensor(obj_mask, dtype=torch.int64) # [H, W]
239
+
240
+ # Choose the object once, from first frame
241
+ if t == 0:
242
+ unique_ids = torch.unique(obj_mask_tensor)
243
+ unique_objects = unique_ids[unique_ids != 0] # exclude background
244
+ if len(unique_objects) == 0:
245
+ raise ValueError(f"No objects in segmentation mask at frame {frame_idx}!")
246
+ rand_obj_id = random.choice(unique_objects.tolist())
247
+
248
+ # Compute modal mask for selected object
249
+ modal_mask = (obj_mask_tensor == rand_obj_id).float().unsqueeze(0) # [1, H, W]
250
+
251
+ # Combine RGB + modal mask
252
+ scene_with_mask = torch.cat((scene_tensor, modal_mask), dim=0) # [4, H, W]
253
+ scene_frames.append(scene_with_mask) # list of [4, H, W]
254
+
255
+ # Load amodal mask (per-object segmentation from separate path, assumed same format)
256
+ amodal_mask = Image.open(paths[f'obj_{rand_obj_id:04d}']['segmentation'][frame_idx]) # reuse same mask
257
+ #amodal_mask_tensor = (torch.tensor(amodal_mask_arr, dtype=torch.float32) == rand_obj_id).float().unsqueeze(0) # [1, H, W]
258
+ amodal_mask_tensor = image_to_tensor(amodal_mask) # [1, H, W]
259
+ amodal_frames.append(amodal_mask_tensor)
260
+
261
+ # Stack all frames: output [T, 4, H, W] and [T, 1, H, W]
262
+ modal = torch.stack(scene_frames, dim=0) # [T, 4, H, W]
263
+ amodal = torch.stack(amodal_frames, dim=0) # [T, 1, H, W]
264
+
265
+ return modal, amodal
266
+
267
+
268
+ class conv2d_inplace_spatial(nn.Module):
269
+ def __init__(self, in_channels, out_channels, pooling_function, activation = nn.GELU()):
270
+ super().__init__()
271
+ self.double_conv = nn.Sequential(
272
+ nn.Conv2d(in_channels, out_channels, kernel_size=(3, 3), padding=(1, 1)),
273
+ nn.BatchNorm2d(out_channels),
274
+ nn.ReLU(),
275
+ nn.Conv2d(out_channels, out_channels, kernel_size=(3, 3), padding=(1, 1)),
276
+ nn.BatchNorm2d(out_channels),
277
+ activation,
278
+ pooling_function,
279
+ )
280
+
281
+ def forward(self, x):
282
+ return self.double_conv(x)
283
+
284
+
285
+ class AttentionGate(nn.Module):
286
+ def __init__(self, F_g, F_l, F_int):
287
+ super().__init__()
288
+ self.W_g = nn.Sequential(
289
+ nn.Conv2d(F_g, F_int, 1),
290
+ nn.BatchNorm2d(F_int)
291
+ )
292
+
293
+ self.W_x = nn.Sequential(
294
+ nn.Conv2d(F_l, F_int, 1),
295
+ nn.BatchNorm2d(F_int)
296
+ )
297
+
298
+ self.psi = nn.Sequential(
299
+ nn.Conv2d(F_int, 1, 1),
300
+ nn.BatchNorm2d(1),
301
+ nn.Sigmoid()
302
+ )
303
+
304
+ self.relu = nn.ReLU(inplace=True)
305
+
306
+ def forward(self, x, g):
307
+ g1 = self.W_g(g)
308
+ x1 = self.W_x(x)
309
+ psi = self.relu(g1 + x1)
310
+ psi = self.psi(psi)
311
+ return x * psi
312
+
313
+
314
+ class Upscale(nn.Module):
315
+ def __init__(self, scale_factor=(2, 2), mode='bilinear', align_corners=False):
316
+ super(Upscale, self).__init__()
317
+ self.scale_factor = scale_factor
318
+ self.mode = mode
319
+ self.align_corners = align_corners
320
+
321
+ def forward(self, x):
322
+ return F.interpolate(x, scale_factor=self.scale_factor, mode=self.mode, align_corners=self.align_corners)
323
+
324
+
325
+ class Unet_Image(nn.Module):
326
+ def __init__(self, in_channels = 4, mask_content_preds = False):
327
+ super().__init__()
328
+
329
+ self.mpool_2 = nn.MaxPool2d((2, 2))
330
+
331
+ self.down1 = conv2d_inplace_spatial(in_channels, 32, self.mpool_2)
332
+ self.down2 = conv2d_inplace_spatial(32, 64, self.mpool_2)
333
+ self.down3 = conv2d_inplace_spatial(64, 128, self.mpool_2)
334
+ self.down4 = conv2d_inplace_spatial(128, 256, self.mpool_2)
335
+
336
+ self.upscale_2 = Upscale(scale_factor=(2, 2), mode='bilinear', align_corners=False)
337
+
338
+ self.bottleneck = nn.Sequential(
339
+ nn.Conv2d(256, 64, 1), nn.ReLU()
340
+ )
341
+ self.lstm = nn.LSTM(input_size=64*16*16, hidden_size=512, batch_first=True, bidirectional=True)
342
+ self.lstm_proj = nn.Linear(1024, 256 * 16 * 16)
343
+
344
+ self.up1 = conv2d_inplace_spatial(256, 128, self.upscale_2)
345
+ self.up2 = conv2d_inplace_spatial(256, 64, self.upscale_2)
346
+ self.up3 = conv2d_inplace_spatial(128, 32, self.upscale_2)
347
+
348
+ self.atten_gate2 = AttentionGate(128, 128, 64)
349
+ self.atten_gate1 = AttentionGate(64, 64, 32)
350
+ self.atten_gate0 = AttentionGate(32, 32, 16)
351
+
352
+ self.up4_amodal_content = conv2d_inplace_spatial(64, 1, self.upscale_2, activation = nn.Identity())
353
+
354
+ def encode_frame(self, x):
355
+ x1 = self.down1(x)
356
+ x2 = self.down2(x1)
357
+ x3 = self.down3(x2)
358
+ x4 = self.down4(x3)
359
+ x4_bottleneck = self.bottleneck(x4)
360
+ return x1, x2, x3, x4_bottleneck# [B, T, 3, H, W]
361
+
362
+ def decode(self, h1, h2, h3, h4):
363
+ h4 = self.up1(h4) # 6, 256, 1, 16, 16 -> 6, 128, 1, 32, 32 (double spatial, then conv-in-place channels to half)
364
+ h3 = self.atten_gate2(h3, h4)
365
+ h34 = torch.cat((h3, h4), dim = 1) # (6, 2*128, 1, 32, 32)
366
+
367
+ h34 = self.up2(h34) # 6, 256, 1, 32, 32 -> 6, 128, 2, 64, 64
368
+ h34 = self.atten_gate1(h2, h34)
369
+ h234 = torch.cat((h2, h34), dim = 1) # (6, 2*128, )
370
+
371
+ h234 = self.up3(h234)
372
+ h234 = self.atten_gate0(h1, h234)
373
+ h1234 = torch.cat((h1, h234), dim = 1)
374
+
375
+ #logits_amodal_mask = self.up4_amodal_mask(h1234)
376
+ logits_amodal_content = self.up4_amodal_content(h1234)
377
+ return logits_amodal_content
378
+
379
+ def forward(self, x): # x: [B, T, C, H, W]
380
+ B, T, C, H, W = x.shape
381
+ lstm_inputs = []
382
+ skip_connections = []
383
+
384
+ for t in range(T):
385
+ x1, x2, x3, x4 = self.encode_frame(x[:, t])
386
+ skip_connections.append((x1, x2, x3))
387
+ lstm_inputs.append(x4.flatten(1)) # [B, 64*16*16]
388
+
389
+ lstm_in = torch.stack(lstm_inputs, dim=1) # [B, T, feat_dim]
390
+ lstm_out, _ = self.lstm(lstm_in) # [B, T, 1024]
391
+ lstm_out = self.lstm_proj(lstm_out).view(B, T, 256, 16, 16)
392
+
393
+ # Decode for each frame
394
+ output_frames = []
395
+ for t in range(T):
396
+ x1, x2, x3 = skip_connections[t]
397
+ decoded = self.decode(x1, x2, x3, lstm_out[:, t])
398
+ output_frames.append(decoded)
399
+
400
+ return torch.stack(output_frames, dim=1)
401
+
402
+
403
+ def draw_amodal_boundary(rgb_image, amodal_mask, color=(255, 0, 255)):
404
+ """
405
+ Draws an outline of the amodal mask on top of the RGB image.
406
+ Assumes rgb_image is in [H, W, 3] and amodal_mask is [H, W].
407
+ """
408
+ contours, _ = cv2.findContours(amodal_mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
409
+ outlined = cv2.drawContours(rgb_image.copy(), contours, -1, color, thickness=2)
410
+ return outlined
411
+
412
+
413
+ def save_sequence_gif(output, input, target, gif_path='output.gif', fps=2, frame_idx=0):
414
+ output = output.detach().cpu()
415
+ input = input.detach().cpu()
416
+ target = target.detach().cpu()
417
+
418
+ _, T, _, H, W = output.shape
419
+ frames = []
420
+
421
+ for t in range(T):
422
+ fig, axs = plt.subplots(1, 4, figsize=(12, 3))
423
+
424
+ # Get RGB image
425
+ rgb = input[frame_idx, t, :3].permute(1, 2, 0).numpy() # shape: [H, W, 3]
426
+ rgb = (rgb * 255).astype(np.uint8) if rgb.max() <= 1.0 else rgb.astype(np.uint8)
427
+
428
+ # Get GT amodal mask
429
+ gt_mask = target[frame_idx, t, 0].numpy()
430
+ gt_mask = (gt_mask > 0.5).astype(np.uint8) # Binarize
431
+
432
+ # Draw outline
433
+ rgb_outlined = draw_amodal_boundary(rgb, gt_mask)
434
+
435
+ axs[0].imshow(rgb_outlined)
436
+ axs[0].set_title("RGB + GT Amodal Outline")
437
+
438
+ # Modal mask
439
+ modal = input[frame_idx, t, 3]
440
+ axs[1].imshow(modal, cmap='gray')
441
+ axs[1].set_title("Modal Mask")
442
+
443
+ # Predicted amodal
444
+ pred = output[frame_idx, t, 0]
445
+ axs[2].imshow(pred, cmap='gray')
446
+ axs[2].set_title("Predicted Amodal")
447
+
448
+ # Ground truth amodal
449
+ axs[3].imshow(gt_mask, cmap='gray')
450
+ axs[3].set_title("GT Amodal")
451
+
452
+ for ax in axs:
453
+ ax.axis('off')
454
+ plt.tight_layout()
455
+
456
+ buf = io.BytesIO()
457
+ plt.savefig(buf, format='png')
458
+ plt.close(fig)
459
+ buf.seek(0)
460
+ frame = Image.open(buf)
461
+ frames.append(frame)
462
+
463
+ frames[0].save(
464
+ gif_path, save_all=True, append_images=frames[1:], duration=int(1000 / fps), loop=0
465
+ )
466
+ print(f"Saved GIF to {gif_path}")
467
+
468
+
469
+ train_dataset = WindowedModalMaskDataset('data/train', window_size=10)
470
+ train_size = int(0.8 * len(train_dataset))
471
+ val_size = len(train_dataset) - train_size
472
+ train_dataset, val_dataset = random_split(train_dataset, [train_size, val_size])
473
+ train_dataloader = DataLoader(train_dataset, batch_size=16, shuffle = True)
474
+ val_dataloader = DataLoader(val_dataset, batch_size=16, shuffle=False)
475
+
476
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
477
+
478
+ loss_fn = nn.BCEWithLogitsLoss()
479
+
480
+ model = Unet_Image(4).to(device)
481
+ optimizer = torch.optim.Adam(model.parameters(), lr=3e-3)
482
+ step = 0
483
+ for epoch in range(30):
484
+ model.train()
485
+ step += 1
486
+ for data, target in train_dataloader:
487
+ data, target = data.to(device), target.to(device)
488
+
489
+ fake_video = model(data)
490
+
491
+ recon_loss = loss_fn(fake_video, target)
492
+
493
+ optimizer.zero_grad()
494
+ recon_loss.backward()
495
+ optimizer.step()
496
+
497
+ #Show predictions from last trianing run
498
+ #fake_video = torch.sigmoid(fake_video).round()
499
+ #gif = f'train_epoch_{step:03d}.gif'
500
+ #save_sequence_gif(fake_video, data, target, gif_path=gif, fps=6, frame_idx=0)
501
+
502
+ model.eval()
503
+ val_loss = 0.0
504
+ with torch.no_grad():
505
+ for data,target in val_dataloader:
506
+ data, target = data.to(device), target.to(device)
507
+
508
+ fake_video = model(data)
509
+
510
+ recon_loss = loss_fn(fake_video, target)
511
+ val_loss += recon_loss.item()
512
+
513
+ #fake_video = torch.sigmoid(fake_video).round()
514
+ #gif = f'train_epoch_{step:03d}.gif'
515
+ #save_sequence_gif(fake_video, data, target, gif_path=gif, fps=6, frame_idx=0)
516
+ print(f"Epoch {epoch+1} - Val Loss: {val_loss/len(val_dataloader):.4f}")
517
+
518
+ #Testing
519
+ test_dataset = WindowedModalMaskDataset('data/test', window_size=15)
520
+ test_dataloader = DataLoader(test_dataset, batch_size=16, shuffle=False)
521
+
522
+ model.eval()
523
+ step = 0
524
+ with torch.no_grad():
525
+ for data, target in test_dataloader:
526
+ step += 1
527
+ data, target = data.to(device), target.to(device)
528
+ fake_video = model(data)
529
+ fake_video = torch.sigmoid(fake_video).round()
530
+ gif = f'output{step:04d}.gif'
531
+ #if step % 50 == 0:
532
+ save_sequence_gif(fake_video, data, target, gif_path=gif, fps=6, frame_idx=0)
533
+ #break
Task_2_1/amodal_checkpoint.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4711dd882a08422066838c5900efeb69f16cf9f8985123546e52f1b100a40ff5
3
+ size 1659492858