Skip to content

Commit 0f5c5ec

Browse files
authored
Remove dead and redundant code across monai/ (#8952)
### Description Ran a code agent for dead code. Vetted them myself thereafter. Removes dead statements, no-ops, and leftover commented-out code. No runtime behavior changes. | File | Dead/redundant code removed | |---|---| | `networks/nets/basic_unet.py` | Stray `print(f"BasicUNet features: ...")` debug call in constructor | | `networks/nets/basic_unetplusplus.py` | Stray `print(f"BasicUNetPlusPlus features: ...")` debug call in constructor | | `networks/blocks/text_embedding.py` | Stray `print(self.text_embedding)` debug call in `TextEncoder.forward` | | `metrics/generalized_dice.py` | No-op self-assignment `y_pred_o = y_pred_o` | | `networks/layers/simplelayers.py` | No-op self-assignment `filter = filter` in `MeanFilter` | | `losses/nacl_loss.py` | Redundant `.abs_()` after `.pow_(2)` (operand already non-negative) in L2 branch | | `losses/image_dissimilarity.py` | Overwrite discarding the `look_up_option`-validated `kernel_type` in `GlobalMutualInformationLoss` | | `data/ultrasound_confidence_map.py` | Dead `elif` branch with discarded bare `s.shape[0]` expression | | `inferers/merger.py` | Duplicated recomputation of `is_zarr_v3` in `ZarrAvgMerger` | | `utils/profiling.py` | Unused module-level `pandas` optional-import (only consumer re-imports locally) | | `apps/nnunet/utils.py` | Three blocks of commented-out code in `create_new_dataset_json` | | `apps/vista3d/transforms.py` | Commented-out `AsDiscrete` alternative | | `transforms/utils.py` | Commented-out `torch.zeros` alternative | | `networks/layers/filtering.py` | Unreachable commented-out body after `raise` in `PHLFilter.backward` | ### Types of changes - [x] Non-breaking change (fix or new feature that would not break existing functionality). --------- Signed-off-by: Soumya Snigdha Kundu <soumya_snigdha.kundu@kcl.ac.uk>
1 parent 683e1d1 commit 0f5c5ec

13 files changed

Lines changed: 2 additions & 27 deletions

File tree

monai/apps/nnunet/utils.py

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,6 @@ def create_new_dataset_json(
149149
"""
150150
new_json_data: dict = {}
151151

152-
# modality = self.input_info.pop("modality")
153152
modality = ensure_tuple(modality) # type: ignore
154153

155154
new_json_data["channel_names"] = {}
@@ -161,18 +160,11 @@ def create_new_dataset_json(
161160
for _j in range(num_foreground_classes):
162161
new_json_data["labels"][f"class{_j + 1}"] = _j + 1
163162

164-
# new_json_data["numTraining"] = len(datalist_json["training"])
165163
new_json_data["numTraining"] = num_training_data
166164
new_json_data["file_ending"] = ".nii.gz"
167165

168166
ConfigParser.export_config_file(
169-
config=new_json_data,
170-
# filepath=os.path.join(raw_data_foldername, "dataset.json"),
171-
filepath=output_filepath,
172-
fmt="json",
173-
sort_keys=True,
174-
indent=4,
175-
ensure_ascii=False,
167+
config=new_json_data, filepath=output_filepath, fmt="json", sort_keys=True, indent=4, ensure_ascii=False
176168
)
177169

178170
return

monai/apps/vista3d/transforms.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -160,8 +160,6 @@ def __call__(self, data):
160160
pred = pred.argmax(0).unsqueeze(0).float() + 1.0
161161
pred[is_bk] = 0.0
162162
else:
163-
# AsDiscrete will remove NaN
164-
# pred = monai.transforms.AsDiscrete(threshold=0.5)(pred)
165163
pred[pred > 0] = 1.0
166164
if "label_prompt" in data and data["label_prompt"] is not None:
167165
pred += 0.5 # inplace mapping to avoid cloning pred

monai/inferers/merger.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -309,9 +309,6 @@ def __init__(
309309

310310
self.chunks = chunks
311311

312-
# Handle compressor/codecs based on zarr version
313-
is_zarr_v3 = version_geq(get_package_version("zarr"), "3.0.0")
314-
315312
# Initialize codecs/compressor attributes with proper types
316313
self.codecs: list | None = None
317314
self.value_codecs: list | None = None

monai/losses/image_dissimilarity.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,6 @@ def __init__(
232232
sigma = torch.mean(bin_centers[1:] - bin_centers[:-1]) * sigma_ratio
233233
self.kernel_type = look_up_option(kernel_type, ["gaussian", "b-spline"])
234234
self.num_bins = num_bins
235-
self.kernel_type = kernel_type
236235
# declared as buffers so they move with the module (e.g. ``.to(device)``); only populated for the
237236
# gaussian kernel, hence the ``Tensor`` annotation reflects the type at the use sites in that path.
238237
self.preterm: torch.Tensor | None

monai/losses/nacl_loss.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ def forward(self, inputs: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
138138
if self.distance_type == "l1":
139139
loss_conf = utargets.sub(inputs).abs_().mean()
140140
elif self.distance_type == "l2":
141-
loss_conf = utargets.sub(inputs).pow_(2).abs_().mean()
141+
loss_conf = utargets.sub(inputs).pow_(2).mean()
142142

143143
loss: torch.Tensor = loss_ce + self.alpha * loss_conf
144144

monai/metrics/generalized_dice.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,6 @@ def compute_generalized_dice(
181181
else:
182182
numer = 2.0 * (intersection * w)
183183
denom = denominator * w
184-
y_pred_o = y_pred_o
185184

186185
# Compute the score
187186
generalized_dice_score = numer / denom

monai/networks/blocks/text_embedding.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,6 @@ def forward(self):
7979
# text embedding as random initialized 'rand_embedding'
8080
text_embedding = self.text_embedding.weight
8181
else:
82-
print(self.text_embedding)
8382
text_embedding = nn.functional.relu(self.text_to_vision(self.text_embedding))
8483

8584
if self.spatial_dims == 3:

monai/networks/layers/filtering.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,9 +96,6 @@ def forward(ctx, input, features, sigmas=None):
9696
@staticmethod
9797
def backward(ctx, grad_output):
9898
raise NotImplementedError("PHLFilter does not currently support Backpropagation")
99-
# scaled_features, = ctx.saved_variables
100-
# grad_input = _C.phl_filter(grad_output, scaled_features)
101-
# return grad_input
10299

103100

104101
class TrainableBilateralFilterFunction(torch.autograd.Function):

monai/networks/layers/simplelayers.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -671,7 +671,6 @@ def __init__(self, spatial_dims: int, size: int) -> None:
671671
size: edge length of the filter
672672
"""
673673
filter = torch.ones([size] * spatial_dims)
674-
filter = filter
675674
super().__init__(filter=filter)
676675

677676

monai/networks/nets/basic_unet.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,6 @@ def __init__(
235235
"""
236236
super().__init__()
237237
fea = ensure_tuple_rep(features, 6)
238-
print(f"BasicUNet features: {fea}.")
239238

240239
self.conv_0 = TwoConv(spatial_dims, in_channels, features[0], act, norm, bias, dropout)
241240
self.down_1 = Down(spatial_dims, fea[0], fea[1], act, norm, bias, dropout)

0 commit comments

Comments
 (0)