jskvrna commited on
Commit
7cf6fd9
·
1 Parent(s): e0d1066

Adds initial 3D CNN voxel implementation

Browse files

Implements a fast 3D CNN for vertex prediction from voxelized point cloud patches. It uses 3D convolutions and voxelization and includes data loading and training scripts. Also adds a batch script for cluster training.

Files changed (4) hide show
  1. fast_voxel.py +591 -0
  2. hoho_gpu_voxel.batch +19 -0
  3. train_voxel.py +13 -0
  4. train_voxel_cluster.py +13 -0
fast_voxel.py ADDED
@@ -0,0 +1,591 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ import numpy as np
6
+ import pickle
7
+ from torch.utils.data import Dataset, DataLoader
8
+ from typing import List, Dict, Tuple, Optional
9
+ import json
10
+
11
+ class Fast3DCNN(nn.Module):
12
+ """
13
+ Fast 3D CNN implementation for 3D vertex prediction from voxelized point cloud patches.
14
+ Takes 7D point clouds (x,y,z,r,g,b,filtered_flag) and predicts 3D vertex coordinates.
15
+ Uses voxelization and 3D convolutions instead of PointNet architecture.
16
+ """
17
+ def __init__(self, input_channels=7, output_dim=3, voxel_size=32, predict_score=True, predict_class=True, num_classes=1):
18
+ super(Fast3DCNN, self).__init__()
19
+ self.voxel_size = voxel_size
20
+ self.predict_score = predict_score
21
+ self.predict_class = predict_class
22
+ self.num_classes = num_classes
23
+
24
+ # 3D Convolutional layers for feature extraction
25
+ self.conv1 = nn.Conv3d(input_channels, 64, kernel_size=3, padding=1)
26
+ self.conv2 = nn.Conv3d(64, 128, kernel_size=3, padding=1)
27
+ self.conv3 = nn.Conv3d(128, 256, kernel_size=3, padding=1)
28
+ self.conv4 = nn.Conv3d(256, 512, kernel_size=3, padding=1)
29
+ self.conv5 = nn.Conv3d(512, 512, kernel_size=3, padding=1)
30
+
31
+ # Additional convolutional layers for deeper feature extraction
32
+ self.conv6 = nn.Conv3d(512, 1024, kernel_size=3, padding=1)
33
+
34
+ # Batch normalization layers
35
+ self.bn1 = nn.BatchNorm3d(64)
36
+ self.bn2 = nn.BatchNorm3d(128)
37
+ self.bn3 = nn.BatchNorm3d(256)
38
+ self.bn4 = nn.BatchNorm3d(512)
39
+ self.bn5 = nn.BatchNorm3d(512)
40
+ self.bn6 = nn.BatchNorm3d(1024)
41
+
42
+ # Max pooling layers
43
+ self.pool = nn.MaxPool3d(kernel_size=2, stride=2)
44
+
45
+ # Calculate the size after convolutions and pooling
46
+ # Starting with voxel_size^3, after 3 pooling operations: voxel_size / 8
47
+ final_size = voxel_size // 8
48
+ flattened_size = 1024 * (final_size ** 3)
49
+
50
+ # Adaptive pooling to handle variable sizes
51
+ self.adaptive_pool = nn.AdaptiveAvgPool3d((4, 4, 4))
52
+ flattened_size = 1024 * 4 * 4 * 4
53
+
54
+ # Shared fully connected layers
55
+ self.shared_fc1 = nn.Linear(flattened_size, 1024)
56
+ self.shared_fc2 = nn.Linear(1024, 512)
57
+
58
+ # Position prediction head
59
+ self.pos_fc1 = nn.Linear(512, 512)
60
+ self.pos_fc2 = nn.Linear(512, 256)
61
+ self.pos_fc3 = nn.Linear(256, 128)
62
+ self.pos_fc4 = nn.Linear(128, output_dim)
63
+
64
+ # Score prediction head
65
+ if self.predict_score:
66
+ self.score_fc1 = nn.Linear(512, 512)
67
+ self.score_fc2 = nn.Linear(512, 256)
68
+ self.score_fc3 = nn.Linear(256, 128)
69
+ self.score_fc4 = nn.Linear(128, 64)
70
+ self.score_fc5 = nn.Linear(64, 1)
71
+
72
+ # Classification head
73
+ if self.predict_class:
74
+ self.class_fc1 = nn.Linear(512, 512)
75
+ self.class_fc2 = nn.Linear(512, 256)
76
+ self.class_fc3 = nn.Linear(256, 128)
77
+ self.class_fc4 = nn.Linear(128, 64)
78
+ self.class_fc5 = nn.Linear(64, num_classes)
79
+
80
+ # Dropout layers
81
+ self.dropout_light = nn.Dropout(0.2)
82
+ self.dropout_medium = nn.Dropout(0.3)
83
+ self.dropout_heavy = nn.Dropout(0.4)
84
+
85
+ def forward(self, x):
86
+ """
87
+ Forward pass
88
+ Args:
89
+ x: (batch_size, input_channels, voxel_size, voxel_size, voxel_size) tensor
90
+ Returns:
91
+ Tuple containing predictions based on configuration:
92
+ - position: (batch_size, output_dim) tensor of predicted 3D coordinates
93
+ - score: (batch_size, 1) tensor of predicted distance to GT (if predict_score=True)
94
+ - classification: (batch_size, num_classes) tensor of class logits (if predict_class=True)
95
+ """
96
+ batch_size = x.size(0)
97
+
98
+ # 3D Convolutional feature extraction
99
+ x1 = F.relu(self.bn1(self.conv1(x)))
100
+ x1 = self.pool(x1)
101
+
102
+ x2 = F.relu(self.bn2(self.conv2(x1)))
103
+ x2 = self.pool(x2)
104
+
105
+ x3 = F.relu(self.bn3(self.conv3(x2)))
106
+ x3 = self.pool(x3)
107
+
108
+ x4 = F.relu(self.bn4(self.conv4(x3)))
109
+ x5 = F.relu(self.bn5(self.conv5(x4)))
110
+ x6 = F.relu(self.bn6(self.conv6(x5)))
111
+
112
+ # Adaptive pooling to ensure consistent size
113
+ x6 = self.adaptive_pool(x6)
114
+
115
+ # Flatten for fully connected layers
116
+ global_features = x6.view(batch_size, -1)
117
+
118
+ # Shared features
119
+ shared1 = F.relu(self.shared_fc1(global_features))
120
+ shared1 = self.dropout_light(shared1)
121
+ shared2 = F.relu(self.shared_fc2(shared1))
122
+ shared_features = self.dropout_medium(shared2)
123
+
124
+ # Position prediction
125
+ pos1 = F.relu(self.pos_fc1(shared_features))
126
+ pos1 = self.dropout_light(pos1)
127
+ pos2 = F.relu(self.pos_fc2(pos1))
128
+ pos2 = self.dropout_medium(pos2)
129
+ pos3 = F.relu(self.pos_fc3(pos2))
130
+ pos3 = self.dropout_light(pos3)
131
+ position = self.pos_fc4(pos3)
132
+
133
+ outputs = [position]
134
+
135
+ if self.predict_score:
136
+ # Score prediction
137
+ score1 = F.relu(self.score_fc1(shared_features))
138
+ score1 = self.dropout_light(score1)
139
+ score2 = F.relu(self.score_fc2(score1))
140
+ score2 = self.dropout_medium(score2)
141
+ score3 = F.relu(self.score_fc3(score2))
142
+ score3 = self.dropout_light(score3)
143
+ score4 = F.relu(self.score_fc4(score3))
144
+ score4 = self.dropout_light(score4)
145
+ score = F.relu(self.score_fc5(score4))
146
+ outputs.append(score)
147
+
148
+ if self.predict_class:
149
+ # Classification prediction
150
+ class1 = F.relu(self.class_fc1(shared_features))
151
+ class1 = self.dropout_light(class1)
152
+ class2 = F.relu(self.class_fc2(class1))
153
+ class2 = self.dropout_medium(class2)
154
+ class3 = F.relu(self.class_fc3(class2))
155
+ class3 = self.dropout_light(class3)
156
+ class4 = F.relu(self.class_fc4(class3))
157
+ class4 = self.dropout_light(class4)
158
+ classification = self.class_fc5(class4)
159
+ outputs.append(classification)
160
+
161
+ # Return outputs based on configuration
162
+ if len(outputs) == 1:
163
+ return outputs[0]
164
+ elif len(outputs) == 2:
165
+ if self.predict_score:
166
+ return outputs[0], outputs[1]
167
+ else:
168
+ return outputs[0], outputs[1]
169
+ else:
170
+ return outputs[0], outputs[1], outputs[2]
171
+
172
+ def voxelize_patch(patch_7d: np.ndarray, voxel_size: int = 32, patch_size: float = 1.0) -> np.ndarray:
173
+ """
174
+ Convert point cloud patch to voxel grid.
175
+
176
+ Args:
177
+ patch_7d: (N, 7) array of points with [x, y, z, r, g, b, filtered_flag]
178
+ voxel_size: Size of the voxel grid (voxel_size^3)
179
+ patch_size: Physical size of the patch in world coordinates
180
+
181
+ Returns:
182
+ voxels: (7, voxel_size, voxel_size, voxel_size) array of voxelized features
183
+ """
184
+ if len(patch_7d) == 0:
185
+ return np.zeros((7, voxel_size, voxel_size, voxel_size))
186
+
187
+ # Extract coordinates and features
188
+ coords = patch_7d[:, :3] # x, y, z
189
+ features = patch_7d[:, 3:] # r, g, b, filtered_flag
190
+
191
+ # Normalize coordinates to [0, voxel_size-1]
192
+ coords_min = coords.min(axis=0)
193
+ coords_max = coords.max(axis=0)
194
+ coords_range = coords_max - coords_min
195
+ coords_range[coords_range == 0] = 1 # Avoid division by zero
196
+
197
+ normalized_coords = (coords - coords_min) / coords_range * (voxel_size - 1)
198
+ voxel_indices = normalized_coords.astype(int)
199
+
200
+ # Clip to valid range
201
+ voxel_indices = np.clip(voxel_indices, 0, voxel_size - 1)
202
+
203
+ # Initialize voxel grid
204
+ voxels = np.zeros((7, voxel_size, voxel_size, voxel_size))
205
+
206
+ # Fill voxels with features (average if multiple points fall in same voxel)
207
+ counts = np.zeros((voxel_size, voxel_size, voxel_size))
208
+
209
+ for i in range(len(patch_7d)):
210
+ x, y, z = voxel_indices[i]
211
+ # Store normalized coordinates in first 3 channels
212
+ voxels[0, x, y, z] += normalized_coords[i, 0] / (voxel_size - 1) # normalized x
213
+ voxels[1, x, y, z] += normalized_coords[i, 1] / (voxel_size - 1) # normalized y
214
+ voxels[2, x, y, z] += normalized_coords[i, 2] / (voxel_size - 1) # normalized z
215
+ # Store RGB and filtered_flag in remaining channels
216
+ voxels[3:, x, y, z] += features[i]
217
+ counts[x, y, z] += 1
218
+
219
+ # Average features where multiple points exist
220
+ mask = counts > 0
221
+ for c in range(7):
222
+ voxels[c][mask] /= counts[mask]
223
+
224
+ return voxels
225
+
226
+ class VoxelPatchDataset(Dataset):
227
+ """
228
+ Dataset class for loading saved patches and converting them to voxel grids for 3D CNN training.
229
+ """
230
+
231
+ def __init__(self, dataset_dir: str, voxel_size: int = 32, augment: bool = False):
232
+ self.dataset_dir = dataset_dir
233
+ self.voxel_size = voxel_size
234
+ self.augment = augment
235
+
236
+ # Load patch files
237
+ self.patch_files = []
238
+ for file in os.listdir(dataset_dir):
239
+ if file.endswith('.pkl'):
240
+ self.patch_files.append(os.path.join(dataset_dir, file))
241
+
242
+ print(f"Found {len(self.patch_files)} patch files in {dataset_dir}")
243
+
244
+ def __len__(self):
245
+ return len(self.patch_files)
246
+
247
+ def __getitem__(self, idx):
248
+ """
249
+ Load and process a patch for training.
250
+ Returns:
251
+ voxel_data: (7, voxel_size, voxel_size, voxel_size) tensor of voxelized data
252
+ target: (3,) tensor of target 3D coordinates
253
+ valid_mask: scalar tensor indicating if this is a valid sample
254
+ distance_to_gt: scalar tensor of distance from initial prediction to GT
255
+ classification: scalar tensor for binary classification (1 if GT vertex present, 0 if not)
256
+ """
257
+ patch_file = self.patch_files[idx]
258
+
259
+ with open(patch_file, 'rb') as f:
260
+ patch_info = pickle.load(f)
261
+
262
+ patch_7d = patch_info['patch_7d'] # (N, 7)
263
+ target = patch_info.get('assigned_wf_vertex', None) # (3,) or None
264
+ initial_pred = patch_info.get('cluster_center', None) # (3,) or None
265
+
266
+ # Determine classification label based on GT vertex presence
267
+ has_gt_vertex = 1.0 if target is not None else 0.0
268
+
269
+ # Handle patches without ground truth
270
+ if target is None:
271
+ target = np.zeros(3)
272
+ else:
273
+ target = np.array(target)
274
+
275
+ # Voxelize the patch
276
+ voxel_data = voxelize_patch(patch_7d, self.voxel_size)
277
+
278
+ # Data augmentation (only if GT vertex is present)
279
+ if self.augment and has_gt_vertex > 0:
280
+ voxel_data, target = self._augment_voxels(voxel_data, target)
281
+
282
+ # Convert to tensors (copy arrays to handle negative strides from augmentation)
283
+ voxel_tensor = torch.from_numpy(voxel_data.copy()).float() # (7, voxel_size, voxel_size, voxel_size)
284
+ target_tensor = torch.from_numpy(target.copy()).float() # (3,)
285
+
286
+ # Valid mask (check if voxel grid has any non-zero values)
287
+ valid_mask = torch.tensor(1.0 if voxel_data.sum() > 0 else 0.0)
288
+
289
+ # Handle initial_pred
290
+ if initial_pred is not None:
291
+ initial_pred_tensor = torch.from_numpy(initial_pred).float()
292
+ else:
293
+ initial_pred_tensor = torch.zeros(3).float()
294
+
295
+ # Classification tensor
296
+ classification_tensor = torch.tensor(has_gt_vertex).float()
297
+
298
+ return voxel_tensor, target_tensor, valid_mask, initial_pred_tensor, classification_tensor
299
+
300
+ def _augment_voxels(self, voxel_data: np.ndarray, target: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
301
+ """
302
+ Apply data augmentation to voxel data.
303
+ """
304
+ # Random rotation around Z-axis
305
+ if np.random.random() > 0.5:
306
+ k = np.random.randint(1, 4) # 90, 180, or 270 degrees
307
+ voxel_data = np.rot90(voxel_data, k, axes=(1, 2)) # Rotate around z-axis
308
+
309
+ # Random flip
310
+ if np.random.random() > 0.5:
311
+ voxel_data = np.flip(voxel_data, axis=1) # Flip along x-axis
312
+ if np.random.random() > 0.5:
313
+ voxel_data = np.flip(voxel_data, axis=2) # Flip along y-axis
314
+
315
+ return voxel_data, target
316
+
317
+ def save_patches_dataset(patches: List[Dict], dataset_dir: str, entry_id: str):
318
+ """
319
+ Save patches from prediction pipeline to create a training dataset.
320
+
321
+ Args:
322
+ patches: List of patch dictionaries from generate_patches()
323
+ dataset_dir: Directory to save the dataset
324
+ entry_id: Unique identifier for this entry/image
325
+ """
326
+ os.makedirs(dataset_dir, exist_ok=True)
327
+
328
+ for i, patch in enumerate(patches):
329
+ # Create unique filename
330
+ filename = f"{entry_id}_patch_{i}.pkl"
331
+ filepath = os.path.join(dataset_dir, filename)
332
+
333
+ # Skip if file already exists
334
+ if os.path.exists(filepath):
335
+ continue
336
+
337
+ # Save patch data
338
+ with open(filepath, 'wb') as f:
339
+ pickle.dump(patch, f)
340
+
341
+ print(f"Saved {len(patches)} patches for entry {entry_id}")
342
+
343
+ # Create dataloader with custom collate function to filter invalid samples
344
+ def collate_fn(batch):
345
+ valid_batch = []
346
+ for voxel_data, target, valid_mask, initial_pred, classification in batch:
347
+ # Filter out invalid samples
348
+ if valid_mask > 0:
349
+ valid_batch.append((voxel_data, target, valid_mask, initial_pred, classification))
350
+
351
+ if len(valid_batch) == 0:
352
+ return None
353
+
354
+ # Stack valid samples
355
+ voxel_data = torch.stack([item[0] for item in valid_batch])
356
+ targets = torch.stack([item[1] for item in valid_batch])
357
+ valid_masks = torch.stack([item[2] for item in valid_batch])
358
+ initial_preds = torch.stack([item[3] for item in valid_batch])
359
+ classifications = torch.stack([item[4] for item in valid_batch])
360
+
361
+ return voxel_data, targets, valid_masks, initial_preds, classifications
362
+
363
+ # Initialize weights using Xavier/Glorot initialization
364
+ def init_weights(m):
365
+ if isinstance(m, (nn.Conv3d, nn.Conv1d)):
366
+ nn.init.xavier_uniform_(m.weight)
367
+ if m.bias is not None:
368
+ nn.init.zeros_(m.bias)
369
+ elif isinstance(m, nn.Linear):
370
+ nn.init.xavier_uniform_(m.weight)
371
+ if m.bias is not None:
372
+ nn.init.zeros_(m.bias)
373
+ elif isinstance(m, (nn.BatchNorm3d, nn.BatchNorm1d)):
374
+ nn.init.ones_(m.weight)
375
+ nn.init.zeros_(m.bias)
376
+
377
+ def train_3dcnn(dataset_dir: str, model_save_path: str, epochs: int = 100, batch_size: int = 16, lr: float = 0.001,
378
+ voxel_size: int = 32, score_weight: float = 0.1, class_weight: float = 0.5):
379
+ """
380
+ Train the Fast3DCNN model on saved patches.
381
+
382
+ Args:
383
+ dataset_dir: Directory containing saved patch files
384
+ model_save_path: Path to save the trained model
385
+ epochs: Number of training epochs
386
+ batch_size: Training batch size (reduced due to memory requirements of 3D conv)
387
+ lr: Learning rate
388
+ voxel_size: Size of voxel grid
389
+ score_weight: Weight for the distance prediction loss
390
+ class_weight: Weight for the classification loss
391
+ """
392
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
393
+ print(f"Training on device: {device}")
394
+
395
+ # Create dataset and dataloader
396
+ dataset = VoxelPatchDataset(dataset_dir, voxel_size=voxel_size, augment=True)
397
+ print(f"Dataset loaded with {len(dataset)} samples")
398
+
399
+ dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=4,
400
+ collate_fn=collate_fn, drop_last=True)
401
+
402
+ # Initialize model with score and classification prediction
403
+ model = Fast3DCNN(input_channels=7, output_dim=3, voxel_size=voxel_size,
404
+ predict_score=True, predict_class=True, num_classes=1)
405
+
406
+ model.apply(init_weights)
407
+ model.to(device)
408
+
409
+ # Loss functions
410
+ position_criterion = nn.MSELoss()
411
+ score_criterion = nn.MSELoss()
412
+ classification_criterion = nn.BCEWithLogitsLoss()
413
+
414
+ optimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=1e-4)
415
+ scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=30, gamma=0.5)
416
+
417
+ # Training loop
418
+ model.train()
419
+ for epoch in range(epochs):
420
+ total_loss = 0.0
421
+ total_pos_loss = 0.0
422
+ total_score_loss = 0.0
423
+ total_class_loss = 0.0
424
+ num_batches = 0
425
+
426
+ for batch_idx, batch_data in enumerate(dataloader):
427
+ if batch_data is None: # Skip invalid batches
428
+ continue
429
+
430
+ voxel_data, targets, valid_masks, initial_preds, classifications = batch_data
431
+ voxel_data = voxel_data.to(device) # (batch_size, 7, voxel_size, voxel_size, voxel_size)
432
+ targets = targets.to(device) # (batch_size, 3)
433
+ classifications = classifications.to(device) # (batch_size,)
434
+
435
+ # Forward pass
436
+ optimizer.zero_grad()
437
+ predictions, predicted_scores, predicted_classes = model(voxel_data)
438
+
439
+ # Compute actual distance from predictions to targets
440
+ actual_distances = torch.norm(predictions - targets, dim=1, keepdim=True)
441
+
442
+ # Only compute position and score losses for samples with GT vertices
443
+ has_gt_mask = classifications > 0.5
444
+
445
+ if has_gt_mask.sum() > 0:
446
+ # Position loss only for samples with GT vertices
447
+ pos_loss = position_criterion(predictions[has_gt_mask], targets[has_gt_mask])
448
+ score_loss = score_criterion(predicted_scores[has_gt_mask], actual_distances[has_gt_mask])
449
+ else:
450
+ pos_loss = torch.tensor(0.0, device=device)
451
+ score_loss = torch.tensor(0.0, device=device)
452
+
453
+ # Classification loss for all samples
454
+ class_loss = classification_criterion(predicted_classes.squeeze(), classifications)
455
+
456
+ # Combined loss
457
+ total_batch_loss = pos_loss + score_weight * score_loss + class_weight * class_loss
458
+
459
+ # Backward pass
460
+ total_batch_loss.backward()
461
+ optimizer.step()
462
+
463
+ total_loss += total_batch_loss.item()
464
+ total_pos_loss += pos_loss.item()
465
+ total_score_loss += score_loss.item()
466
+ total_class_loss += class_loss.item()
467
+ num_batches += 1
468
+
469
+ if batch_idx % 50 == 0:
470
+ print(f"Epoch {epoch+1}/{epochs}, Batch {batch_idx}, "
471
+ f"Total Loss: {total_batch_loss.item():.6f}, "
472
+ f"Pos Loss: {pos_loss.item():.6f}, "
473
+ f"Score Loss: {score_loss.item():.6f}, "
474
+ f"Class Loss: {class_loss.item():.6f}")
475
+
476
+ avg_loss = total_loss / num_batches if num_batches > 0 else 0
477
+ avg_pos_loss = total_pos_loss / num_batches if num_batches > 0 else 0
478
+ avg_score_loss = total_score_loss / num_batches if num_batches > 0 else 0
479
+ avg_class_loss = total_class_loss / num_batches if num_batches > 0 else 0
480
+
481
+ print(f"Epoch {epoch+1}/{epochs} completed, "
482
+ f"Avg Total Loss: {avg_loss:.6f}, "
483
+ f"Avg Pos Loss: {avg_pos_loss:.6f}, "
484
+ f"Avg Score Loss: {avg_score_loss:.6f}, "
485
+ f"Avg Class Loss: {avg_class_loss:.6f}")
486
+
487
+ scheduler.step()
488
+
489
+ # Save model checkpoint every epoch
490
+ checkpoint_path = model_save_path.replace('.pth', f'_epoch_{epoch+1}.pth')
491
+ torch.save({
492
+ 'model_state_dict': model.state_dict(),
493
+ 'optimizer_state_dict': optimizer.state_dict(),
494
+ 'epoch': epoch + 1,
495
+ 'loss': avg_loss,
496
+ }, checkpoint_path)
497
+
498
+ # Save the trained model
499
+ torch.save({
500
+ 'model_state_dict': model.state_dict(),
501
+ 'optimizer_state_dict': optimizer.state_dict(),
502
+ 'epoch': epochs,
503
+ }, model_save_path)
504
+
505
+ print(f"Model saved to {model_save_path}")
506
+ return model
507
+
508
+ def load_3dcnn_model(model_path: str, device: torch.device = None, voxel_size: int = 32, predict_score: bool = True) -> Fast3DCNN:
509
+ """
510
+ Load a trained Fast3DCNN model.
511
+
512
+ Args:
513
+ model_path: Path to the saved model
514
+ device: Device to load the model on
515
+ voxel_size: Size of voxel grid
516
+ predict_score: Whether the model predicts scores
517
+
518
+ Returns:
519
+ Loaded Fast3DCNN model
520
+ """
521
+ if device is None:
522
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
523
+
524
+ model = Fast3DCNN(input_channels=7, output_dim=3, voxel_size=voxel_size, predict_score=predict_score)
525
+
526
+ checkpoint = torch.load(model_path, map_location=device)
527
+ model.load_state_dict(checkpoint['model_state_dict'])
528
+
529
+ model.to(device)
530
+ model.eval()
531
+
532
+ return model
533
+
534
+ def predict_vertex_from_patch(model: Fast3DCNN, patch: np.ndarray, device: torch.device = None, voxel_size: int = 32) -> Tuple[np.ndarray, float, float]:
535
+ """
536
+ Predict 3D vertex coordinates, confidence score, and classification from a patch using trained 3D CNN.
537
+
538
+ Args:
539
+ model: Trained Fast3DCNN model
540
+ patch: Dictionary containing patch data with 'patch_7d' and 'cluster_center' keys
541
+ device: Device to run prediction on
542
+ voxel_size: Size of voxel grid
543
+
544
+ Returns:
545
+ tuple of (predicted_coordinates, confidence_score, classification_score)
546
+ predicted_coordinates: (3,) numpy array of predicted 3D coordinates
547
+ confidence_score: float representing predicted distance to GT (lower is better)
548
+ classification_score: float representing probability of GT vertex presence (0-1)
549
+ """
550
+ if device is None:
551
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
552
+
553
+ patch_7d = patch['patch_7d'] # (N, 7)
554
+
555
+ # Voxelize the patch
556
+ voxel_data = voxelize_patch(patch_7d, voxel_size)
557
+
558
+ # Convert to tensor
559
+ voxel_tensor = torch.from_numpy(voxel_data).float().unsqueeze(0) # (1, 7, voxel_size, voxel_size, voxel_size)
560
+ voxel_tensor = voxel_tensor.to(device)
561
+
562
+ # Predict
563
+ with torch.no_grad():
564
+ outputs = model(voxel_tensor)
565
+
566
+ if model.predict_score and model.predict_class:
567
+ position, score, classification = outputs
568
+ position = position.cpu().numpy().squeeze()
569
+ score = score.cpu().numpy().squeeze()
570
+ classification = torch.sigmoid(classification).cpu().numpy().squeeze()
571
+ elif model.predict_score:
572
+ position, score = outputs
573
+ position = position.cpu().numpy().squeeze()
574
+ score = score.cpu().numpy().squeeze()
575
+ classification = None
576
+ elif model.predict_class:
577
+ position, classification = outputs
578
+ position = position.cpu().numpy().squeeze()
579
+ score = None
580
+ classification = torch.sigmoid(classification).cpu().numpy().squeeze()
581
+ else:
582
+ position = outputs
583
+ position = position.cpu().numpy().squeeze()
584
+ score = None
585
+ classification = None
586
+
587
+ # Apply offset correction
588
+ offset = patch['cluster_center']
589
+ position += offset
590
+
591
+ return position, score, classification
hoho_gpu_voxel.batch ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ #SBATCH --nodes=1 # 1 node
3
+ #SBATCH --ntasks-per-node=1 # 1 tasks per node
4
+ #SBATCH --cpus-per-task=16 # 6 CPUS per task = 12 CPUS per node
5
+ #SBATCH --mem-per-cpu=10G # 8GB per CPU = 96GB per node
6
+ #SBATCH --time=24:00:00 # time limits: 1 hour
7
+ #SBATCH --error=hoho_gpu.err # standard error file
8
+ #SBATCH --output=hoho_gpu.out # standard output file
9
+ #SBATCH --partition=amdgpu # partition name
10
+ #SBATCH --mail-user=skvrnjan@fel.cvut.cz # where send info about job
11
+ #SBATCH --mail-type=ALL # what to send, valid type values are NONE, BEGIN, END, FAIL, REQUEUE, ALL
12
+ #SBATCH --gres=gpu:1
13
+
14
+ cd /mnt/personal/skvrnjan/hoho/
15
+ module purge
16
+ module load Python/3.10.8-GCCcore-12.2.0
17
+ module load CUDA/12.6.0
18
+ source /mnt/personal/skvrnjan/venvs/hoho/bin/activate
19
+ python train_voxel_cluster.py
train_voxel.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fast_voxel import train_3dcnn
2
+ import os
3
+
4
+ if __name__ == "__main__":
5
+
6
+ # Load the dataset
7
+ dataset_path = "/home/skvrnjan/personal/hohocustom/"
8
+ model_save_path = "/home/skvrnjan/personal/hoho_voxel/"
9
+
10
+ os.makedirs(model_save_path, exist_ok=True)
11
+
12
+ # Train the model
13
+ train_3dcnn(dataset_path, model_save_path, epochs=100, batch_size=16, lr=0.001, voxel_size=32, score_weight=0.5, class_weight=0.5)
train_voxel_cluster.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fast_voxel import train_3dcnn
2
+ import os
3
+
4
+ if __name__ == "__main__":
5
+
6
+ # Load the dataset
7
+ dataset_path = "/mnt/personal/skvrnjan/hohocustom/"
8
+ model_save_path = "/mnt/personal/skvrnjan/hoho_voxel/initial.pth"
9
+
10
+ os.makedirs(model_save_path, exist_ok=True)
11
+
12
+ # Train the model
13
+ train_3dcnn(dataset_path, model_save_path, epochs=100, batch_size=128, lr=0.001, voxel_size=32, score_weight=0.5, class_weight=0.5)