File size: 25,931 Bytes
0bd444e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
import os
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from timm.models.layers import trunc_normal_
from einops import rearrange
import numpy as np
from typing import List, Dict, Any
import matplotlib.pyplot as plt
import json
import random
import time
from clean_eval import evaluate as rollout_evaluate

# ============================================================================ 
# 1. PYTORCH DATASET CLASS FOR TIME-STEPPED DATA
# ============================================================================ 
class TimeStepDataset(Dataset):
    """Dataset for flattened timestep training data"""

    def __init__(self, pt_file_path: str):
        if not os.path.exists(pt_file_path):
            raise FileNotFoundError(f"Dataset file not found at: {pt_file_path}")
        self.data = torch.load(pt_file_path, weights_only=False)
        print(f"Loaded {len(self.data)} timesteps from {pt_file_path}")

    def __len__(self) -> int:
        return len(self.data)

    def __getitem__(self, idx: int) -> Dict[str, Any]:
        sample = self.data[idx]
        return {
            'coordinates': sample['coordinates'],
            'node_type': sample['node_type'],
            'current_velocities': sample['current_velocities'],
            'target_velocities': sample['target_velocities'],
            'meta_info': sample['meta_info']
        }

class TrajectoryDataset(Dataset):
    """Dataset for full trajectory evaluation data"""

    def __init__(self, pt_file_path: str):
        if not os.path.exists(pt_file_path):
            raise FileNotFoundError(f"Dataset file not found at: {pt_file_path}")
        self.trajectories = torch.load(pt_file_path, weights_only=False)
        print(f"Loaded {len(self.trajectories)} trajectories from {pt_file_path}")

    def __len__(self) -> int:
        return len(self.trajectories)

    def __getitem__(self, idx: int) -> Dict[str, Any]:
        return self.trajectories[idx]

# ============================================================================ 
# 2. TRANSOLVER MODEL ARCHITECTURE (Adapted for Time-Dependent Prediction)
# ============================================================================ 
ACTIVATION = {'gelu': nn.GELU, 'tanh': nn.Tanh, 'sigmoid': nn.Sigmoid, 'relu': nn.ReLU, 'leaky_relu': nn.LeakyReLU(0.1)}

class MLP(nn.Module):
    def __init__(self, n_input, n_hidden, n_output, n_layers=1, act='gelu', res=True):
        super(MLP, self).__init__()
        if act in ACTIVATION.keys():
            act = ACTIVATION[act]
        else:
            raise NotImplementedError
        self.linear_pre = nn.Sequential(nn.Linear(n_input, n_hidden), act())
        self.linear_post = nn.Linear(n_hidden, n_output)
        self.linears = nn.ModuleList([nn.Sequential(nn.Linear(n_hidden, n_hidden), act()) for _ in range(n_layers)])
        self.res = res

    def forward(self, x):
        x = self.linear_pre(x)
        for i in range(len(self.linears)):
            if self.res:
                x = self.linears[i](x) + x
            else:
                x = self.linears[i](x)
        x = self.linear_post(x)
        return x

class Physics_Attention_Irregular_Mesh(nn.Module):
    def __init__(self, dim, heads=8, dim_head=64, dropout=0., slice_num=64):
        super().__init__()
        inner_dim = dim_head * heads
        self.dim_head = dim_head
        self.heads = heads
        self.scale = dim_head ** -0.5
        self.softmax = nn.Softmax(dim=-1)
        self.dropout = nn.Dropout(dropout)
        self.temperature = nn.Parameter(torch.ones([1, heads, 1, 1]) * 0.5)
        self.in_project_x = nn.Linear(dim, inner_dim)
        self.in_project_fx = nn.Linear(dim, inner_dim)
        self.in_project_slice = nn.Linear(dim_head, slice_num)
        torch.nn.init.orthogonal_(self.in_project_slice.weight)
        self.to_q = nn.Linear(dim_head, dim_head, bias=False)
        self.to_k = nn.Linear(dim_head, dim_head, bias=False)
        self.to_v = nn.Linear(dim_head, dim_head, bias=False)
        self.to_out = nn.Sequential(nn.Linear(inner_dim, dim), nn.Dropout(dropout))

    def forward(self, x):
        B, N, C = x.shape
        fx_mid = self.in_project_fx(x).reshape(B, N, self.heads, self.dim_head).permute(0, 2, 1, 3).contiguous()
        x_mid = self.in_project_x(x).reshape(B, N, self.heads, self.dim_head).permute(0, 2, 1, 3).contiguous()
        slice_weights = self.softmax(self.in_project_slice(x_mid) / self.temperature)
        slice_norm = slice_weights.sum(2)
        slice_token = torch.einsum("bhnc,bhng->bhgc", fx_mid, slice_weights)
        slice_token = slice_token / ((slice_norm + 1e-5)[:, :, :, None].repeat(1, 1, 1, self.dim_head))
        q_slice_token = self.to_q(slice_token)
        k_slice_token = self.to_k(slice_token)
        v_slice_token = self.to_v(slice_token)
        dots = torch.matmul(q_slice_token, k_slice_token.transpose(-1, -2)) * self.scale
        attn = self.softmax(dots)
        attn = self.dropout(attn)
        out_slice_token = torch.matmul(attn, v_slice_token)
        out_x = torch.einsum("bhgc,bhng->bhnc", out_slice_token, slice_weights)
        out_x = rearrange(out_x, 'b h n d -> b n (h d)')
        out = self.to_out(out_x)
        return out

class Transolver_block(nn.Module):
    def __init__(self, num_heads, hidden_dim, dropout, act='gelu', mlp_ratio=4, last_layer=False, out_dim=1, slice_num=32):
        super().__init__()
        self.last_layer = last_layer
        self.ln_1 = nn.LayerNorm(hidden_dim)
        self.Attn = Physics_Attention_Irregular_Mesh(hidden_dim, heads=num_heads, dim_head=hidden_dim // num_heads, dropout=dropout, slice_num=slice_num)
        self.ln_2 = nn.LayerNorm(hidden_dim)
        self.mlp = MLP(hidden_dim, hidden_dim * mlp_ratio, hidden_dim, n_layers=0, res=False, act=act)
        if self.last_layer:
            self.ln_3 = nn.LayerNorm(hidden_dim)
            self.mlp2 = nn.Linear(hidden_dim, out_dim)

    def forward(self, fx):
        fx2 = self.Attn(self.ln_1(fx)) + fx
        fx = self.mlp(self.ln_2(fx2)) + fx2
        if self.last_layer:
            return self.mlp2(self.ln_3(fx))
        return fx

class Model(nn.Module):
    def __init__(self, in_dim=13, out_dim=3, n_layers=8, n_hidden=256, dropout=0, n_head=8, act='gelu', mlp_ratio=2, slice_num=32):
        super(Model, self).__init__()
        self.preprocess = MLP(in_dim, n_hidden * 2, n_hidden, n_layers=0, res=False, act=act)
        self.n_hidden = n_hidden
        self.blocks = nn.ModuleList([Transolver_block(num_heads=n_head, hidden_dim=n_hidden, dropout=dropout,
                                                      act=act, mlp_ratio=mlp_ratio,
                                                      out_dim=out_dim,
                                                      slice_num=slice_num,
                                                      last_layer=(_ == n_layers - 1))
                                     for _ in range(n_layers)])
        self.initialize_weights()
        self.placeholder = nn.Parameter((1 / n_hidden) * torch.rand(n_hidden, dtype=torch.float))

    def initialize_weights(self):
        self.apply(self._init_weights)

    def _init_weights(self, m):
        if isinstance(m, nn.Linear):
            trunc_normal_(m.weight, std=0.02)
            if isinstance(m, nn.Linear) and m.bias is not None:
                nn.init.constant_(m.bias, 0)
        elif isinstance(m, (nn.LayerNorm, nn.BatchNorm1d)):
            nn.init.constant_(m.bias, 0)
            nn.init.constant_(m.weight, 1.0)

    def forward(self, x):
        fx = self.preprocess(x)
        fx = fx + self.placeholder[None, None, :] 
        for block in self.blocks:
            fx = block(fx)
        return fx

# ============================================================================ 
# 3. CHECKPOINTING FUNCTIONS
# ============================================================================ 
def save_checkpoint(model, optimizer, scheduler, epoch, loss, path, norm_stats):
    """Save training checkpoint"""
    checkpoint = {
        'epoch': epoch,
        'model_state_dict': model.state_dict(),
        'optimizer_state_dict': optimizer.state_dict(),
        'scheduler_state_dict': scheduler.state_dict() if scheduler else None,
        'loss': loss,
        'norm_stats': norm_stats  # Save normalization stats
    }
    torch.save(checkpoint, path)
    print(f"Checkpoint saved: {path}")

def load_checkpoint(model, optimizer, scheduler, path):
    """Load training checkpoint"""
    checkpoint = torch.load(path, map_location='cpu')
    model.load_state_dict(checkpoint['model_state_dict'])
    optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
    if scheduler and checkpoint.get('scheduler_state_dict'):
        scheduler.load_state_dict(checkpoint['scheduler_state_dict'])
    
    # Load norm_stats if they exist, otherwise return None
    norm_stats = checkpoint.get('norm_stats', None)
    if norm_stats is None:
        print("Warning: Normalization stats not found in checkpoint.")
        
    return checkpoint['epoch'], checkpoint['loss'], norm_stats

# ============================================================================ 
# 4. EVALUATION FUNCTIONS
# ============================================================================ 
def create_wall_mask(node_type):
    """Create mask to ignore wall nodes during loss calculation"""
    wall_class_index = 5  # Assuming walls are class 5
    node_class_indices = torch.argmax(node_type, dim=-1)
    mask = (node_class_indices != wall_class_index).float().unsqueeze(-1)
    return mask

def evaluate_rollout(model, trajectory_loader, device, norm_stats):
    """Run rollout evaluation on full trajectories"""
    model.eval()
    results = []
    
    print(f"Starting rollout evaluation on {len(trajectory_loader)} trajectories...")
    
    with torch.no_grad():
        for i, trajectory in enumerate(trajectory_loader):
            try:
                print(f"\nProcessing trajectory {i+1}/{len(trajectory_loader)}")
                
                # Since trajectory_loader has batch_size=1, we need to extract the single trajectory
                single_trajectory = {}
                for key, value in trajectory.items():
                    if key != 'meta_info':
                        # Remove the batch dimension
                        single_trajectory[key] = value.squeeze(0)
                    else:
                        # meta_info is special - it's a dict where each value is a list/tensor due to batching
                        # We need to extract the first element from each value in the meta_info dict
                        single_trajectory[key] = {}
                        for meta_key, meta_value in value.items():
                            if isinstance(meta_value, (list, tuple)):
                                single_trajectory[key][meta_key] = meta_value[0]
                            elif isinstance(meta_value, dict):
                                # Handle nested dictionaries (like node_type_counts)
                                single_trajectory[key][meta_key] = {}
                                for nested_key, nested_value in meta_value.items():
                                    if isinstance(nested_value, (list, tuple)):
                                        single_trajectory[key][meta_key][nested_key] = nested_value[0]
                                    elif torch.is_tensor(nested_value) and nested_value.numel() > 1:
                                        single_trajectory[key][meta_key][nested_key] = nested_value[0]
                                    else:
                                        single_trajectory[key][meta_key][nested_key] = nested_value
                            elif torch.is_tensor(meta_value) and meta_value.numel() > 1:
                                # For tensors with more than one element, take the first element
                                single_trajectory[key][meta_key] = meta_value[0]
                            else:
                                # For scalars or other types, keep as is
                                single_trajectory[key][meta_key] = meta_value
                
                # Pass the normalization statistics to the evaluation function
                _, traj_result = rollout_evaluate(model, single_trajectory, norm_stats)
                results.append(traj_result)
                print(f"Successfully processed trajectory {i+1}")
                
            except Exception as e:
                print(f"Error processing trajectory {i+1}: {str(e)}")
                print(f"Trajectory data shapes:")
                for key, value in trajectory.items():
                    if hasattr(value, 'shape'):
                        print(f"  {key}: {value.shape}")
                    else:
                        print(f"  {key}: {type(value)} - {value}")
                raise e
                
    print(f"Completed rollout evaluation on {len(results)} trajectories")
    return results
# ============================================================================ 
# 5. MAIN TRAINING SCRIPT
# ============================================================================ 
def main():
    script_start_time = time.time()
    # --- CONFIGURATION ---
    preprocessed_dir = r"/home/gd_user1/AnK/project_PINN/cleanroom/rawdataset"
    base_filename = "final_data_timestep_data"
    output_dir = r"/home/gd_user1/AnK/project_PINN/cleanroom/second_output/output_2"

    train_pt_path = os.path.join(preprocessed_dir, f"{base_filename}_train.pt")
    val_pt_path = os.path.join(preprocessed_dir, f"{base_filename}_test.pt")

    os.makedirs(output_dir, exist_ok=True)

    hparams = {
        'lr': 0.0005, 'batch_size': 1, 'nb_epochs': 400,
        'in_dim': 13,  # coordinates(3) + node_type(6) + current_vel(3) + inlet_vel(1)
        'out_dim': 3, 'n_hidden': 256, 'n_layers': 6, 'n_head': 8, 'slice_num': 32,
        'checkpoint_freq': 10, 'eval_freq': 10
    }

    # --- SETUP ---
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    print(f"Using device: {device}")
    if torch.cuda.is_available():
        print(f"GPU: {torch.cuda.get_device_name(0)}")
        print(f"CUDA version: {torch.version.cuda}")

    # Set random seeds for reproducibility
    torch.manual_seed(42)
    random.seed(42)
    np.random.seed(42)

    # --- DATALOADERS ---
    print("Loading datasets...")
    train_dataset = TimeStepDataset(train_pt_path)
    val_timestep_dataset = TimeStepDataset(val_pt_path)  # For single-step validation
    test_trajectory_dataset = TrajectoryDataset(val_pt_path)  # For rollout evaluation

    train_loader = DataLoader(train_dataset, batch_size=hparams['batch_size'], shuffle=True)
    val_timestep_loader = DataLoader(val_timestep_dataset, batch_size=hparams['batch_size'], shuffle=False)
    test_trajectory_loader = DataLoader(test_trajectory_dataset, batch_size=1, shuffle=False)

    # --- COMPUTE NORMALIZATION STATISTICS FROM TRAINING DATA ---
    def compute_normalization_stats(train_dataset):
        """Compute normalization statistics from training dataset"""
        coords_list = []
        vel_list = []
        inlet_vel_list = []

        print("Computing normalization statistics from training data...")

        for sample in train_dataset:
            coords_list.append(sample['coordinates'])
            vel_list.append(sample['current_velocities'])
            # Handle inlet velocity (it's in meta_info and may be tensor or scalar)
            inlet_vel = sample['meta_info']['velocity']
            if torch.is_tensor(inlet_vel):
                inlet_vel_list.append(inlet_vel.item())
            else:
                inlet_vel_list.append(float(inlet_vel))

        # Stack and compute statistics
        coords_all = torch.stack(coords_list)  # [num_samples, num_nodes, 3]
        vel_all = torch.stack(vel_list)        # [num_samples, num_nodes, 3]
        inlet_vel_all = torch.tensor(inlet_vel_list)  # [num_samples]

        stats = {
            'coords_mean': coords_all.mean(dim=[0, 1]),  # Mean across samples and nodes
            'coords_std': coords_all.std(dim=[0, 1]),
            'vel_mean': vel_all.mean(dim=[0, 1]),
            'vel_std': vel_all.std(dim=[0, 1]),
            'inlet_vel_mean': inlet_vel_all.mean(),
            'inlet_vel_std': inlet_vel_all.std()
        }

        print(f"Computed stats - Coords mean: {stats['coords_mean']}, std: {stats['coords_std']}")
        print(f"Velocities mean: {stats['vel_mean']}, std: {stats['vel_std']}")
        print(f"Inlet vel mean: {stats['inlet_vel_mean']:.6f}, std: {stats['inlet_vel_std']:.6f}")

        return stats

    # Compute normalization statistics
    norm_stats = compute_normalization_stats(train_dataset)
    coords_mean = norm_stats['coords_mean'].to(device)
    coords_std = norm_stats['coords_std'].to(device)
    vel_mean = norm_stats['vel_mean'].to(device)
    vel_std = norm_stats['vel_std'].to(device)
    inlet_vel_mean = norm_stats['inlet_vel_mean'].to(device)
    inlet_vel_std = norm_stats['inlet_vel_std'].to(device)
    epsilon = 1e-8  # Small constant to prevent division by zero

    # --- MODEL, OPTIMIZER, SCHEDULER SETUP ---
    model = Model(in_dim=hparams['in_dim'], out_dim=hparams['out_dim'], 
                  n_hidden=hparams['n_hidden'], n_layers=hparams['n_layers'],
                  n_head=hparams['n_head'], slice_num=hparams['slice_num']).to(device)
    
    optimizer = torch.optim.Adam(model.parameters(), lr=hparams['lr'])
    scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=50, gamma=0.9)
    criterion = nn.MSELoss()

    # Initialize training variables
    start_epoch = 0
    best_val_loss = float('inf')

    # Check for existing checkpoint to resume training
    latest_checkpoint_path = os.path.join(output_dir, 'checkpoint_latest.pth')
    if os.path.exists(latest_checkpoint_path):
        print(f"Found existing checkpoint: {latest_checkpoint_path}")
        try:
            start_epoch, last_loss, loaded_norm_stats = load_checkpoint(
                model, optimizer, scheduler, latest_checkpoint_path
            )
            if loaded_norm_stats is not None:
                norm_stats = loaded_norm_stats
                # Update the normalization tensors
                coords_mean = norm_stats['coords_mean'].to(device)
                coords_std = norm_stats['coords_std'].to(device)
                vel_mean = norm_stats['vel_mean'].to(device)
                vel_std = norm_stats['vel_std'].to(device)
                inlet_vel_mean = norm_stats['inlet_vel_mean'].to(device)
                inlet_vel_std = norm_stats['inlet_vel_std'].to(device)
                print("Loaded normalization statistics from checkpoint.")
            print(f"Resuming training from epoch {start_epoch}")
            best_val_loss = last_loss
        except Exception as e:
            print(f"Error loading checkpoint: {e}")
            print("Starting fresh training...")
            start_epoch = 0
            best_val_loss = float('inf')

    print(f"Starting training from epoch {start_epoch} to {hparams['nb_epochs']}")
    print("="*60)

    train_loss_history = []
    val_loss_history = []
    lr_history = []
    val_epochs = []

    # --- TRAINING LOOP ---
    for epoch in range(start_epoch, hparams['nb_epochs']):
        epoch_start_time = time.time()
        model.train()
        total_train_loss = 0.0

        for batch_idx, batch in enumerate(train_loader):
            coordinates = batch['coordinates'].to(device)
            node_type = batch['node_type'].to(device)
            current_velocities = batch['current_velocities'].to(device)
            target_velocities = batch['target_velocities'].to(device)

            inlet_velocities = batch['meta_info']['velocity']
            if torch.is_tensor(inlet_velocities):
                inlet_vel_tensor = inlet_velocities.clone().detach().float().to(device)
            else:
                inlet_vel_tensor = torch.tensor(inlet_velocities, dtype=torch.float32).to(device)
            
            # --- NORMALIZE FEATURES ---
            norm_coords = (coordinates - coords_mean) / (coords_std + epsilon)
            norm_current_vel = (current_velocities - vel_mean) / (vel_std + epsilon)
            norm_target_vel = (target_velocities - vel_mean) / (vel_std + epsilon)
            norm_inlet_vel = (inlet_vel_tensor - inlet_vel_mean) / (inlet_vel_std + epsilon)

            batch_size, num_nodes, _ = coordinates.shape
            inlet_vel_feature = norm_inlet_vel.view(batch_size, 1, 1).expand(batch_size, num_nodes, 1)

            # Input: [normalized coordinates, node_type, normalized velocities, normalized inlet_velocity]
            input_features = torch.cat([norm_coords, node_type, norm_current_vel, inlet_vel_feature], dim=-1)

            optimizer.zero_grad()
            predicted_normalized_velocities = model(input_features)

            # Apply wall masking
            mask = create_wall_mask(node_type)
            loss = criterion(predicted_normalized_velocities * mask, norm_target_vel * mask)
            loss.backward()
            optimizer.step()

            total_train_loss += loss.item()

            # Progress update every 50 batches
            if batch_idx % 50 == 0:
                print(f"Epoch {epoch+1}/{hparams['nb_epochs']} | Batch {batch_idx+1}/{len(train_loader)} | Loss: {loss.item():.6f}")

        scheduler.step()
        lr_history.append(optimizer.param_groups[0]['lr'])
        epoch_time = time.time() - epoch_start_time
        avg_train_loss = total_train_loss / len(train_loader)
        train_loss_history.append(avg_train_loss)

        print(f"Epoch {epoch+1}/{hparams['nb_epochs']} completed | Avg Train Loss: {avg_train_loss:.6f} | Time: {epoch_time:.2f}s")

        # --- PERIODIC EVALUATION ---
        if (epoch + 1) % hparams['eval_freq'] == 0 or epoch == hparams['nb_epochs'] - 1:
            print(f"Epoch {epoch+1}/{hparams['nb_epochs']} | Train Loss: {avg_train_loss:.6f}")

            # Rollout evaluation
            print("  Running rollout evaluation...")
            rollout_results = evaluate_rollout(model, test_trajectory_loader, device, norm_stats)

            # Calculate loss from rollout
            total_rollout_mse = 0.0
            for result in rollout_results:
                # Move tensors to the correct device
                pred_traj = result['predicted_trajectory'].to(device)
                gt_traj = result['ground_truth_trajectory'].to(device)
                node_type = result['node_type'].to(device)

                # Create a mask to ignore wall nodes
                mask = create_wall_mask(node_type).unsqueeze(0)  # Add time dim for broadcasting

                # Calculate masked MSE
                loss = criterion(pred_traj * mask, gt_traj * mask)
                total_rollout_mse += loss.item()
            
            avg_rollout_mse = total_rollout_mse / len(rollout_results)
            
            val_loss = avg_rollout_mse
            val_loss_history.append(val_loss)
            val_epochs.append(epoch + 1)
            print(f"  Validation Rollout MSE: {val_loss:.6f}")

            # Save rollout results
            rollout_path = os.path.join(output_dir, f"rollout_results_epoch_{epoch+1}.npy")
            np.save(rollout_path, rollout_results, allow_pickle=True) # allow_pickle is good practice for np.save with dicts
            print(f"  -> Saved rollout results to {rollout_path}")

            # Save best model based on rollout loss
            if val_loss < best_val_loss:
                best_val_loss = val_loss
                best_model_path = os.path.join(output_dir, 'best_model.pth')
                torch.save(model.state_dict(), best_model_path)
                print(f"  -> New best model saved with validation loss: {best_val_loss:.6f}")

        # --- PERIODIC CHECKPOINTING ---
        if (epoch + 1) % hparams['checkpoint_freq'] == 0:
            # Use validation loss if available, otherwise use training loss
            checkpoint_loss = val_loss if 'val_loss' in locals() else avg_train_loss
            checkpoint_path = os.path.join(output_dir, f'checkpoint_epoch_{epoch+1}.pth')
            save_checkpoint(model, optimizer, scheduler, epoch + 1, checkpoint_loss, checkpoint_path, norm_stats)

    # --- SAVE LATEST CHECKPOINT ---
    save_checkpoint(model, optimizer, scheduler, hparams['nb_epochs'], best_val_loss,
                   os.path.join(output_dir, 'checkpoint_latest.pth'), norm_stats)

    print("="*60)
    print("Training complete.")
    print(f"Best validation loss: {best_val_loss:.6f}")

    # --- PLOTTING AND SAVING LOSS HISTORY ---
    plt.figure(figsize=(10, 5))
    plt.plot(train_loss_history, label='Training Loss')
    plt.plot(val_epochs, val_loss_history, 'o-', label='Validation Loss')
    plt.title('Training and Validation Loss Over Epochs')
    plt.xlabel('Epoch')
    plt.ylabel('Loss (MSE)')
    plt.legend()
    plt.grid(True)
    plt.savefig(os.path.join(output_dir, 'training_loss_plot.png'))
    print(f"Loss plot saved to {os.path.join(output_dir, 'training_loss_plot.png')}")

    loss_data = {
        'train_loss_history': train_loss_history,
        'val_loss_history': val_loss_history,
        'val_epochs': val_epochs,
        'lr_history': lr_history,
        'best_val_loss': best_val_loss
    }
    with open(os.path.join(output_dir, 'loss_history.json'), 'w') as f:
        json.dump(loss_data, f, indent=4)
    print(f"Loss history saved to {os.path.join(output_dir, 'loss_history.json')}")
    
    script_end_time = time.time()
    elapsed_time_seconds = script_end_time - script_start_time
    print("="*60)
    print(f"Total script execution time: {elapsed_time_seconds / 60:.2f} minutes ({elapsed_time_seconds:.2f} seconds)")
if __name__ == '__main__':
    main()