-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfinal_swinunet_pipeline.py
More file actions
2363 lines (1943 loc) · 92.5 KB
/
final_swinunet_pipeline.py
File metadata and controls
2363 lines (1943 loc) · 92.5 KB
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Standard library imports
import os
import re
import random
import math
import time
import warnings
import sys
import copy
import logging
import datetime
import contextlib
import subprocess
from collections import defaultdict
from pathlib import Path
from typing import List, Dict, Tuple, Optional, Any
# Numerical and scientific computing
import numpy as np
import psutil
from scipy.ndimage import map_coordinates
# Visualization
import matplotlib.pyplot as plt
# Deep learning frameworks
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader, Subset
from torch.optim.lr_scheduler import (
CosineAnnealingLR,
CosineAnnealingWarmRestarts,
LinearLR,
SequentialLR
)
from torch.utils.tensorboard import SummaryWriter
import torch.profiler
from torchvision.transforms import functional as TF
# DDP and metrics
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data.distributed import DistributedSampler
from torchmetrics import MeanAbsoluteError, StructuralSimilarityIndexMeasure
# Third-party libraries
import timm # For Swin Transformer models
from torchinfo import summary # For model summary
from tqdm.auto import tqdm # Progress bars
# Warning suppressions
def suppress_all_warnings():
"""Suppress all common deep learning framework warnings"""
# Python warnings
warnings.filterwarnings('ignore')
warnings.filterwarnings('ignore', category=UserWarning)
warnings.filterwarnings('ignore', category=FutureWarning)
warnings.filterwarnings('ignore', category=DeprecationWarning)
# PyTorch optimizations
try:
import torch
torch.backends.cudnn.benchmark = True
except ImportError:
pass
# Apply comprehensive warning suppression
suppress_all_warnings()
# Configurations
class Config:
"""
Central configuration class for all model and training parameters.
Provides default values and validation for the experiment setup.
"""
# --- Paths, Logging & Resuming ---
TRAIN_PATH = Path("/tmp/gkhanal-runtime-dir/data/train/openfwi_72x72")
OUTPUT_DIR = Path("/home/gkhanal/fwi_project/fwi_test/swinv2/results/july25")
EXPERIMENT_NAME = "SwinV2_FWI_Combined_Loss_LRWarmRestart"
RESUME_CHECKPOINT = None # Path to checkpoint file to resume training
# --- Experiment Controls ---
RUN_PROFILER = False # Enable PyTorch profiler
EXPORT_ONNX = True # Export final model to ONNX format
USE_LOSS_WEIGHTING = True # Whether to use class-weighted loss
# --- Model & Architecture ---
MODEL_NAME = 'swinv2_tiny_window8_256.ms_in1k' # Timm model name
PRETRAINED = True # Use pretrained weights
OUTPUT_CHANNELS = 1 # Output velocity channels
NUM_SOURCES = 5 # Number of seismic sources
DECODER_CHANNELS = [512, 256, 128] # Enhanced decoder channel sizes
DECODER_DROPOUT = 0.2 # Dropout rate in decoder
USE_ENHANCED_DECODER = True # Use enhanced decoder with learned upsampling
# Model dimensions
INPUT_HEIGHT = 72 # Input seismic data height
INPUT_WIDTH = 72 # Input seismic data width
OUTPUT_HEIGHT = 70 # Output velocity model height
OUTPUT_WIDTH = 70 # Output velocity model width
BACKBONE_INPUT_SIZE = 256 # Interpolation size for backbone
STEM_CHANNELS = 32 # Initial stem convolution channels
RGB_CHANNELS = 3 # RGB channels for backbone input
GROUPNORM_GROUPS = 8 # GroupNorm groups
SCSE_REDUCTION = 16 # Default reduction factor in SCSE block
# --- Loss function weights ---
HUBER_LOSS_WEIGHT = 0.4 # Weight for Huber loss
GRAD_LOSS_WEIGHT = 0.55 # Weight for gradient loss
TV_LOSS_WEIGHT = 0.05 # Weight for total variation loss
# --- Training ---
DEVICE = "cuda" # Default device
USE_AMP = True # Automatic Mixed Precision
NUM_EPOCHS = 50 # Total training epochs
BATCH_SIZE = 256 # Batch size per GPU
ACCUMULATION_STEPS = 1 # Gradient accumulation steps
WEIGHT_DECAY = 1e-4 # Weight decay
GRAD_CLIP_NORM = 1.0 # Gradient clipping norm
# --- Learning Rate Scheduler
LEARNING_RATE = 1.5e-4 # Initial learning rate (increased for stronger restarts)
LR_MIN = 1e-6 # Minimum learning rate
WARMUP_EPOCHS = 5 # Warmup epochs
WARMUP_LR_START_FACTOR = 0.01 # Starting factor for warmup learning rate
# --- Warm Restarts Configuration
USE_WARM_RESTARTS = True # Use CosineAnnealingWarmRestarts instead of CosineAnnealingLR
T_0 = 8 # Initial restart period (shorter for more exploration)
T_MULT = 2 # Factor to increase T_i after each restart (more gradual)
ETA_MIN_RESTART = 5e-7 # Minimum learning rate for restarts (lower for deeper exploration)
LR_RESTART_DETECTION_THRESHOLD = 2.0 # Threshold for detecting learning rate restarts
LR_RESTART_SECONDARY_THRESHOLD = 1.5 # Secondary threshold for restart detection
LR_RESTART_MIN_INCREASE_RATIO = 10.0 # Minimum increase ratio from bottom for restart detection
# --- Validation, Checkpointing & EMA ---
VALIDATION_SPLIT = 0.20 # Validation set fraction
PATIENCE = 5 # Early stopping patience
CHECKPOINT_EVERY = 5 # Save checkpoint every N epochs
EMA_DECAY = 0.99 # EMA decay rate
# --- Data ---
RANDOM_SEED = 42 # Random seed for reproducibility
VELOCITY_MIN = 1500.0 # Minimum velocity value (m/s)
VELOCITY_MAX = 4500.0 # Maximum velocity value (m/s)
MAX_RETRIES = 3 # Max retries in dataset loading
MIN_STD_CLAMP = 1e-6 # Minimum std clamp value for normalization
# --- Training Constants ---
DDP_TIMEOUT_SECONDS = 60 # DDP timeout seconds
VALIDATION_BATCH_MULTIPLIER = 2 # Batch size multiplier for validation
ELASTIC_ALPHA_RANGE = (30, 50) # Alpha range for elastic deformation
ELASTIC_SIGMA_RANGE = (4, 6) # Sigma range for elastic deformation
ONNX_OPSET_VERSION = 13 # ONNX opset version
# --- Torch Compile ---
USE_TORCH_COMPILE = False # Enable torch.compile for model optimization
COMPILE_MODE = "default" # Compile mode: "default", "reduce-overhead", "max-autotune"
# --- Dataloader ---
NUM_WORKERS = 48 # DataLoader workers
PIN_MEMORY = True # Pin memory for faster transfer
PERSISTENT_WORKERS = True # Maintain workers between epochs
PREFETCH_FACTOR = 8 # Prefetch batches
MEMORY_WORKERS_RATIO = 2 # GB of memory per worker for optimal worker calculation
# Augmentation configuration classes
class AugmentationToggles:
"""Toggle switches for different augmentation types"""
AMP_JITTER = False # Amplitude jitter
RECEIVER_DROP = False # Random receiver dropout
GAUSSIAN_NOISE = True # Add Gaussian noise
VELOCITY_AUG = True # Velocity scaling
VELOCITY_SMOOTH = False # Velocity smoothing
FAULT_SIMULATION = False # Fault simulation
ELASTIC_DEFORM = False # Elastic deformation
class AugmentationParams:
"""Parameters for data augmentations"""
# Noise parameters
NOISE_STD = 0.02 # Std of Gaussian noise
RECEIVER_DROP_PROB = 0.3 # Probability of receiver drop
MAX_RECEIVER_DROPS = 5 # Maximum receivers to drop
# Amplitude jitter
AMP_JITTER_PROB = 0.2 # Probability of amplitude jitter
AMP_JITTER_SCALE = 0.1 # Scale of amplitude variation
# Fault simulation
FAULT_NOISE_PROB = 0.2 # Probability of fault noise
FAULT_NOISE_STRENGTH = 0.1 # Strength of fault displacement
# Velocity augmentations
VEL_AUG_PROB = 0.2 # Probability of velocity scaling
VEL_AUG_SCALE = 0.1 # Scale of velocity variation
VEL_SMOOTH_PROB = 0.2 # Probability of smoothing
# Elastic deformation
ELASTIC_DEFORM_PROB = 0.3 # Probability of elastic deformation
GAUSSIAN_BLUR_KERNEL_MULTIPLIER = 6 # Multiplier for gaussian blur kernel size (6 * sigma + 1)
def validate(self) -> None:
"""Validate configuration parameters"""
if not self.TRAIN_PATH.exists():
raise FileNotFoundError(f"Train path not found: {self.TRAIN_PATH}")
if self.ACCUMULATION_STEPS > 0 and self.BATCH_SIZE % self.ACCUMULATION_STEPS != 0:
raise ValueError(f"BATCH_SIZE ({self.BATCH_SIZE}) must be divisible by ACCUMULATION_STEPS ({self.ACCUMULATION_STEPS}) for proper gradient accumulation.")
if self.NUM_WORKERS < 0:
raise ValueError(f"NUM_WORKERS must be non-negative, got {self.NUM_WORKERS}")
if self.BATCH_SIZE <= 0:
raise ValueError(f"BATCH_SIZE must be positive, got {self.BATCH_SIZE}")
if self.NUM_EPOCHS <= 0:
raise ValueError(f"NUM_EPOCHS must be positive, got {self.NUM_EPOCHS}")
# Initialize configuration
cfg = Config()
augs = cfg.AugmentationToggles()
aug_params = cfg.AugmentationParams()
# Distributed Data Parallel (DDP) Manager)
class DDPManager:
"""
Handles distributed training setup and cleanup.
Automatically falls back to single-GPU mode if DDP initialization fails.
"""
def __init__(self) -> None:
"""Initialize DDP environment if available"""
self.is_ddp = 'WORLD_SIZE' in os.environ and torch.cuda.is_available()
if self.is_ddp:
try:
# Initialize distributed process group
dist.init_process_group(
backend="nccl",
timeout=datetime.timedelta(seconds=cfg.DDP_TIMEOUT_SECONDS)
)
self.rank = dist.get_rank()
self.world_size = dist.get_world_size()
device_id = self.rank % torch.cuda.device_count()
self.device = torch.device(f'cuda:{device_id}')
torch.cuda.set_device(device_id)
except Exception as e:
logging.error(f"DDP initialization failed: {e}. Falling back to single-GPU.")
self.is_ddp = False
self._setup_single_gpu()
else:
self._setup_single_gpu()
def _setup_single_gpu(self) -> None:
"""Setup for single-GPU training"""
self.rank = 0
self.world_size = 1
self.device = torch.device(cfg.DEVICE if torch.cuda.is_available() else "cpu")
def cleanup(self) -> None:
"""Cleanup distributed process group if initialized"""
if self.is_ddp and dist.is_initialized():
dist.destroy_process_group()
def is_main_process(self) -> bool:
"""Check if current process is the main process"""
return self.rank == 0
# Setup Utilities
def set_seed(seed_value: int = cfg.RANDOM_SEED, rank: int = 0) -> None:
"""
Set random seeds for reproducibility.
Args:
seed_value: Base seed value
rank: Process rank to ensure different seeds across processes
"""
seed = seed_value + rank
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.benchmark = True
def seed_worker(worker_id: int) -> None:
"""Seed numpy and random for DataLoader workers"""
worker_seed = torch.initial_seed() % 2**32
np.random.seed(worker_seed)
random.seed(worker_seed)
def setup_logging(log_file: str = 'training.log') -> None:
"""Configure logging to file and console"""
log_format = logging.Formatter("%(asctime)s [%(levelname)s] - %(message)s")
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# Remove existing handlers
for handler in logger.handlers[:]:
logger.removeHandler(handler)
# File handler
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(log_format)
logger.addHandler(file_handler)
# Console handler
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(log_format)
logger.addHandler(console_handler)
def safe_barrier(ddp_manager: DDPManager, timeout_seconds: int = cfg.DDP_TIMEOUT_SECONDS) -> None:
"""
A DDP barrier with timeout to prevent hangs.
Args:
ddp_manager: DDPManager instance
timeout_seconds: Maximum time to wait for barrier
"""
if ddp_manager.is_ddp:
try:
dist.barrier(device_ids=[ddp_manager.rank])
except RuntimeError as e:
logging.error(f"DDP barrier timed out after {timeout_seconds}s: {e}")
raise
def validate_ddp_setup(ddp_manager: DDPManager) -> None:
"""Validate DDP communication between processes"""
if not ddp_manager.is_ddp:
return
try:
# Test communication with all_reduce
tensor = torch.tensor([ddp_manager.rank], device=ddp_manager.device, dtype=torch.float)
dist.all_reduce(tensor, op=dist.ReduceOp.SUM)
expected = float(sum(range(ddp_manager.world_size)))
assert tensor.item() == expected, f"DDP validation failed: got {tensor.item()}, expected {expected}"
if ddp_manager.is_main_process():
logging.info("DDP communication validated successfully.")
except Exception as e:
logging.error(f"DDP validation failed: {e}", exc_info=True)
raise
def validate_scheduler_config(train_loader: DataLoader) -> None:
"""Validate warm restart scheduler configuration"""
if not cfg.USE_WARM_RESTARTS:
return
steps_per_epoch = len(train_loader) // cfg.ACCUMULATION_STEPS
warmup_steps = cfg.WARMUP_EPOCHS * steps_per_epoch
total_steps = cfg.NUM_EPOCHS * steps_per_epoch
remaining_steps = total_steps - warmup_steps
t_0_steps = cfg.T_0 * steps_per_epoch
# Calculate expected restart schedule
restart_steps = []
current_period = t_0_steps
current_step = warmup_steps + current_period
while current_step < total_steps:
restart_steps.append(current_step)
current_period = int(current_period * cfg.T_MULT)
current_step += current_period
logging.info(f"Warm restart schedule validation:")
logging.info(f" - Total training steps: {total_steps}")
logging.info(f" - Warmup steps: {warmup_steps}")
logging.info(f" - Steps per epoch: {steps_per_epoch}")
logging.info(f" - Initial restart period: {t_0_steps} steps ({cfg.T_0} epochs)")
logging.info(f" - Expected restarts at steps: {restart_steps}")
logging.info(f" - Total expected restarts: {len(restart_steps)}")
if len(restart_steps) == 0:
logging.warning("No restarts will occur with current configuration!")
elif len(restart_steps) < 2:
logging.warning("Only 1 restart scheduled. Consider smaller T_0 for more exploration.")
def validate_model_outputs(model: nn.Module, sample_input: torch.Tensor, device: torch.device) -> None:
"""Validate model produces expected outputs without NaNs"""
logging.info("Performing model output validation...")
try:
with torch.no_grad():
output = model(sample_input.to(device))
assert output.shape[-2:] == (cfg.OUTPUT_HEIGHT, cfg.OUTPUT_WIDTH), f"Expected output shape ending in ({cfg.OUTPUT_HEIGHT},{cfg.OUTPUT_WIDTH}), got {output.shape[-2:]}"
assert not torch.isnan(output).any(), "Model produced NaN outputs on sample input"
assert torch.isfinite(output).all(), "Model produced non-finite values (inf) on sample input"
logging.info("Model output validation passed.")
except Exception as e:
logging.error(f"Model output validation FAILED: {e}", exc_info=True)
raise
class AdaptiveAugmentation:
"""
Dynamically adjusts augmentation strength based on validation performance.
Attributes:
strength: Current augmentation strength multiplier
decay_rate: Rate at which strength decays
patience: Number of validation checks without improvement before decay
counter: Current patience counter
best_loss: Best validation loss observed
"""
def __init__(self, initial_strength: float = 1.0, decay_rate: float = 0.98, patience: int = 2) -> None:
self.strength = initial_strength
self.decay_rate = decay_rate
self.patience = patience
self.counter = 0
self.best_loss = float('inf')
def update(self, validation_loss: float) -> None:
"""Update augmentation strength based on validation loss"""
if validation_loss < self.best_loss:
self.best_loss = validation_loss
self.counter = 0
else:
self.counter += 1
if self.counter >= self.patience:
old_strength = self.strength
self.strength *= self.decay_rate
logging.info(f"Augmentation strength decayed from {old_strength:.3f} to {self.strength:.3f}")
self.counter = 0
class WarmRestartMonitor:
"""Monitor and log warm restarts for CosineAnnealingWarmRestarts"""
def __init__(self):
self.last_lr = None
self.restart_count = 0
self.step_count = 0
self.warmup_complete = False
self.min_lr_seen = float('inf')
def check_restart(self, current_lr: float) -> bool:
"""Check if a restart occurred based on learning rate increase"""
restart_detected = False
# Skip restart detection during warmup
if not self.warmup_complete:
if self.last_lr is not None and current_lr < self.last_lr:
self.warmup_complete = True
logging.info(f"Warmup completed at step {self.step_count}, starting restart monitoring")
if self.warmup_complete and self.last_lr is not None:
# Track minimum LR to detect restarts more reliably
self.min_lr_seen = min(self.min_lr_seen, self.last_lr)
# Detect restart: significant LR increase from recent minimum
lr_increase_ratio = current_lr / self.last_lr
min_increase_from_bottom = current_lr / self.min_lr_seen
if (lr_increase_ratio > cfg.LR_RESTART_DETECTION_THRESHOLD or # Primary threshold for restart detection
(lr_increase_ratio > cfg.LR_RESTART_SECONDARY_THRESHOLD and min_increase_from_bottom > cfg.LR_RESTART_MIN_INCREASE_RATIO)): # Secondary threshold + far from minimum
self.restart_count += 1
logging.info(f"🔄 Warm restart #{self.restart_count} detected at step {self.step_count} "
f"(LR: {self.last_lr:.2e} → {current_lr:.2e}, ratio: {lr_increase_ratio:.1f}x)")
self.min_lr_seen = float('inf') # Reset minimum tracking
restart_detected = True
self.last_lr = current_lr
self.step_count += 1
return restart_detected
# Data and Preprocessing
def scan_files(root_dir: Path) -> List[Dict[str, Any]]:
"""Scan directory for input/target file pairs and group them by type"""
file_pairs = []
for item in sorted(root_dir.iterdir()):
if not item.is_dir():
continue
name = item.name
group = "Unknown"
if "Vel" in name:
group = "Vel"
elif "Style" in name:
group = "Style"
elif "Fault" in name:
group = "Fault"
# Match data/model pairs
for data_file in sorted(item.glob("data*.npy")):
match = re.search(r"data(\d+)\.npy", data_file.name)
if match:
idx = match.group(1)
model_file = item / f"model{idx}.npy"
if model_file.exists():
file_pairs.append({"input": data_file, "target": model_file, "group": group})
# Match seis/vel pairs
for seis_file in sorted(item.glob("seis*.npy")):
vel_file = item / seis_file.name.replace("seis", "vel", 1)
if vel_file.exists():
file_pairs.append({"input": seis_file, "target": vel_file, "group": group})
return file_pairs
def create_stratified_split(file_pairs: List[Dict[str, Any]], val_frac: float) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
"""Create stratified train/validation split maintaining group proportions"""
groups = defaultdict(list)
for pair in file_pairs:
groups[pair["group"]].append(pair)
train_files, val_files = [], []
for group, items in groups.items():
random.shuffle(items)
n_val = max(1, int(len(items) * val_frac))
val_files.extend(items[:n_val])
train_files.extend(items[n_val:])
random.shuffle(train_files)
random.shuffle(val_files)
return train_files, val_files
def calculate_class_weights(train_pairs: List[Dict[str, Any]], ddp_manager: DDPManager) -> Optional[Dict[str, float]]:
"""Calculate class weights for loss balancing"""
if not cfg.USE_LOSS_WEIGHTING:
return None
logging.info("Calculating class weights for loss balancing...")
group_counts = defaultdict(int)
total_samples = 0
for pair in train_pairs:
group_counts[pair['group']] += 1
total_samples += 1
if total_samples == 0:
return None
num_classes = len(group_counts)
weights = {}
# Inverse frequency weighting
for group, count in group_counts.items():
weights[group] = total_samples / (num_classes * count)
# Normalize weights
max_weight = max(weights.values())
for group in weights:
weights[group] /= max_weight
if ddp_manager.is_main_process():
logging.info(f"Calculated loss weights: {weights}")
return weights
def log_dataset_info(train_pairs: List[Dict[str, Any]], val_pairs: List[Dict[str, Any]]) -> None:
"""Log detailed information about dataset splits"""
logging.info("--- Dataset Analysis ---")
def analyze_split(name: str, pairs: List[Dict]) -> None:
if not pairs:
logging.info(f"{name} set is empty.")
return
group_counts = defaultdict(int)
total_samples = 0
for pair in tqdm(pairs, desc=f"Scanning {name} files", leave=False):
try:
with open(pair['input'], 'rb') as f:
version = np.lib.format.read_magic(f)
shape, _, _ = np.lib.format._read_array_header(f, version)
num_samples_in_file = shape[0]
group = pair['group']
group_counts[group] += num_samples_in_file
total_samples += num_samples_in_file
except Exception as e:
logging.warning(f"Could not read shape for {pair['input']}: {e}")
logging.info(f"Split: {name} | Total Samples: {total_samples}")
for group, count in sorted(group_counts.items()):
logging.info(f" - Group: {group:<6} | Samples: {count}")
analyze_split("Training", train_pairs)
analyze_split("Validation", val_pairs)
logging.info("------------------------")
class FWIDataset(Dataset):
"""Dataset for loading FWI training samples"""
def __init__(self, metadata: List[Dict[str, Any]], device: torch.device) -> None:
"""
Args:
metadata: List of dicts containing input/target file paths
device: Target device for data loading
"""
self.metadata_files = metadata
self.device = device
self.flat_index = []
# Build flat index mapping (file_idx, sample_idx)
for file_idx, pair in enumerate(self.metadata_files):
try:
num_samples = np.load(pair["input"], mmap_mode='r').shape[0]
self.flat_index.extend([(file_idx, sample_idx) for sample_idx in range(num_samples)])
except Exception as e:
logging.error(f"Failed to process file {pair['input']}: {e}")
def __len__(self) -> int:
return len(self.flat_index)
def __getitem__(self, idx: int) -> Tuple[torch.Tensor, torch.Tensor, str]:
"""Load and preprocess a single sample with retry mechanism"""
max_retries = cfg.MAX_RETRIES
for attempt in range(max_retries):
try:
file_idx, sample_idx = self.flat_index[idx]
sample_info = self.metadata_files[file_idx]
# Load input and target data
input_data = np.load(sample_info['input'], mmap_mode='r')[sample_idx].copy()
target_data = np.load(sample_info['target'], mmap_mode='r')[sample_idx].copy()
group = sample_info['group']
# Validate data integrity
if np.isnan(input_data).any() or np.isnan(target_data).any():
raise ValueError(f"NaN values detected in data for sample {idx}")
if input_data.size == 0 or target_data.size == 0:
raise ValueError(f"Empty data arrays for sample {idx}")
# Convert to tensors
seismic = torch.from_numpy(input_data).float()
velocity = torch.from_numpy(target_data).float()
# Handle different input formats
if group == 'Fault' and seismic.ndim == 2:
seismic = seismic.unsqueeze(0).repeat(cfg.NUM_SOURCES, 1, 1)
if velocity.ndim == 2:
velocity = velocity.unsqueeze(0)
return seismic, velocity, group
except Exception as e:
if attempt < max_retries - 1:
logging.warning(f"Attempt {attempt + 1} failed for sample {idx}: {e}. Retrying...")
# Try a different sample on retry to avoid persistent corruption
idx = (idx + 1) % len(self.flat_index)
continue
else:
# All retries exhausted - raise error to fail fast
logging.error(f"Failed to load sample {idx} after {max_retries} attempts: {e}")
raise RuntimeError(f"Failed to load sample {idx} after {max_retries} attempts") from e
class GPUBatchProcessor:
"""Handles batch processing and augmentations on GPU"""
def __init__(self, device: torch.device, aug_scheduler: AdaptiveAugmentation) -> None:
"""
Args:
device: Target device for processing
aug_scheduler: Adaptive augmentation controller
"""
self.device = device
self.aug_scheduler = aug_scheduler
self.velocity_min = torch.tensor(cfg.VELOCITY_MIN, device=device)
self.velocity_range = torch.tensor(cfg.VELOCITY_MAX - cfg.VELOCITY_MIN, device=device)
def _elastic_deform(self, image: torch.Tensor, alpha: float, sigma: float) -> torch.Tensor:
"""Apply elastic deformation to input images"""
B, _, H, W = image.shape
coords_y, coords_x = torch.meshgrid(
torch.arange(H, device=self.device),
torch.arange(W, device=self.device),
indexing='ij'
)
coords = torch.stack([coords_y, coords_x], dim=0).float()
# Generate random displacement fields
dx = torch.randn(B, H, W, device=self.device) * sigma
dy = torch.randn(B, H, W, device=self.device) * sigma
# Smooth displacement fields
kernel_size = int(aug_params.GAUSSIAN_BLUR_KERNEL_MULTIPLIER * sigma + 1)
if kernel_size % 2 == 0:
kernel_size += 1
dx = TF.gaussian_blur(dx.unsqueeze(1), kernel_size=(kernel_size, kernel_size)).squeeze(1)
dy = TF.gaussian_blur(dy.unsqueeze(1), kernel_size=(kernel_size, kernel_size)).squeeze(1)
# Apply displacement
displaced_coords = coords + alpha * torch.stack([dy, dx], dim=1)
displaced_coords = displaced_coords.permute(0, 2, 3, 1)
norm_coords = 2 * (displaced_coords / torch.tensor([W-1, H-1], device=self.device) - 0.5)
return F.grid_sample(
image, norm_coords,
mode='bilinear',
padding_mode='reflection',
align_corners=False
)
def _augment_velocity(self, velocity: torch.Tensor) -> torch.Tensor:
"""Apply velocity-specific augmentations"""
aug_strength = self.aug_scheduler.strength
# Velocity scaling
if augs.VELOCITY_AUG and torch.rand(1) < aug_params.VEL_AUG_PROB * aug_strength:
scales = 1.0 + (torch.rand(velocity.size(0), 1, 1, 1, device=self.device) * 2 - 1) * aug_params.VEL_AUG_SCALE * aug_strength
velocity = velocity * scales
# Velocity smoothing
if augs.VELOCITY_SMOOTH and torch.rand(1) < aug_params.VEL_SMOOTH_PROB * aug_strength:
kernel_size = random.choice([3, 5])
velocity = F.avg_pool2d(
velocity,
kernel_size=kernel_size,
stride=1,
padding=kernel_size // 2
)
return torch.clamp(velocity, cfg.VELOCITY_MIN, cfg.VELOCITY_MAX)
def _simulate_faults(self, velocity: torch.Tensor) -> torch.Tensor:
"""Simulate geological faults in velocity models"""
batch_size, _, h, w = velocity.shape
x, y = torch.arange(w, device=self.device), torch.arange(h, device=self.device)
xx, yy = torch.meshgrid(x, y, indexing='xy')
# Generate random fault lines
angles = torch.rand(batch_size, device=self.device) * math.pi
offsets = (torch.rand(batch_size, device=self.device) * 2 - 1) * math.sqrt(h**2+w**2) * 0.2
mask = (xx * torch.cos(angles).view(-1, 1, 1) + yy * torch.sin(angles).view(-1, 1, 1)) > offsets.view(-1, 1, 1)
# Apply displacement along faults
displacement = (torch.rand_like(velocity) * 2 - 1) * self.velocity_range * aug_params.FAULT_NOISE_STRENGTH
velocity[mask.unsqueeze(1)] += displacement[mask.unsqueeze(1)]
return torch.clamp(velocity, cfg.VELOCITY_MIN, cfg.VELOCITY_MAX)
def process_batch(self, seismic: torch.Tensor, velocity: Optional[torch.Tensor] = None,
groups: Optional[List[str]] = None, is_train: bool = False) -> Tuple:
"""
Process a batch of data including normalization and augmentations.
Args:
seismic: Input seismic data
velocity: Target velocity data (optional)
groups: Data group labels (optional)
is_train: Whether to apply training augmentations
Returns:
Tuple of (processed_seismic, normalized_velocity, denormalized_velocity)
"""
# Transfer to device
seismic = seismic.to(self.device, non_blocking=True)
original_velocity = velocity
if velocity is not None:
velocity = velocity.to(self.device, non_blocking=True)
# Apply augmentations during training
aug_strength = self.aug_scheduler.strength if is_train else 0.0
if is_train and velocity is not None:
# Elastic deformation
if augs.ELASTIC_DEFORM and torch.rand(1) < aug_params.ELASTIC_DEFORM_PROB * aug_strength:
velocity = self._elastic_deform(
velocity,
alpha=random.uniform(*cfg.ELASTIC_ALPHA_RANGE),
sigma=random.uniform(*cfg.ELASTIC_SIGMA_RANGE)
)
# Fault simulation
if augs.FAULT_SIMULATION and torch.rand(1) < aug_params.FAULT_NOISE_PROB * aug_strength:
velocity = self._simulate_faults(velocity)
# Amplitude jitter
if augs.AMP_JITTER and torch.rand(1) < aug_params.AMP_JITTER_PROB * aug_strength:
seismic *= (1.0 + (torch.rand(seismic.size(0), 1, 1, 1, device=self.device) * 2 - 1) * aug_params.AMP_JITTER_SCALE)
# Receiver dropout
if augs.RECEIVER_DROP and torch.rand(1) < aug_params.RECEIVER_DROP_PROB * aug_strength:
num_drops = torch.randint(1, aug_params.MAX_RECEIVER_DROPS + 1, (1,)).item()
if seismic.dim() == 4 and seismic.size(1) == cfg.NUM_SOURCES:
perm = torch.rand(seismic.size(0), cfg.NUM_SOURCES, device=self.device).argsort(dim=1)
seismic[torch.arange(seismic.size(0), device=self.device).unsqueeze(1), perm[:, :num_drops]] = 0.0
# Gaussian noise
if augs.GAUSSIAN_NOISE:
seismic += torch.randn_like(seismic) * aug_params.NOISE_STD * aug_strength
# Normalize seismic data
mean = seismic.mean(dim=(-1, -2), keepdim=True)
std = torch.clamp(seismic.std(dim=(-1, -2), keepdim=True), min=cfg.MIN_STD_CLAMP)
seismic = (seismic - mean) / std
# Handle NaN values
if torch.isnan(seismic).any():
logging.warning("NaN values detected in seismic data after normalization. Replacing with zeros.")
seismic = torch.nan_to_num(seismic)
# Normalize velocity if provided
if velocity is not None:
norm_velocity = (velocity - self.velocity_min) / self.velocity_range
return seismic, norm_velocity, original_velocity.to(self.device) if original_velocity is not None else None
return seismic, None, None
def denormalize(self, norm_vel: torch.Tensor) -> torch.Tensor:
"""Convert normalized velocity back to original scale"""
return norm_vel * self.velocity_range + self.velocity_min
# Model Architecture
class SCSEBlock(nn.Module):
"""Squeeze-and-Excitation block with spatial attention"""
def __init__(self, channels: int, reduction: int = cfg.SCSE_REDUCTION) -> None:
super().__init__()
# Channel attention
self.cSE = nn.Sequential(
nn.AdaptiveAvgPool2d(1),
nn.Conv2d(channels, channels//reduction, 1),
nn.GELU(),
nn.Conv2d(channels//reduction, channels, 1),
nn.Sigmoid()
)
# Spatial attention
self.sSE = nn.Sequential(
nn.Conv2d(channels, 1, 1),
nn.Sigmoid()
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x * self.cSE(x) + x * self.sSE(x)
class LearnedUpsample(nn.Module):
"""Learned upsampling using PixelShuffle for smooth, artifact-free upsampling"""
def __init__(self, in_channels: int, out_channels: int, scale_factor: int = 2) -> None:
super().__init__()
self.scale_factor = scale_factor
self.conv = nn.Conv2d(
in_channels,
out_channels * (scale_factor ** 2),
kernel_size=3,
padding=1,
bias=False
)
self.pixel_shuffle = nn.PixelShuffle(scale_factor)
self.norm = nn.GroupNorm(cfg.GROUPNORM_GROUPS, out_channels)
self.activation = nn.GELU()
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.conv(x)
x = self.pixel_shuffle(x)
x = self.norm(x)
return self.activation(x)
class ResidualBlock(nn.Module):
"""Residual block for decoder with improved skip connections"""
def __init__(self, channels: int, dropout: float = 0.1) -> None:
super().__init__()
self.conv1 = nn.Conv2d(channels, channels, 3, padding=1, bias=False)
self.norm1 = nn.GroupNorm(cfg.GROUPNORM_GROUPS, channels)
self.conv2 = nn.Conv2d(channels, channels, 3, padding=1, bias=False)
self.norm2 = nn.GroupNorm(cfg.GROUPNORM_GROUPS, channels)
self.activation = nn.GELU()
self.dropout = nn.Dropout2d(dropout)
self.scse = SCSEBlock(channels)
def forward(self, x: torch.Tensor) -> torch.Tensor:
residual = x
x = self.conv1(x)
x = self.norm1(x)
x = self.activation(x)
x = self.dropout(x)
x = self.conv2(x)
x = self.norm2(x)
# Add residual connection
x = x + residual
x = self.activation(x)
# Apply attention
x = self.scse(x)
return x
class EnhancedUNetDecoderBlock(nn.Module):
"""Enhanced decoder block with learned upsampling and improved residual connections"""
def __init__(self, in_ch: int, skip_ch: int, out_ch: int) -> None:
super().__init__()
# Learned upsampling instead of simple interpolation
self.learned_upsample = LearnedUpsample(in_ch, in_ch)
# Channel reduction for concatenated features
concat_ch = in_ch + skip_ch
self.channel_reduce = nn.Conv2d(concat_ch, out_ch, 1, bias=False)
self.reduce_norm = nn.GroupNorm(cfg.GROUPNORM_GROUPS, out_ch)
# Residual processing blocks
self.res_block1 = ResidualBlock(out_ch, cfg.DECODER_DROPOUT)
self.res_block2 = ResidualBlock(out_ch, cfg.DECODER_DROPOUT)
# Skip connection for the entire block
self.skip_conv = nn.Conv2d(concat_ch, out_ch, 1, bias=False) if concat_ch != out_ch else nn.Identity()
def forward(self, x: torch.Tensor, skip: torch.Tensor) -> torch.Tensor:
# Learned upsampling
x_up = self.learned_upsample(x)
# Concatenate with skip connection
x_concat = torch.cat([x_up, skip], dim=1)
# Store for skip connection
skip_input = x_concat
# Channel reduction
x = self.channel_reduce(x_concat)
x = self.reduce_norm(x)
x = F.gelu(x)
# Residual processing
x = self.res_block1(x)
x = self.res_block2(x)
# Block-level skip connection
if not isinstance(self.skip_conv, nn.Identity):
skip_processed = self.skip_conv(skip_input)
x = x + skip_processed
return x
class MultiSourceUNetSwin(nn.Module):
"""Main model combining Swin Transformer backbone with UNet-like decoder"""
def __init__(self, ddp_manager: DDPManager) -> None:
super().__init__()
# Initial stem convolution
self.stem = nn.Sequential(
nn.Conv2d(1, cfg.STEM_CHANNELS, 3, padding=1, bias=False),
nn.GroupNorm(cfg.GROUPNORM_GROUPS, cfg.STEM_CHANNELS),
nn.GELU(),
nn.Conv2d(cfg.STEM_CHANNELS, cfg.STEM_CHANNELS, 3, padding=1, bias=False),
nn.GroupNorm(cfg.GROUPNORM_GROUPS, cfg.STEM_CHANNELS),
nn.GELU(),
nn.Conv2d(cfg.STEM_CHANNELS, cfg.RGB_CHANNELS, 1, bias=False)
)
# Load backbone (Swin Transformer V2) with warning suppression
if ddp_manager.is_ddp:
# Ensure all processes load the same pretrained weights
if ddp_manager.is_main_process():
self.backbone = timm.create_model(
cfg.MODEL_NAME,
pretrained=cfg.PRETRAINED,
in_chans=cfg.RGB_CHANNELS,
features_only=True
)
safe_barrier(ddp_manager)
if not ddp_manager.is_main_process():
self.backbone = timm.create_model(
cfg.MODEL_NAME,
pretrained=cfg.PRETRAINED,
in_chans=cfg.RGB_CHANNELS,
features_only=True
)
else:
self.backbone = timm.create_model(
cfg.MODEL_NAME,
pretrained=cfg.PRETRAINED,
in_chans=cfg.RGB_CHANNELS,
features_only=True
)
# Enable gradient checkpointing if available
if hasattr(self.backbone, 'set_grad_checkpointing'):
self.backbone.set_grad_checkpointing(True)
if ddp_manager.is_main_process():
logging.info("Gradient checkpointing enabled for backbone.")
# Build enhanced decoder with learned upsampling and residual blocks
enc_channels = self.backbone.feature_info.channels()
dec_channels = cfg.DECODER_CHANNELS
if ddp_manager.is_main_process():
logging.info(f"Building enhanced decoder with channels: {dec_channels}")
logging.info(f"Encoder channels: {enc_channels}")
decoder_layers = []
in_ch = enc_channels[-1]
for i in range(len(dec_channels)):
skip_ch = enc_channels[-(i+2)]
out_ch = dec_channels[i]
decoder_layers.append(EnhancedUNetDecoderBlock(in_ch, skip_ch, out_ch))