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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
from torch import nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import itertools
|
| 6 |
+
import numpy as np
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
from torch.utils.data import DataLoader, DistributedSampler
|
| 9 |
+
from torch.nn.parallel import DistributedDataParallel as DDP
|
| 10 |
+
from torch.distributed import init_process_group, destroy_process_group
|
| 11 |
+
from torch.utils.data import TensorDataset
|
| 12 |
+
from datetime import datetime
|
| 13 |
+
from torch.optim.lr_scheduler import LambdaLR
|
| 14 |
+
import sys
|
| 15 |
+
from utils.logger import Logger
|
| 16 |
+
from dataset.data_util import MinMaxScaler, TrajectoryDataset
|
| 17 |
+
from utils.utils import IterativeKMeans, assign_labels, get_positive_negative_pairs, mask_data_general, get_data_paths, continuous_mask_data, continuous_time_based_mask, mask_multiple_segments
|
| 18 |
+
from diffProModel.loss import ContrastiveLoss
|
| 19 |
+
from diffProModel.protoTrans import TrajectoryTransformer
|
| 20 |
+
from diffProModel.Diffusion import Diffusion
|
| 21 |
+
from test import test_model # Import test_model
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def ddp_setup(distributed):
|
| 25 |
+
"""Initialize the process group for distributed data parallel if distributed is True."""
|
| 26 |
+
if distributed:
|
| 27 |
+
if not torch.distributed.is_initialized():
|
| 28 |
+
init_process_group(backend="nccl")
|
| 29 |
+
torch.cuda.set_device(int(os.environ['LOCAL_RANK']))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def setup_model_save_directory(exp_dir, timestamp):
|
| 33 |
+
"""Set up the directory for saving model checkpoints."""
|
| 34 |
+
model_save_path = exp_dir / 'models' / (timestamp + '/')
|
| 35 |
+
os.makedirs(model_save_path, exist_ok=True)
|
| 36 |
+
return model_save_path
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def lr_lambda_fn(current_epoch, warmup_epochs, total_epochs):
|
| 40 |
+
if current_epoch < warmup_epochs:
|
| 41 |
+
return float(current_epoch) / float(max(1, warmup_epochs))
|
| 42 |
+
return 0.5 * (1. + torch.cos(torch.tensor(torch.pi * (current_epoch - warmup_epochs) / float(total_epochs - warmup_epochs))))
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def train_main(config, logger, exp_dir, timestamp_str):
|
| 46 |
+
"""Main function to run the training and testing pipeline for DDPM or DDIM."""
|
| 47 |
+
distributed = config.dis_gpu
|
| 48 |
+
local_rank = 0 # Default for non-DDP logging/master tasks
|
| 49 |
+
#logger.info(config.validation_freq) # 1
|
| 50 |
+
if distributed:
|
| 51 |
+
ddp_setup(distributed) # This also calls torch.cuda.set_device(os.environ['LOCAL_RANK'])
|
| 52 |
+
local_rank = int(os.environ['LOCAL_RANK'])
|
| 53 |
+
device = torch.device(f'cuda:{local_rank}')
|
| 54 |
+
else:
|
| 55 |
+
device_id_to_use = config.device_id
|
| 56 |
+
if torch.cuda.is_available():
|
| 57 |
+
torch.cuda.set_device(device_id_to_use)
|
| 58 |
+
device = torch.device(f'cuda:{device_id_to_use}')
|
| 59 |
+
else:
|
| 60 |
+
device = torch.device('cpu')
|
| 61 |
+
|
| 62 |
+
train_file_paths = get_data_paths(config.data, for_train=True)
|
| 63 |
+
|
| 64 |
+
diffusion_model = Diffusion(loss_type=config.model.loss_type, config=config).to(device)
|
| 65 |
+
|
| 66 |
+
lr = config.learning_rate
|
| 67 |
+
model_save_dir = setup_model_save_directory(exp_dir, timestamp_str)
|
| 68 |
+
|
| 69 |
+
train_dataset = TrajectoryDataset(train_file_paths, config.data.traj_length)
|
| 70 |
+
train_sampler = DistributedSampler(train_dataset, shuffle=True) if distributed else None
|
| 71 |
+
train_dataloader = DataLoader(train_dataset,
|
| 72 |
+
batch_size=config.batch_size,
|
| 73 |
+
shuffle=(train_sampler is None),
|
| 74 |
+
num_workers=config.data.num_workers,
|
| 75 |
+
drop_last=True,
|
| 76 |
+
sampler=train_sampler,
|
| 77 |
+
pin_memory=True)
|
| 78 |
+
|
| 79 |
+
# Create Test DataLoader
|
| 80 |
+
test_file_paths = get_data_paths(config.data, for_train=False)
|
| 81 |
+
test_dataset = TrajectoryDataset(test_file_paths, config.data.traj_length)
|
| 82 |
+
test_dataloader = DataLoader(test_dataset,
|
| 83 |
+
batch_size=config.sampling.batch_size, # Use sampling batch_size from config
|
| 84 |
+
shuffle=False,
|
| 85 |
+
num_workers=config.data.num_workers,
|
| 86 |
+
drop_last=False, # Typically False for full test set evaluation
|
| 87 |
+
pin_memory=True)
|
| 88 |
+
|
| 89 |
+
if distributed:
|
| 90 |
+
diffusion_model = DDP(diffusion_model, device_ids=[local_rank], find_unused_parameters=False)
|
| 91 |
+
|
| 92 |
+
short_samples_model = TrajectoryTransformer(
|
| 93 |
+
input_dim=config.trans.input_dim,
|
| 94 |
+
embed_dim=config.trans.embed_dim,
|
| 95 |
+
num_layers=config.trans.num_layers,
|
| 96 |
+
num_heads=config.trans.num_heads,
|
| 97 |
+
forward_dim=config.trans.forward_dim,
|
| 98 |
+
seq_len=config.data.traj_length,
|
| 99 |
+
n_cluster=config.trans.N_CLUSTER,
|
| 100 |
+
dropout=config.trans.dropout
|
| 101 |
+
).to(device)
|
| 102 |
+
|
| 103 |
+
if distributed:
|
| 104 |
+
short_samples_model = DDP(short_samples_model, device_ids=[local_rank], find_unused_parameters=False)
|
| 105 |
+
|
| 106 |
+
optim = torch.optim.AdamW(itertools.chain(diffusion_model.parameters(), short_samples_model.parameters()), lr=lr, foreach=False)
|
| 107 |
+
|
| 108 |
+
warmup_epochs = config.warmup_epochs
|
| 109 |
+
total_epochs = config.n_epochs
|
| 110 |
+
scheduler = LambdaLR(optim, lr_lambda=lambda epoch: lr_lambda_fn(epoch, warmup_epochs, total_epochs))
|
| 111 |
+
|
| 112 |
+
losses_dict = {}
|
| 113 |
+
contrastive_loss_fn = ContrastiveLoss(margin=config.contrastive_margin)
|
| 114 |
+
ce_loss_fn = nn.CrossEntropyLoss()
|
| 115 |
+
|
| 116 |
+
for epoch in range(1, config.n_epochs + 1):
|
| 117 |
+
if distributed:
|
| 118 |
+
train_sampler.set_epoch(epoch)
|
| 119 |
+
|
| 120 |
+
epoch_losses = []
|
| 121 |
+
previous_features_for_kmeans = []
|
| 122 |
+
|
| 123 |
+
if local_rank == 0:
|
| 124 |
+
logger.info(f"<----Epoch-{epoch}---->")
|
| 125 |
+
|
| 126 |
+
kmeans = IterativeKMeans(num_clusters=config.trans.N_CLUSTER, device=device)
|
| 127 |
+
|
| 128 |
+
pbar = tqdm(train_dataloader, desc=f"Epoch {epoch} Training", disable=(local_rank != 0))
|
| 129 |
+
for batch_idx, (abs_time, lat, lng) in enumerate(pbar):
|
| 130 |
+
trainx_raw = torch.stack([abs_time, lat, lng], dim=-1).to(device)
|
| 131 |
+
|
| 132 |
+
# Use global normalization parameters to avoid per-batch inconsistency
|
| 133 |
+
scaler = MinMaxScaler(global_params_file='./data/robust_normalization_params.json')
|
| 134 |
+
scaler.fit(trainx_raw) # This does nothing for global scaler, but maintains interface
|
| 135 |
+
trainx_scaled = scaler.transform(trainx_raw)
|
| 136 |
+
|
| 137 |
+
prototypes_from_transformer, features_for_kmeans_and_contrastive = short_samples_model(trainx_scaled)
|
| 138 |
+
|
| 139 |
+
if not previous_features_for_kmeans:
|
| 140 |
+
current_batch_prototypes_kmeans, _ = kmeans.fit(features_for_kmeans_and_contrastive.detach())
|
| 141 |
+
else:
|
| 142 |
+
features_memory = torch.cat(previous_features_for_kmeans, dim=0).detach()
|
| 143 |
+
current_batch_prototypes_kmeans, _ = kmeans.update(features_for_kmeans_and_contrastive.detach(), features_memory)
|
| 144 |
+
|
| 145 |
+
if len(previous_features_for_kmeans) < config.kmeans_memory_size:
|
| 146 |
+
previous_features_for_kmeans.append(features_for_kmeans_and_contrastive.detach())
|
| 147 |
+
elif config.kmeans_memory_size > 0 :
|
| 148 |
+
previous_features_for_kmeans.pop(0)
|
| 149 |
+
previous_features_for_kmeans.append(features_for_kmeans_and_contrastive.detach())
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
# Permute the dimensions to match the model's expected input shape
|
| 153 |
+
x0_for_diffusion = trainx_scaled.permute(0, 2, 1)
|
| 154 |
+
|
| 155 |
+
# Apply masking
|
| 156 |
+
if config.masking_strategy == 'general':
|
| 157 |
+
masked_x0_condition_diffusion = mask_data_general(x0_for_diffusion)
|
| 158 |
+
elif config.masking_strategy == 'continuous':
|
| 159 |
+
masked_x0_condition_diffusion = continuous_mask_data(x0_for_diffusion, config.mask_ratio)
|
| 160 |
+
elif config.masking_strategy == 'time_based':
|
| 161 |
+
masked_x0_condition_diffusion = continuous_time_based_mask(x0_for_diffusion, points_to_mask=config.mask_points_per_hour)
|
| 162 |
+
elif config.masking_strategy == 'multi_segment':
|
| 163 |
+
masked_x0_condition_diffusion = mask_multiple_segments(x0_for_diffusion, points_per_segment=config.mask_segments)
|
| 164 |
+
else:
|
| 165 |
+
raise ValueError(f"Unknown masking strategy: {config.masking_strategy}")
|
| 166 |
+
|
| 167 |
+
masked_x0_permuted_for_ssm = masked_x0_condition_diffusion.permute(0, 2, 1)
|
| 168 |
+
|
| 169 |
+
with torch.no_grad():
|
| 170 |
+
_, query_features_from_masked = short_samples_model(masked_x0_permuted_for_ssm)
|
| 171 |
+
|
| 172 |
+
cos_sim = F.cosine_similarity(query_features_from_masked.unsqueeze(1), prototypes_from_transformer.unsqueeze(0), dim=-1)
|
| 173 |
+
d_k = query_features_from_masked.size(-1)
|
| 174 |
+
scaled_cos_sim = F.softmax(cos_sim / np.sqrt(d_k), dim=-1)
|
| 175 |
+
matched_prototypes_for_diffusion = torch.matmul(scaled_cos_sim, prototypes_from_transformer)
|
| 176 |
+
|
| 177 |
+
positive_pairs, negative_pairs = get_positive_negative_pairs(prototypes_from_transformer, features_for_kmeans_and_contrastive)
|
| 178 |
+
contrastive_loss_val = contrastive_loss_fn(features_for_kmeans_and_contrastive, positive_pairs, negative_pairs)
|
| 179 |
+
contrastive_loss_val = contrastive_loss_val * config.contrastive_loss_weight
|
| 180 |
+
|
| 181 |
+
labels_from_transformer_protos = assign_labels(prototypes_from_transformer.detach(), features_for_kmeans_and_contrastive.detach()).long()
|
| 182 |
+
labels_from_kmeans = kmeans.predict(features_for_kmeans_and_contrastive.detach()).long()
|
| 183 |
+
|
| 184 |
+
ce_loss_val = torch.tensor(0.0, device=device)
|
| 185 |
+
if config.ce_loss_weight > 0:
|
| 186 |
+
logits_for_ce = features_for_kmeans_and_contrastive @ F.normalize(prototypes_from_transformer.detach(), dim=-1).T
|
| 187 |
+
ce_loss_val = ce_loss_fn(logits_for_ce, labels_from_kmeans)
|
| 188 |
+
ce_loss_val = ce_loss_val * config.ce_loss_weight
|
| 189 |
+
|
| 190 |
+
diffusion_model_ref = diffusion_model.module if distributed else diffusion_model
|
| 191 |
+
diffusion_loss_val = diffusion_model_ref.trainer(
|
| 192 |
+
x0_for_diffusion.float(),
|
| 193 |
+
masked_x0_condition_diffusion.float(),
|
| 194 |
+
matched_prototypes_for_diffusion.float(),
|
| 195 |
+
weights=config.diffusion_loss_weight
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
total_loss = diffusion_loss_val + ce_loss_val + contrastive_loss_val
|
| 199 |
+
|
| 200 |
+
optim.zero_grad()
|
| 201 |
+
total_loss.backward()
|
| 202 |
+
torch.nn.utils.clip_grad_norm_(itertools.chain(diffusion_model.parameters(), short_samples_model.parameters()), max_norm=1.0)
|
| 203 |
+
optim.step()
|
| 204 |
+
|
| 205 |
+
epoch_losses.append(total_loss.item())
|
| 206 |
+
if local_rank == 0:
|
| 207 |
+
pbar.set_postfix({
|
| 208 |
+
'Loss': total_loss.item(),
|
| 209 |
+
'Diff': diffusion_loss_val.item(),
|
| 210 |
+
'Cont': contrastive_loss_val.item(),
|
| 211 |
+
'CE': ce_loss_val.item(),
|
| 212 |
+
'LR': optim.param_groups[0]['lr']
|
| 213 |
+
})
|
| 214 |
+
|
| 215 |
+
avg_epoch_loss = sum(epoch_losses) / len(epoch_losses) if epoch_losses else 0
|
| 216 |
+
losses_dict[epoch] = avg_epoch_loss
|
| 217 |
+
scheduler.step()
|
| 218 |
+
|
| 219 |
+
if local_rank == 0:
|
| 220 |
+
logger.info(f"Epoch {epoch} Avg Loss: {avg_epoch_loss:.4f}")
|
| 221 |
+
logger.info(f"Current LR: {optim.param_groups[0]['lr']:.6f}")
|
| 222 |
+
|
| 223 |
+
if epoch % config.validation_freq == 0 and local_rank == 0:
|
| 224 |
+
# Save model snapshot
|
| 225 |
+
diffusion_state_dict = diffusion_model.module.state_dict() if distributed else diffusion_model.state_dict()
|
| 226 |
+
transformer_state_dict = short_samples_model.module.state_dict() if distributed else short_samples_model.state_dict()
|
| 227 |
+
|
| 228 |
+
torch.save(diffusion_state_dict, model_save_dir / f"diffusion_model_epoch_{epoch}.pt")
|
| 229 |
+
torch.save(transformer_state_dict, model_save_dir / f"transformer_epoch_{epoch}.pt")
|
| 230 |
+
|
| 231 |
+
if 'prototypes_from_transformer' in locals(): # Check if prototypes were generated in this epoch
|
| 232 |
+
np.save(model_save_dir / f"prototypes_transformer_epoch_{epoch}.npy", prototypes_from_transformer.detach().cpu().numpy())
|
| 233 |
+
|
| 234 |
+
all_losses_path = exp_dir / 'results' / 'all_epoch_losses.npy'
|
| 235 |
+
current_losses_to_save = {e: l for e, l in losses_dict.items()}
|
| 236 |
+
if os.path.exists(all_losses_path):
|
| 237 |
+
try:
|
| 238 |
+
existing_losses = np.load(all_losses_path, allow_pickle=True).item()
|
| 239 |
+
existing_losses.update(current_losses_to_save)
|
| 240 |
+
np.save(all_losses_path, existing_losses)
|
| 241 |
+
except Exception as e:
|
| 242 |
+
if logger: logger.error(f"Error loading/updating losses file: {e}. Saving current losses only.")
|
| 243 |
+
np.save(all_losses_path, current_losses_to_save)
|
| 244 |
+
else:
|
| 245 |
+
np.save(all_losses_path, current_losses_to_save)
|
| 246 |
+
if logger: logger.info(f"Saved model and prototypes snapshot at epoch {epoch} to {model_save_dir}")
|
| 247 |
+
|
| 248 |
+
# Periodic validation call
|
| 249 |
+
if logger: logger.info(f"--- Starting validation for epoch {epoch} ---")
|
| 250 |
+
|
| 251 |
+
diffusion_model_to_test = diffusion_model.module if distributed else diffusion_model
|
| 252 |
+
short_samples_model_to_test = short_samples_model.module if distributed else short_samples_model
|
| 253 |
+
|
| 254 |
+
diffusion_model_to_test.eval()
|
| 255 |
+
short_samples_model_to_test.eval()
|
| 256 |
+
|
| 257 |
+
current_prototypes_for_test = short_samples_model_to_test.prototypes.detach()
|
| 258 |
+
|
| 259 |
+
with torch.no_grad():
|
| 260 |
+
test_model(
|
| 261 |
+
test_dataloader=test_dataloader,
|
| 262 |
+
diffusion_model=diffusion_model_to_test,
|
| 263 |
+
short_samples_model=short_samples_model_to_test,
|
| 264 |
+
config=config,
|
| 265 |
+
epoch=epoch,
|
| 266 |
+
prototypes=current_prototypes_for_test,
|
| 267 |
+
device=device,
|
| 268 |
+
logger=logger,
|
| 269 |
+
exp_dir=exp_dir
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
diffusion_model_to_test.train()
|
| 273 |
+
short_samples_model_to_test.train()
|
| 274 |
+
if logger: logger.info(f"--- Finished validation for epoch {epoch} ---")
|
| 275 |
+
|
| 276 |
+
if distributed:
|
| 277 |
+
destroy_process_group()
|
| 278 |
+
if logger and local_rank == 0: # Ensure logger calls are rank-specific
|
| 279 |
+
logger.info("Training finished.")
|