Skip to content

Commit 9638774

Browse files
committed
Remove all backward compatibility code from codebase
Removes backward compatibility code and comments to maintain a clean, modern codebase: **Config System (callbacks.py):** - Remove old config style support for checkpoint callbacks - Remove old config style support for early_stopping callbacks - Keep only modern unified config style (cfg.monitor.*) **Lightning Model (lit_model.py):** - Remove legacy parameter conversion for decode_binary_contour_distance_watershed - Remove legacy intensity_scale/output_scale fallbacks - Keep only modern config names (intensity_scale, intensity_dtype) **Transform Builders (build.py):** - Remove backward compatibility comments - Remove legacy image_transform.resize fallback - Keep only modern data_transform.resize path **Loss Functions (regularization.py):** - Remove backward compatibility aliases (BinaryReg, FgDTConsistency, etc.) **Utilities (visualizer.py):** - Remove legacy create_visualizer() factory function **Config (hydra_config.py, hydra_utils.py):** - Remove deprecated config field comments - Remove legacy path comments **Impact:** - 7 files modified - 92 lines removed - Clean, focused codebase without legacy support
1 parent c20b7b2 commit 9638774

File tree

7 files changed

+16
-92
lines changed

7 files changed

+16
-92
lines changed

connectomics/config/hydra_config.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -392,9 +392,7 @@ class DataConfig:
392392
default_factory=list
393393
) # Axis permutation for training data (e.g., [2,1,0] for xyz->zyx)
394394
val_transpose: List[int] = field(default_factory=list) # Axis permutation for validation data
395-
test_transpose: List[int] = field(
396-
default_factory=list
397-
) # Axis permutation for test data (deprecated, use inference.data.test_transpose)
395+
test_transpose: List[int] = field(default_factory=list) # Axis permutation for test data
398396

399397
# Dataset statistics (for auto-planning)
400398
target_spacing: Optional[List[float]] = None # Target voxel spacing [z, y, x] in mm
@@ -868,9 +866,7 @@ class TestTimeAugmentationConfig:
868866
flip_axes: Any = (
869867
None # TTA flip strategy: "all" (8 flips), null (no aug), or list like [[0], [1], [2]]
870868
)
871-
act: Optional[str] = (
872-
None # Single activation for all channels: 'softmax', 'sigmoid', 'tanh', None (deprecated, use channel_activations)
873-
)
869+
act: Optional[str] = None # Single activation for all channels: 'softmax', 'sigmoid', 'tanh', None
874870
channel_activations: Optional[List[Any]] = (
875871
None # Per-channel activations: [[start_ch, end_ch, 'activation'], ...] e.g., [[0, 2, 'softmax'], [2, 3, 'sigmoid'], [3, 4, 'tanh']]
876872
)

connectomics/config/hydra_utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -244,8 +244,8 @@ def resolve_data_paths(cfg: Config) -> Config:
244244
Supported paths:
245245
- Training: cfg.data.train_path + cfg.data.train_image/train_label/train_mask
246246
- Validation: cfg.data.val_path + cfg.data.val_image/val_label/val_mask
247-
- Testing (legacy): cfg.data.test_path + cfg.data.test_image/test_label/test_mask
248-
- Inference (primary): cfg.inference.data.test_path + cfg.inference.data.test_image/test_label/test_mask
247+
- Testing: cfg.data.test_path + cfg.data.test_image/test_label/test_mask
248+
- Inference: cfg.inference.data.test_path + cfg.inference.data.test_image/test_label/test_mask
249249
250250
Args:
251251
cfg: Config object to resolve paths for
@@ -316,7 +316,7 @@ def _combine_path(base_path: str, file_path: Optional[Union[str, List[str]]]) ->
316316
cfg.data.val_mask = _combine_path(cfg.data.val_path, cfg.data.val_mask)
317317
cfg.data.val_json = _combine_path(cfg.data.val_path, cfg.data.val_json)
318318

319-
# Resolve test paths (legacy support for cfg.data.test_path)
319+
# Resolve test paths
320320
if cfg.data.test_path:
321321
cfg.data.test_image = _combine_path(cfg.data.test_path, cfg.data.test_image)
322322
cfg.data.test_label = _combine_path(cfg.data.test_path, cfg.data.test_label)

connectomics/data/augment/build.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ def build_train_transforms(
7373
# Load images first (unless using pre-cached dataset)
7474
if not skip_loading:
7575
# Use appropriate loader based on dataset type
76-
dataset_type = getattr(cfg.data, "dataset_type", "volume") # Default to volume for backward compatibility
76+
dataset_type = getattr(cfg.data, "dataset_type", "volume")
7777

7878
if dataset_type == "filename":
7979
# For filename-based datasets (PNG, JPG, etc.), use MONAI's LoadImaged
@@ -94,12 +94,9 @@ def build_train_transforms(
9494
transforms.append(ApplyVolumetricSplitd(keys=keys))
9595

9696
# Apply resize if configured (before cropping)
97-
# Check data_transform first (new), then fall back to image_transform.resize (legacy)
9897
resize_size = None
9998
if hasattr(cfg.data, "data_transform") and hasattr(cfg.data.data_transform, "resize") and cfg.data.data_transform.resize is not None:
10099
resize_size = cfg.data.data_transform.resize
101-
elif hasattr(cfg.data.image_transform, "resize") and cfg.data.image_transform.resize is not None:
102-
resize_size = cfg.data.image_transform.resize
103100

104101
if resize_size:
105102
# Use bilinear for images, nearest for labels/masks
@@ -247,7 +244,7 @@ def _build_eval_transforms_impl(
247244
transforms = []
248245

249246
# Load images first - use appropriate loader based on dataset type
250-
dataset_type = getattr(cfg.data, "dataset_type", "volume") # Default to volume for backward compatibility
247+
dataset_type = getattr(cfg.data, "dataset_type", "volume")
251248

252249
if dataset_type == "filename":
253250
# For filename-based datasets (PNG, JPG, etc.), use MONAI's LoadImaged
@@ -455,8 +452,8 @@ def _build_augmentations(aug_cfg: AugmentationConfig, keys: list[str], do_2d: bo
455452
List of MONAI transforms
456453
"""
457454
transforms = []
458-
459-
# Get preset mode (default to "some" for backward compatibility)
455+
456+
# Get preset mode
460457
preset = getattr(aug_cfg, "preset", "some")
461458

462459
# Helper function to check if augmentation should be applied

connectomics/lightning/callbacks.py

Lines changed: 2 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -428,25 +428,7 @@ def create_callbacks(cfg) -> list:
428428
callbacks.append(vis_callback)
429429

430430
# Model checkpoint callback
431-
# Support both new unified config (training.checkpoint_*) and old separate config (checkpoint.*)
432-
if hasattr(cfg, 'checkpoint') and cfg.checkpoint is not None:
433-
# Old config style (backward compatibility)
434-
monitor = getattr(cfg.checkpoint, 'monitor', 'val/loss')
435-
default_filename = f'epoch={{epoch:03d}}-{monitor}={{{monitor}:.4f}}'
436-
filename = getattr(cfg.checkpoint, 'filename', default_filename)
437-
438-
checkpoint_callback = ModelCheckpoint(
439-
monitor=monitor,
440-
mode=getattr(cfg.checkpoint, 'mode', 'min'),
441-
save_top_k=getattr(cfg.checkpoint, 'save_top_k', 3),
442-
save_last=getattr(cfg.checkpoint, 'save_last', True),
443-
dirpath=getattr(cfg.checkpoint, 'dirpath', 'checkpoints'),
444-
filename=filename,
445-
verbose=True
446-
)
447-
callbacks.append(checkpoint_callback)
448-
elif hasattr(cfg, 'monitor') and hasattr(cfg.monitor, 'checkpoint'):
449-
# New unified config style (monitor.checkpoint.*)
431+
if hasattr(cfg, 'monitor') and hasattr(cfg.monitor, 'checkpoint'):
450432
monitor = getattr(cfg.monitor.checkpoint, 'monitor', 'val/loss')
451433
filename = getattr(cfg.monitor.checkpoint, 'filename', None)
452434
if filename is None:
@@ -465,19 +447,7 @@ def create_callbacks(cfg) -> list:
465447
callbacks.append(checkpoint_callback)
466448

467449
# Early stopping callback
468-
# Support both new unified config (training.early_stopping_*) and old separate config (early_stopping.*)
469-
if hasattr(cfg, 'early_stopping') and cfg.early_stopping is not None and cfg.early_stopping.enabled:
470-
# Old config style (backward compatibility)
471-
early_stop_callback = EarlyStopping(
472-
monitor=getattr(cfg.early_stopping, 'monitor', 'val/loss'),
473-
patience=getattr(cfg.early_stopping, 'patience', 10),
474-
mode=getattr(cfg.early_stopping, 'mode', 'min'),
475-
min_delta=getattr(cfg.early_stopping, 'min_delta', 0.0),
476-
verbose=True
477-
)
478-
callbacks.append(early_stop_callback)
479-
elif hasattr(cfg, 'monitor') and hasattr(cfg.monitor, 'early_stopping') and getattr(cfg.monitor.early_stopping, 'enabled', False):
480-
# New unified config style (monitor.early_stopping.*)
450+
if hasattr(cfg, 'monitor') and hasattr(cfg.monitor, 'early_stopping') and getattr(cfg.monitor.early_stopping, 'enabled', False):
481451
early_stop_callback = EarlyStopping(
482452
monitor=getattr(cfg.monitor.early_stopping, 'monitor', 'val/loss'),
483453
patience=getattr(cfg.monitor.early_stopping, 'patience', 10),

connectomics/lightning/lit_model.py

Lines changed: 5 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -597,17 +597,13 @@ def _apply_postprocessing(self, data: np.ndarray) -> np.ndarray:
597597
data = np.stack(results, axis=0)
598598
print(f" DEBUG: _apply_postprocessing - after stacking, data shape: {data.shape}")
599599

600-
# Step 2: Apply scaling if configured (support both new and legacy names)
600+
# Step 2: Apply scaling if configured
601601
intensity_scale = getattr(postprocessing, 'intensity_scale', None)
602-
output_scale = getattr(postprocessing, 'output_scale', None)
603-
scale = intensity_scale if intensity_scale is not None else output_scale
604-
if scale is not None:
605-
data = data * scale
602+
if intensity_scale is not None:
603+
data = data * intensity_scale
606604

607-
# Step 3: Apply dtype conversion if configured (support both new and legacy names)
608-
intensity_dtype = getattr(postprocessing, 'intensity_dtype', None)
609-
output_dtype = getattr(postprocessing, 'output_dtype', None)
610-
target_dtype_str = intensity_dtype if intensity_dtype is not None else output_dtype
605+
# Step 3: Apply dtype conversion if configured
606+
target_dtype_str = getattr(postprocessing, 'intensity_dtype', None)
611607

612608
if target_dtype_str is not None and target_dtype_str != 'float32':
613609
# Map string dtype to numpy dtype
@@ -739,27 +735,6 @@ def _apply_decode_mode(self, data: np.ndarray) -> np.ndarray:
739735

740736
decode_fn = decode_fn_map[fn_name]
741737

742-
# Backward compatibility: convert old parameter format to new tuple format
743-
# for decode_binary_contour_distance_watershed
744-
if fn_name == 'decode_binary_contour_distance_watershed':
745-
if 'seed_threshold' in kwargs or 'foreground_threshold' in kwargs:
746-
warnings.warn(
747-
"Detected legacy parameters (seed_threshold, contour_threshold, foreground_threshold) "
748-
"for decode_binary_contour_distance_watershed. Converting to new tuple format "
749-
"(binary_threshold, contour_threshold, distance_threshold). "
750-
"Please update your config files to use the new format.",
751-
DeprecationWarning,
752-
)
753-
# Convert old parameters to new tuple format
754-
seed_thresh = kwargs.pop('seed_threshold', 0.9)
755-
contour_thresh = kwargs.pop('contour_threshold', 0.8)
756-
foreground_thresh = kwargs.pop('foreground_threshold', 0.85)
757-
758-
# Map old parameters to new tuple format
759-
kwargs['binary_threshold'] = (seed_thresh, foreground_thresh)
760-
kwargs['contour_threshold'] = (contour_thresh, 1.1)
761-
kwargs['distance_threshold'] = (0.5, -0.5)
762-
763738
try:
764739
# Apply decoding function
765740
sample = decode_fn(sample, **kwargs)

connectomics/models/loss/regularization.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -294,14 +294,6 @@ def forward(self, pred: torch.Tensor) -> torch.Tensor:
294294
return loss.mean()
295295

296296

297-
# Aliases for backward compatibility (if needed in configs)
298-
BinaryReg = BinaryRegularization
299-
FgDTConsistency = ForegroundDistanceConsistency
300-
ContourDTConsistency = ContourDistanceConsistency
301-
FgContourConsistency = ForegroundContourConsistency
302-
NonoverlapReg = NonOverlapRegularization
303-
304-
305297
__all__ = [
306298
'BinaryRegularization',
307299
'ForegroundDistanceConsistency',

connectomics/utils/visualizer.py

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -590,9 +590,3 @@ def _should_visualize(self, trainer, batch_idx: int) -> bool:
590590
log_every_n_steps = getattr(self.cfg.optimization, "vis_every_n_steps", 100)
591591

592592
return trainer.global_step % log_every_n_steps == 0 and batch_idx == 0
593-
594-
595-
# Legacy compatibility
596-
def create_visualizer(cfg, **kwargs):
597-
"""Factory function for creating visualizer (backward compatible)."""
598-
return Visualizer(cfg, **kwargs)

0 commit comments

Comments
 (0)