-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.py
More file actions
1744 lines (1566 loc) · 73.7 KB
/
engine.py
File metadata and controls
1744 lines (1566 loc) · 73.7 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
import gc
import os
import shutil
import glob
from contextlib import contextmanager, nullcontext
from typing import Optional, Union
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.distributed as dist
import math
import optimization
import utilities.engine_initializers as initialize
import wandb
from logger import get_logger
from losses import UnReflectLoss
from highlight_render import HighlightRender
from utilities.ablation import Ablation
from utilities.model import pixel_mask_to_patch_mask
from utilities import engine_helpers
from utilities import engine_memory
from utilities import engine_visualization as engine_viz
from utilities.system_ops import get_slurm_time_left_minutes
ablation = Ablation(False)
class Engine:
def __init__(
self,
model: Union[nn.Module, str, None],
dataset: dict,
config: dict,
notes: str = "",
no_wandb: bool = False,
resume_run_id: str = None,
resume_info: Optional[dict] = None,
will_resume: bool = False,
rank: Optional[int] = None,
world_size: Optional[int] = None,
**kwargs,
):
"""
Initializes the Engine object for polarization-based reflection removal training.
Args:
model (nn.Module): The model to be trained or model config.
dataset (dict): Dictionary containing 'training', 'validation', and optionally 'test' datasets.
config (dict): Dictionary containing config like BATCH_SIZE, LEARNING_RATE, etc.
notes (str, optional): Additional notes for the training session. Defaults to "".
no_wandb (bool): Whether to disable wandb logging.
**kwargs: Additional keyword arguments.
"""
# Set memory-efficient settings
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.deterministic = False
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
torch.autograd.set_detect_anomaly(False) # Disable for performance
# Store configuration
self.config = config
self.config["NOTES"] = notes
self.no_wandb = no_wandb
# Bind ablation flag from config to both instance and module-level context
try:
enabled = bool(self.config.get("ABLATE", False))
except Exception:
enabled = False
ablation.set(enabled)
self.ablation = ablation
# Mark if this Engine is expected to resume from an existing run
# This must be set before any directory setup happens
self._will_resume = bool(will_resume)
# DDP: only set when config.DISTRIBUTE == "ddp"
self._rank = rank
self._world_size = world_size
self._is_ddp = world_size is not None and world_size > 1
self._distribute = config.get("DISTRIBUTE", "single")
# Initialize device and directories
device_dirs = initialize.device_and_directories(config)
self.device = device_dirs["device"]
self.RUNS_DIR = device_dirs["runs_dir"]
# Function to set attributes from initialization functions
def init(init_func, *args, **kwargs):
result = init_func(*args, **kwargs)
for key, value in result.items():
setattr(self, key, value)
return result
# Initialize the models
self.model = model
# Initialize all components using engine_initializers
init(initialize.dataloaders, dataset, config)
# for i in range(len(dataset["Training"])):
# print(dataset["Training"][i]["raw"].shape)
init(initialize.dimensions, self.training_dl, config)
init(initialize.hyperparameters, config)
init(initialize.optimizers, self.model, config)
init(initialize.schedulers, self.optimizer, config, self.training_dl)
init(initialize.transforms, self.height, self.width)
# Wandb: initialized only on rank 0 when DDP (see utilities.engine_initializers.wandb)
resume_wandb_run_id = resume_run_id
init(initialize.wandb, config, self.model, notes, no_wandb, resume_wandb_run_id)
init(initialize.tracking_metrics)
# Skip directory setup during initialization if we're going to resume
# The directories will be set up during resume_from_run()
if not self._will_resume:
if self._is_main_process() or not self._is_ddp:
init(initialize.setup_run_directories, self.RUNS_DIR, self.wandb, False)
if self._is_ddp:
runname_list = [getattr(self, "runname", None)]
dist.broadcast_object_list(runname_list, src=0)
self.runname = runname_list[0]
self.RUN_DIR = os.path.join(self.RUNS_DIR, self.runname)
self.MODELS_DIR = os.path.join(self.RUN_DIR, "models")
self.TEST_DIR = os.path.join(self.RUN_DIR, "tests")
self.paths_file = os.path.join(self.RUN_DIR, "loadeddata.csv")
init(
initialize.earlystopping,
self.earlystopping_patience,
self.MODELS_DIR,
self.runname,
)
self.config["name"] = self.runname
else:
# For resume mode, if resume_info is provided we bind the existing directories immediately
if resume_info is not None:
self.runname = os.path.basename(resume_info.get("run_dir"))
self.RUN_DIR = resume_info.get("run_dir")
self.MODELS_DIR = resume_info.get("models_dir")
self.TEST_DIR = os.path.join(self.RUN_DIR, "tests")
self.paths_file = os.path.join(self.RUN_DIR, "loadeddata.csv")
self.config["name"] = self.runname
else:
# Temporary placeholder; will be updated upon resume
self.config["name"] = "resuming"
self.add_highlights = HighlightRender(height=self.height, width=self.width).to(
self.device
)
# Save hyperparameters to json only when not resuming (rank 0 only when DDP)
if not self._will_resume and self._is_main_process():
initialize.save_hyperparameters_json(self.RUN_DIR, self.config)
# Once the run name is set, we move all the log files to the run directory (rank 0 only when DDP)
if not self._will_resume and self._is_main_process():
TEMPORARY_LOG_DIR = os.path.join(self.RUNS_DIR, "temporary")
if os.path.exists(TEMPORARY_LOG_DIR):
for log_file in os.listdir(TEMPORARY_LOG_DIR):
if log_file.endswith(".log"):
shutil.move(
os.path.join(TEMPORARY_LOG_DIR, log_file),
os.path.join(self.RUN_DIR, log_file),
)
# Initialize polarization-specific losses
self.logger = get_logger(
__name__,
log_to_file=self._is_main_process(),
relative_log_dir=self.RUN_DIR,
)
self.loss = UnReflectLoss(
weight_specular_loss=self.config.SPECULAR_LOSS_WEIGHT,
weight_diffuse_loss=self.config.DIFFUSE_LOSS_WEIGHT,
weight_highlight_loss=self.config.HIGHLIGHT_LOSS_WEIGHT,
weight_image_reconstruction=self.config.IMAGE_RECONSTRUCTION_LOSS_WEIGHT,
# Highlight regression loss parameters
hlreg_w_l1=float(self.config.get("HLREG_W_L1", 1.0)),
hlreg_use_charb=bool(self.config.get("HLREG_USE_CHARB", True)),
hlreg_w_dice=float(self.config.get("HLREG_W_DICE", 0.2)),
hlreg_w_ssim=float(self.config.get("HLREG_W_SSIM", 0.0)),
hlreg_w_grad=float(self.config.get("HLREG_W_GRAD", 0.0)),
hlreg_w_tv=float(self.config.get("HLREG_W_TV", 0.0)),
hlreg_balance_mode=self.config.get("HLREG_BALANCE_MODE", "none"),
hlreg_pos_weight=float(self.config.get("HLREG_POS_WEIGHT", 1.0)),
hlreg_focal_gamma=float(self.config.get("HLREG_FOCAL_GAMMA", 0.0)),
# Highlight rendering parameters
highlight_color=tuple(self.config.get("HIGHLIGHT_COLOR", [1.0, 1.0, 1.0])),
clamp_reconstruction=bool(self.config.get("CLAMP_RECONSTRUCTION", True)),
# Context and regularization weights
weight_seam=float(self.config.get("WEIGHT_SEAM", 0.5)),
ring_dilate_kernel=int(self.config.get("RING_DILATE_KERNEL", 7)),
seam_use_charb=bool(self.config.get("SEAM_USE_CHARB", True)),
seam_weight_grad=float(self.config.get("SEAM_WEIGHT_GRAD", 0.2)),
# Token-space loss parameters
weight_token_inpaint=float(
self.config.get("TOKEN_INPAINT_LOSS_WEIGHT", 1.0)
),
token_feat_alpha=float(self.config.get("TOKEN_FEAT_ALPHA", 0.5)),
# Diffuse highlight penalty parameters
weight_diffuse_highlight_penalty=float(
self.config.get("WEIGHT_DIFFUSE_HIGHLIGHT_PENALTY", 0.0)
),
diffuse_hl_threshold=float(self.config.get("DIFFUSE_HL_THRESHOLD", 0.7)),
diffuse_hl_use_charb=bool(self.config.get("DIFFUSE_HL_USE_CHARB", True)),
diffuse_hl_penalty_mode=self.config.get(
"DIFFUSE_HL_PENALTY_MODE", "brightness"
),
diffuse_hl_target_brightness=self.config.get(
"DIFFUSE_HL_TARGET_BRIGHTNESS", None
),
diffuse_hl_use_luminance=bool(
self.config.get("DIFFUSE_HL_USE_LUMINANCE", False)
),
).to(self.device)
# Memory management settings for optimal GPU memory usage
self.memory_cleanup_frequency = config.get(
"MEMORY_CLEANUP_FREQUENCY", 5
) # Clean every N batches
self.aggressive_cleanup = config.get(
"AGGRESSIVE_MEMORY_CLEANUP", True
) # Use gpuClean utility
self.memory_monitoring = config.get(
"MEMORY_MONITORING", False
) # Log memory usage
# training_sampler is set by init(dataloaders) when DDP; otherwise None
self.training_sampler = getattr(self, "training_sampler", None)
def _is_main_process(self) -> bool:
"""True if this process should log, save checkpoints, and run test."""
return self._rank is None or self._rank == 0
def _unwrap_model(self) -> nn.Module:
"""Return the underlying model (strip DDP or DataParallel wrapper)."""
if self._distribute in ("dp", "ddp"):
return self.model.module
return self.model
def composite_specular_diffuse(
self, specular: torch.Tensor, diffuse: torch.Tensor
) -> torch.Tensor:
"""
Composite specular and diffuse components into a reconstructed image.
Args:
specular (torch.Tensor): Specular component [B, C, H, W]
diffuse (torch.Tensor): Diffuse component [B, C, H, W]
Returns:
torch.Tensor: Reconstructed image [B, 3, H, W]
"""
if self.memory_monitoring:
engine_memory.log_memory_usage(
self.logger, "Before compositing", self.memory_monitoring
)
return engine_helpers.composite_specular_diffuse(specular, diffuse)
def trainloop(self):
"""
The main training loop that runs through all epochs, trains the model,
validates it, and handles early stopping and saving of the model.
"""
# Determine starting epoch (for resume functionality)
start_epoch = getattr(self, "start_epoch", 0)
if start_epoch > 0 and self._is_main_process():
self.logger.info(
f"Starting training loop from epoch index {start_epoch} (display: epoch {start_epoch + 1}/{self.epochs})",
context="TRAINING",
)
for e in range(start_epoch, self.epochs):
### TRAINING + VALIDATION FOR EACH EPOCH
self.train() # Train the model for one epoch
is_overfitting = self.validate() # Train the model for one epoch
if self._is_main_process():
self.csv_log_metrics() # Log the metrics to csv
# Save checkpoint every few epochs (rank 0 only when DDP)
if (e + 1) % self.config.get("SAVE_INTERVAL", 10) == 0:
self.save_checkpoint(e)
### BREAK IF EARLYSTOP
if is_overfitting == "EARLYSTOP":
break # Exit the training loop if early stopping condition is met
# Log locations of important data at the end of training (rank 0 only when DDP)
if self._is_main_process():
self.logger.info("TRAINING COMPLETE", context="SAVE")
self.logger.info(
f"Run directory: {os.path.abspath(self.RUN_DIR)}", context="SAVE"
)
self.logger.info(
f"Checkpoints : {os.path.abspath(self.MODELS_DIR)}", context="SAVE"
)
self.logger.info("Metrics :", context="SAVE")
self.logger.info(
f"Training : {os.path.abspath(os.path.join(self.RUN_DIR, 'training_metrics.csv'))}",
context="SAVE",
)
self.logger.info(
f"Validation : {os.path.abspath(os.path.join(self.RUN_DIR, 'validation_metrics.csv'))}",
context="SAVE",
)
# Remove unused IMAGES_DIR if it exists and is empty
images_dir = os.path.join(self.RUN_DIR, "images")
if os.path.exists(images_dir) and not os.listdir(images_dir):
try:
os.rmdir(images_dir)
self.logger.info(
f"Removed unused directory: {images_dir}", context="SAVE"
)
except OSError:
pass
def train(self):
"""Training phase for one epoch"""
return self.run_epoch(phase="Training")
def validate(self):
"""Validation phase for one epoch"""
result = self.run_epoch(phase="Validation")
# Early stopping logic
if result is not None:
self.step["epoch"] += 1 # Increasing epoch counter
self.LRschedulerPlateau.step(float(result))
if self._is_main_process():
self.earlystopping(
float(result),
self.model,
self.step["epoch"] - 1,
self.optimizer,
self.config,
self.wandb,
)
if self._is_ddp:
# Broadcast early_stop from rank 0 to all ranks
early_stop_tensor = torch.tensor(
1
if (self._is_main_process() and self.earlystopping.early_stop)
else 0,
device=self.device,
dtype=torch.int64,
)
dist.broadcast(early_stop_tensor, src=0)
if early_stop_tensor.item() != 0:
self.earlystopping.early_stop = True
if self.earlystopping.early_stop:
if self._is_main_process():
self.logger.info(
">> [EARLYSTOPPING]: Patience Reached, Stopping Training",
context="TRAINING",
)
return "EARLYSTOP"
return "IMPROVED"
return "CONTINUE"
def test(self):
"""Test phase"""
# Persistent test index: auto test after training is idx 0
test_idx = self._load_and_increment_test_index()
result = self.run_epoch(phase="Test", test_idx=test_idx)
if self.wandb is not None:
self.log_tests()
return result
def log_tests(self):
"""
Logs the test metrics to Weights and Biases.
"""
self.logger.info(">> TEST REPORT", context="TEST")
self.logger.info(self.metrics["Test"].describe(), context="TEST")
self.metrics["Test"].to_csv(os.path.join(self.RUN_DIR, "test_metrics.csv"))
if self.wandb:
self.wandb.log(
{"Test/Summary": wandb.Table(dataframe=self.metrics["Test"])}
)
# Log locations of important data
self.logger.info(">> RUN DATA LOCATIONS", context="SAVE")
self.logger.info(
f"Run data directory: {os.path.abspath(self.RUN_DIR)}", context="SAVE"
)
self.logger.info(
f"Models saved at: {os.path.abspath(self.MODELS_DIR)}", context="SAVE"
)
self.logger.info("Metrics CSV files:", context="SAVE")
self.logger.info(
f" - Training: {os.path.abspath(os.path.join(self.RUN_DIR, 'training_metrics.csv'))}",
context="SAVE",
)
self.logger.info(
f" - Validation: {os.path.abspath(os.path.join(self.RUN_DIR, 'validation_metrics.csv'))}",
context="SAVE",
)
self.logger.info(
f" - Test: {os.path.abspath(os.path.join(self.RUN_DIR, 'test_metrics.csv'))}",
context="SAVE",
)
# Log WandB URLs again for convenience
if hasattr(self.wandb, "url") and self.wandb.url:
self.logger.info(f"WandB run URL: {self.wandb.url}", context="WANDB")
project_url = self.wandb.url.rsplit("/", 1)[0]
self.logger.info(f"WandB project URL: {project_url}", context="WANDB")
def csv_log_metrics(self):
"""Save metrics to CSV files"""
if not self.metrics["Training"].empty:
self.metrics["Training"].to_csv(
os.path.join(self.RUN_DIR, "training_metrics.csv")
)
if not self.metrics["Validation"].empty:
self.metrics["Validation"].to_csv(
os.path.join(self.RUN_DIR, "validation_metrics.csv")
)
def console_log_metrics(
self,
stage,
epoch=None,
batch_idx=None,
dataloader_len=None,
extra_info=None,
):
"""
Print metrics and status information for training, validation, or test.
Parameters:
-----------
stage : str
The current stage ('Training', 'Validation', or 'Test').
epoch : int, optional
Current epoch number.
batch_idx : int, optional
Current batch index.
dataloader_len : int, optional
Length of the dataloader being used.
extra_info : str, optional
Additional information to display in the phase indicator.
"""
# Simple alignment function (since we don't have the original utilities)
def align(text, width, direction="left"):
if direction == "left":
return f"{text:<{width}}"
elif direction == "right":
return f"{text:>{width}}"
else: # center
return f"{text:^{width}}"
epoch_batch_info = align(
f"E {str(epoch + 1)}/{self.epochs} ", 10, "right"
) + align(f"B {str(batch_idx + 1)}/{dataloader_len} ", 10, "left")
# Note: extra_info is used in console logging but phase_indicator was unused
# Print header with run name and status information
if "offline" in self.runname:
printedrunname = "run"
else:
printedrunname = f"{self.runname.split('-')[0][0]}{self.runname.split('-')[1][0]}{self.runname.split('-')[2]}"
metricstring = align(f"{printedrunname}:", 6, "right") + epoch_batch_info
# Generate metrics string
metrs = ""
# Print metrics from the appropriate metrics dictionary
if stage in self.metrics.keys():
# First print the Loss column if it exists
if (
"Loss" in self.metrics[stage].columns
and self.metrics[stage]["Loss"].iloc[-1] is not None
):
metrs += (
"[yellow]Loss[/yellow]"
+ "="
+ align(
f"{self.metrics[stage]['Loss'].iloc[-1]:.4f}",
6,
"left",
)
+ " "
)
# Then print other columns that don't have a "/" in their name
for m in self.metrics[stage].columns:
if (
m != "Loss"
and "/" not in m
and self.metrics[stage][m].iloc[-1] is not None
and not m.startswith("Step/") # Skip step metrics
and not m.startswith(
"HyperParameters/"
) # Skip hyperparameter metrics
):
# Use full metric name for better readability
display_name = m if len(m) <= 6 else m[:6]
metrs += (
f"[yellow]{display_name}[/yellow]"
+ "="
+ align(
f"{self.metrics[stage][m].iloc[-1]:.4f}",
6,
"left",
)
+ " "
)
self.logger.info(metricstring + metrs, context=stage.upper())
def log_loaded_paths(self, paths, phase):
"""Log loaded file paths for debugging"""
if hasattr(self, "paths_file"):
with open(self.paths_file, mode="a") as file:
file.write(f"{self.step[f'{phase}_batch']},{paths}\n")
def backward_pass(
self,
loss_tensor,
accumulate_gradients=False,
phase="Training",
submodules_to_monitor=None,
):
"""
Performs the backward pass, including gradient calculation, clipping, and optimization steps.
Optimized for memory efficiency with strategic cleanup.
Args:
loss_tensor (torch.Tensor): The loss tensor to backpropagate
accumulate_gradients (bool): If True, will update weights after backpropagation
assuming gradient accumulation is complete
phase (str): Current phase ("Training", "Validation", "Test")
submodules_to_monitor (dict, optional): Dictionary mapping submodule names to submodule objects
for separate gradient/weight norm monitoring
Returns:
dict: A dictionary containing gradient norms, weight norms, and error status
"""
# Initialize return values
grad_norm = np.nan
weight_norm = np.nan
submodule_norms = {}
if phase != "Training":
loss_tensor.detach()
torch.cuda.empty_cache()
return {
"ERROR_IN_BACKWARD_PASS": False,
"grad_norm": grad_norm,
"weight_norm": weight_norm,
"submodule_norms": submodule_norms,
}
# Log memory usage before backward pass if monitoring is enabled
if self.memory_monitoring:
self._log_memory_usage("Before backward pass")
ERROR_IN_BACKWARD_PASS = False
try:
loss_tensor.backward()
except RuntimeError as e:
self.logger.error(
f">> [ERROR]: {e} - Skipping batch {self.step['Training_batch']} in epoch {self.step['epoch']}"
)
ERROR_IN_BACKWARD_PASS = True
# Gradient clipping with memory optimization
if (
self.config.GRADIENT_CLIPPING_MAX_NORM is not None
and not ERROR_IN_BACKWARD_PASS
):
try:
# Calculate gradient and weight norms for the whole model
grad_norm, weight_norm = optimization.get_norms(self.model.parameters())
# Calculate norms for specific submodules if requested
if submodules_to_monitor is not None:
for submodule_name, submodule in submodules_to_monitor.items():
if submodule is None:
continue
try:
sub_grad_norm, sub_weight_norm = optimization.get_norms(
submodule.parameters()
)
submodule_norms[submodule_name] = {
"grad_norm": sub_grad_norm,
"weight_norm": sub_weight_norm,
}
except Exception as e:
self.logger.warning(
f"Failed to compute norms for submodule {submodule_name}: {e}"
)
submodule_norms[submodule_name] = {
"grad_norm": np.nan,
"weight_norm": np.nan,
}
if self.config.GRADIENT_CLIPPING_MAX_NORM > 0:
torch.nn.utils.clip_grad_norm_(
self.model.parameters(),
max_norm=self.config.GRADIENT_CLIPPING_MAX_NORM,
)
except Exception as e:
self.logger.warning(f"Gradient clipping failed: {e}")
# Step only if warmup phase is finished and we are backpropagating the accumulated gradients
if accumulate_gradients:
if not ERROR_IN_BACKWARD_PASS:
self.optimizer.step()
self.optimizer.zero_grad()
self.LRscheduler.step()
# Aggressive memory cleanup after backward pass
loss_tensor.detach()
del loss_tensor
# Clean up gradients and intermediate computations
if self.aggressive_cleanup:
# Only clear gradients if we actually performed an optimizer step; otherwise
# leave them to accumulate for gradient accumulation.
if accumulate_gradients:
for param in self.model.parameters():
if param.grad is not None:
param.grad.detach_()
param.grad = None
# Force garbage collection and cache clearing
torch.cuda.empty_cache()
gc.collect()
return {
"ERROR_IN_BACKWARD_PASS": ERROR_IN_BACKWARD_PASS,
"grad_norm": grad_norm,
"weight_norm": weight_norm,
"submodule_norms": submodule_norms,
}
def switch_optimizer(self, current_epoch):
"""
Switches the optimizer if the current epoch matches the switch epoch and
the bootstrap and refining optimizers are different.
Args:
current_epoch (int): The current epoch number
Returns:
bool: True if the optimizer was switched, False otherwise
"""
if (
current_epoch == self.switch_optimizer_epoch
and self.optimizer_bootstrap_name != self.optimizer_refining_name
):
self.logger.info(
f">> [OPTIMIZER]: "
f"Switching from [{self.optimizer_bootstrap_name}] to [{self.optimizer_refining_name}]"
)
self.in_optswitch_phase = True
self.optimizer = getattr(optimization, self.optimizer_refining_name)(
self.model.parameters(),
lr=self.learning_rate,
weight_decay=self.weight_decay,
)
return True
return False
def run_epoch(self, phase: str, test_idx: Optional[int] = None) -> Optional[float]:
"""
Run one epoch of training, validation, or test.
Adapted for polarization-based reflection removal with memory optimizations.
Args:
phase: "Training", "Validation", or "Test"
Returns:
Average loss for the epoch (if applicable)
"""
# Phase setup
is_training = phase == "Training"
if is_training:
self.model.train()
else:
self.model.eval()
# Get dataset from the initialized dataset structure
dataset = self.dataset[phase]
if dataset is None:
self.logger.warning(
f"No dataset available for {phase}", context=phase.upper()
)
return None
# DDP: run Test phase only on rank 0
if phase == "Test" and self._is_ddp and not self._is_main_process():
return None
# When DDP, use stored training_dl/validation_dl and set_epoch for training
if self._is_ddp and phase in ("Training", "Validation"):
if phase == "Training" and self.training_sampler is not None:
self.training_sampler.set_epoch(self.step["epoch"])
dataloader = self.training_dl if phase == "Training" else self.validation_dl
else:
cpu_affinity = os.sched_getaffinity(os.getpid())
if self.config.get("NUM_WORKERS", "auto") == "auto":
NUM_WORKERS = int(math.floor(0.9 * len(list(cpu_affinity))))
else:
NUM_WORKERS = self.config.NUM_WORKERS
NUM_WORKERS = int(math.floor(0.9 * len(list(cpu_affinity))))
dataloader = torch.utils.data.DataLoader(
dataset,
batch_size=self.batch_size,
num_workers=NUM_WORKERS
if self.config.NUM_WORKERS == "auto"
else self.config.NUM_WORKERS,
drop_last=True,
pin_memory=self.config.PIN_MEMORY,
prefetch_factor=self.config.PREFETCH_FACTOR,
shuffle=self.config.SHUFFLE,
)
if len(dataloader) == 0:
self.logger.warning(
"Empty dataloader, skipping epoch.", context=phase.upper()
)
return None
epoch_losses = []
images_logged = False
# Switch optimizer if needed (for training)
if is_training:
self.switch_optimizer(self.step["epoch"])
base_lr = self.optimizer.param_groups[0]["lr"]
# Get image logging frequency from config
image_log_interval = self.config.get("IMAGE_LOG_INTERVAL", 20)
with self.choose_if_grad(phase):
for batch_idx, sample in enumerate(dataloader):
# Strategic memory cleanup at batch start
if batch_idx == 0 or batch_idx % self.memory_cleanup_frequency == 0:
torch.cuda.empty_cache()
if self.aggressive_cleanup:
gc.collect()
# Calculate step for warmup logic
step = self.step["epoch"] * len(dataloader) + batch_idx
# Determine if we should log images on this batch
log_images_this_batch = (
batch_idx > 0
and batch_idx % image_log_interval == 0
and image_log_interval > 1
) or (batch_idx == len(dataloader) - 1 and not images_logged)
# Warmup logic
if is_training and step < self.warmup_steps:
warmup_factor = step / self.warmup_steps
current_lr = base_lr * warmup_factor
for param_group in self.optimizer.param_groups:
param_group["lr"] = current_lr
### Add polarization highlights
random_light_pos = self.add_highlights.sample_light_source(
dist_to_camera=self.config.LIGHT_DISTANCE_RANGE,
left_right_angle=self.config.LIGHT_LEFT_RIGHT_ANGLE,
above_below_angle=self.config.LIGHT_ABOVE_BELOW_ANGLE,
batch_size=self.batch_size,
device=self.device,
)
highlight_result = self.add_highlights(
rgb=sample["diffuse"].to(self.device, non_blocking=True),
light_pos=random_light_pos,
surface_roughness=self.config.SURFACE_ROUGHNESS,
intensity=self.config.INTENSITY,
return_dataset_highlights=True,
dataset_highlight_dilation=self.config.DATASET_HIGHLIGHT_DILATION,
dataset_highlight_threshold=self.config.DATASET_HIGHLIGHT_THRESHOLD,
dataset_highlight_use_luminance=bool(
self.config.get("DATASET_HIGHLIGHT_USE_LUMINANCE", True)
),
)
dataset_highlights_soft_mask = highlight_result[
"dataset_highlights_soft_mask"
]
synthetic_highlights_soft_mask = highlight_result["highlight"]
### SUPERVISION MASKS: Control which pixels and patches provide supervision
# 1 if pixel provides supervision, 0 if not
pixel_supervision_mask = highlight_result["pixel_supervision_mask"]
# 1 if patch provides supervision and is to be included in the loss computation, 0 if to be excluded
patch_supervision_mask = pixel_mask_to_patch_mask(
dataset_highlights_soft_mask,
patch_size=16,
threshold=self.config.DATASET_HIGHLIGHT_SUPERVISION_THRESHOLD,
invert=True,
)
### HOLE MASKS: Control which pixels and patches are to be inpainted
pixel_inpaint_soft_mask = torch.clamp(
synthetic_highlights_soft_mask + dataset_highlights_soft_mask,
0,
1,
)
# 1 if the pixel needs to be inpainted, 0 if not
pixel_inpaint_mask = (
pixel_inpaint_soft_mask
> self.config.DATASET_HIGHLIGHT_SUPERVISION_THRESHOLD
).bool()
# 1 if the patch needs to be inpainted, 0 if not
patch_inpaint_mask = pixel_mask_to_patch_mask(
pixel_inpaint_mask,
patch_size=16,
threshold=self.config.DATASET_HIGHLIGHT_SUPERVISION_THRESHOLD,
invert=False,
)
# Token inpainter ground truth: run with unwrapped model under no_grad so that
# only one forward per step goes through DDP and participates in loss. Otherwise
# DDP sees a forward that does not use all parameters (just_extract_tokens=True
# uses only the encoder) and raises "Expected to have finished reduction...".
diffuse_img = sample["diffuse"].to(self.device, non_blocking=True)
with torch.no_grad():
raw_model = self._unwrap_model()
diffuse_teacher_tokens = raw_model(
diffuse_img, just_extract_tokens=True
)
### Constructing ground truth dict
rgb_highlighted = highlight_result["rgb_highlighted"]
if "specular" in sample:
specular = sample["specular"].to(self.device, non_blocking=True)
else:
specular = None
# Ground truth diffuse: original RGB (contains real highlights)
diffuse = sample["diffuse"].to(self.device, non_blocking=True)
gt_decomposition = {
"diffuse": diffuse, # Contains real highlights, but masked during loss
"rgb_highlighted": rgb_highlighted,
"specular": specular,
"highlight": pixel_inpaint_soft_mask,
"tokens_teacher": diffuse_teacher_tokens,
}
del sample # Clean up. All necessary data is already on GPU.
# Log memory usage before forward pass if monitoring
if self.memory_monitoring and batch_idx % 10 == 0:
self._log_memory_usage(f"Before forward pass - batch {batch_idx}")
if self.ablation:
print("This is an ablation block")
### Forward pass
model_input = {
"rgb": gt_decomposition["rgb_highlighted"],
# "inpaint_mask_override": pixel_inpaint_mask,
"inpaint_mask_threshold": self.config.INPAINT_MASK_THRESHOLD,
"inpaint_mask_dilation": self.config.INPAINT_MASK_DILATION,
}
# if self._distribute == "dp":
# pred_decomposition = self.model(
# model_input["rgb"],
# model_input["inpaint_mask_override"],
# model_input["inpaint_mask_threshold"],
# model_input["inpaint_mask_dilation"],
# )
# else:
pred_decomposition = self.model(model_input)
### COMPUTE LOSS FUNCTION
losses = self.loss(
prediction=pred_decomposition,
ground_truth=gt_decomposition,
pixel_supervision_mask=pixel_supervision_mask,
pixel_inpaint_mask=pixel_inpaint_mask,
patch_supervision_mask=patch_supervision_mask,
patch_inpaint_mask=patch_inpaint_mask,
)
loss_value = losses["total"]
# Compositing the reconstructed image - for visualization purposes
if "diffuse" in pred_decomposition:
pred_decomposition["rgb_highlighted"] = self.loss.reconstruct_image(
pred_decomposition
)
# Adding the loss mask to the gt_decomposition to log it on wandb
if phase == "Training":
gt_decomposition["supervision_mask"] = pixel_supervision_mask
gt_decomposition["masked_diffuse"] = (
diffuse * pixel_supervision_mask
)
### Backward pass
backward_output = None
if is_training:
try:
# Check if we should accumulate gradients
accumulate_gradients = (
batch_idx + 1
) % self.gradient_accumulation_steps == 0
# Use the backward_pass method
backward_output = self.backward_pass(
loss_value,
accumulate_gradients=accumulate_gradients,
phase=phase,
submodules_to_monitor={
"highlight_decoder": getattr(
self._unwrap_model().decoders,
"highlight",
None,
),
"diffuse_decoder": getattr(
self._unwrap_model().decoders,
"diffuse",
None,
),
"specular_decoder": getattr(
self._unwrap_model().decoders,
"specular",
None,
),
"dinov3": self._unwrap_model().dinov3,
"token_inpaint": getattr(
self._unwrap_model(),
"token_inpaint",
None,
),
},
)
except Exception as e:
self.logger.error(
f"Error in backward pass: {e}", context=phase.upper()
)
continue
# Track metrics
epoch_losses.append(loss_value.item())
self.step[f"{phase}_batch"] += 1
# Update metrics dataframe
metrics = {
"Loss": loss_value.item(),
"HyperParameters/LR": self.optimizer.param_groups[0]["lr"],
f"Step/{'val' if phase == 'Validation' else ''}batch": self.step[
f"{phase}_batch"
],
f"Step/{'idx' if phase == 'Test' else 'epoch'}": self.step["epoch"],
}
if phase == "Test" and test_idx is not None:
metrics["Step/test_idx"] = test_idx
metrics["Index"] = float(test_idx)
# Add individual loss components if available
if isinstance(losses, dict):
for loss_name, loss_val in losses.items():
if isinstance(loss_val, torch.Tensor) and loss_name != "total":
# Use the loss name directly (without "Loss_" prefix) for better display
metrics[loss_name] = loss_val.item()
# Add gradient information if available
if (
backward_output is not None
and backward_output.get("grad_norm") is not None
):
metrics["Gradients/MODEL_GradNorm"] = backward_output["grad_norm"]
metrics["Gradients/MODEL_WeightNorm"] = backward_output[
"weight_norm"
]
# Add submodule gradient norms if available
if "submodule_norms" in backward_output:
for submodule_name, norms in backward_output[
"submodule_norms"
].items():
metrics[f"Gradients/{submodule_name}_GradNorm"] = norms[
"grad_norm"
]
metrics[f"Gradients/{submodule_name}_WeightNorm"] = norms[
"weight_norm"
]
# Compute evaluation metrics (vectorized over batch)
eval_metrics = engine_helpers.compute_eval_metrics(
pred_decomposition,
gt_decomposition,
phase,
pixel_supervision_mask,
)
metrics.update(eval_metrics)