I'll help you implement a contrastive learning approach for your B-Rep CAD models. Let's start with the dataset class and then build the training pipeline.
import os
import torch
from torch_geometric.data import Dataset, Data
import glob
import re
class CADPairDataset(Dataset):
def __init__(self, root, transform=None, pre_transform=None):
"""
Dataset for CAD model pairs (coarse and split versions)
Args:
root: Root directory where the processed data is stored
transform: Optional transform to be applied on a sample
pre_transform: Optional transform to be applied before saving
"""
super(CADPairDataset, self).__init__(root, transform, pre_transform)
@property
def raw_file_names(self):
return []
@property
def processed_file_names(self):
# Return all processed file pairs
return glob.glob(os.path.join(self.processed_dir, "*.pt"))
def process(self):
# This method should be implemented if you need to process raw files
# In this case, we assume the .pt files are already processed
pass
def len(self):
# Count unique model IDs (without _aug suffix)
unique_models = set()
for file_path in self.processed_file_names:
file_name = os.path.basename(file_path)
# Remove _aug suffix if present
model_id = re.sub(r'_aug\.pt$', '.pt', file_name)
unique_models.add(model_id)
return len(unique_models)
def get(self, idx):
# Get all file paths
all_files = sorted(self.processed_file_names)
# Extract unique model IDs
unique_models = sorted(set(re.sub(r'_aug\.pt$', '.pt', os.path.basename(f))
for f in all_files))
# Get the model ID for this index
model_id = unique_models[idx]
model_base = os.path.splitext(model_id)[0]
# Find the coarse and split versions
coarse_path = os.path.join(self.processed_dir, model_id)
split_path = os.path.join(self.processed_dir, f"{model_base}_aug.pt")
# Load both graphs
coarse_graph = torch.load(coarse_path)
split_graph = torch.load(split_path)
return coarse_graph, split_graph
Now, let's implement the contrastive learning framework with a projection head and SimCLR-style loss:
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import global_mean_pool
from torch_geometric.loader import DataLoader
import numpy as np
class ProjectionHead(nn.Module):
def __init__(self, input_dim, hidden_dim=256, output_dim=128):
super(ProjectionHead, self).__init__()
self.projection = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.BatchNorm1d(hidden_dim),
nn.ReLU(inplace=True),
nn.Linear(hidden_dim, output_dim)
)
def forward(self, x):
return F.normalize(self.projection(x), p=2, dim=1)
class CADContrastiveModel(nn.Module):
def __init__(self, encoder, projection_dim=128):
super(CADContrastiveModel, self).__init__()
self.encoder = encoder
self.projection = ProjectionHead(
input_dim=encoder.out_channels,
output_dim=projection_dim
)
def forward(self, x):
# Get node embeddings from the encoder
node_embeddings = self.encoder(x.x, x.edge_index, x.edge_attr)
# Pool to get graph-level embedding
graph_embedding = global_mean_pool(node_embeddings, x.batch)
# Project to get the final representation
projection = self.projection(graph_embedding)
return projection, graph_embedding
def contrastive_loss(z1, z2, temperature=0.1):
"""
SimCLR contrastive loss function
Args:
z1, z2: Batch of projected embeddings [batch_size, projection_dim]
temperature: Temperature parameter for softmax
"""
batch_size = z1.shape[0]
# Concatenate embeddings from both views
z = torch.cat([z1, z2], dim=0)
# Compute similarity matrix
sim = torch.mm(z, z.t().contiguous()) / temperature
# Mask out self-similarity
sim_i_j = torch.diag(sim, batch_size)
sim_j_i = torch.diag(sim, -batch_size)
# Positive pairs
positive_samples = torch.cat([sim_i_j, sim_j_i], dim=0).reshape(2 * batch_size, 1)
# Mask out self-similarity and positive pairs for negative samples
mask = torch.ones_like(sim)
mask = mask.fill_diagonal_(0)
for i in range(batch_size):
mask[i, batch_size + i] = 0
mask[batch_size + i, i] = 0
# Get negative samples
negative_samples = sim[mask.bool()].reshape(2 * batch_size, -1)
# InfoNCE loss
logits = torch.cat([positive_samples, negative_samples], dim=1)
labels = torch.zeros(2 * batch_size, dtype=torch.long, device=z1.device)
return F.cross_entropy(logits, labels)
def train_contrastive(model, train_loader, optimizer, device, epoch):
model.train()
total_loss = 0
for batch_idx, (coarse_graphs, split_graphs) in enumerate(train_loader):
# Move data to device
coarse_graphs = coarse_graphs.to(device)
split_graphs = split_graphs.to(device)
# Zero gradients
optimizer.zero_grad()
# Forward pass for both views
z1, h1 = model(coarse_graphs)
z2, h2 = model(split_graphs)
# Compute contrastive loss
loss = contrastive_loss(z1, z2)
# Backward pass
loss.backward()
optimizer.step()
total_loss += loss.item()
if batch_idx % 10 == 0:
print(f'Epoch: {epoch}, Batch: {batch_idx}, Loss: {loss.item():.6f}')
avg_loss = total_loss / len(train_loader)
print(f'Epoch: {epoch}, Average Loss: {avg_loss:.6f}')
return avg_loss
def pretrain_model(encoder, dataset, batch_size=32, epochs=100, lr=0.0001, device='cuda'):
"""
Pretrain the encoder using contrastive learning
Args:
encoder: The graph neural network encoder
dataset: CADPairDataset instance
batch_size: Batch size for training
epochs: Number of training epochs
lr: Learning rate
device: Device to use for training
Returns:
Pretrained encoder
"""
# Create data loader
train_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
# Create model
model = CADContrastiveModel(encoder).to(device)
# Optimizer
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
# Learning rate scheduler
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=epochs)
# Training loop
for epoch in range(1, epochs + 1):
loss = train_contrastive(model, train_loader, optimizer, device, epoch)
scheduler.step()
# Return the pretrained encoder
return model.encoder