From 2774923697b3775a7ecd070b0bc6385f650c8fa1 Mon Sep 17 00:00:00 2001 From: UGBOMEH OGOCHUKWU WILLIAMS Date: Wed, 8 Apr 2026 17:30:03 +0100 Subject: [PATCH 1/3] Fix #8802: read nda_croppeds from input dict when pre-computed ImageStats.__call__ crashed with UnboundLocalError when a caller pre-populated "nda_croppeds" in the input dict. The variable was only assigned in the if-branch but referenced unconditionally on both paths. Added the missing else-branch to read the pre-computed value from the dict, and wrapped the method body in try/finally to guarantee grad state is always restored on exit. Fixes #8802 --- monai/auto3dseg/analyzer.py | 54 +++++++++++++++++++----------------- tests/apps/test_auto3dseg.py | 30 ++++++++++++++++++++ 2 files changed, 59 insertions(+), 25 deletions(-) diff --git a/monai/auto3dseg/analyzer.py b/monai/auto3dseg/analyzer.py index a731546a9e..47467b07e5 100644 --- a/monai/auto3dseg/analyzer.py +++ b/monai/auto3dseg/analyzer.py @@ -255,36 +255,40 @@ def __call__(self, data): restore_grad_state = torch.is_grad_enabled() torch.set_grad_enabled(False) - ndas = [d[self.image_key][i] for i in range(d[self.image_key].shape[0])] - if "nda_croppeds" not in d: - nda_croppeds = [get_foreground_image(nda) for nda in ndas] - - # perform calculation - report = deepcopy(self.get_report_format()) - - report[ImageStatsKeys.SHAPE] = [list(nda.shape) for nda in ndas] - report[ImageStatsKeys.CHANNELS] = len(ndas) - report[ImageStatsKeys.CROPPED_SHAPE] = [list(nda_c.shape) for nda_c in nda_croppeds] - report[ImageStatsKeys.SPACING] = ( - affine_to_spacing(data[self.image_key].affine).tolist() - if isinstance(data[self.image_key], MetaTensor) - else [1.0] * min(3, data[self.image_key].ndim) - ) + try: + ndas = [d[self.image_key][i] for i in range(d[self.image_key].shape[0])] + if "nda_croppeds" not in d: + nda_croppeds = [get_foreground_image(nda) for nda in ndas] + else: + nda_croppeds = d["nda_croppeds"] + + # perform calculation + report = deepcopy(self.get_report_format()) + + report[ImageStatsKeys.SHAPE] = [list(nda.shape) for nda in ndas] + report[ImageStatsKeys.CHANNELS] = len(ndas) + report[ImageStatsKeys.CROPPED_SHAPE] = [list(nda_c.shape) for nda_c in nda_croppeds] + report[ImageStatsKeys.SPACING] = ( + affine_to_spacing(data[self.image_key].affine).tolist() + if isinstance(data[self.image_key], MetaTensor) + else [1.0] * min(3, data[self.image_key].ndim) + ) - report[ImageStatsKeys.SIZEMM] = [ - a * b for a, b in zip(report[ImageStatsKeys.SHAPE][0], report[ImageStatsKeys.SPACING]) - ] + report[ImageStatsKeys.SIZEMM] = [ + a * b for a, b in zip(report[ImageStatsKeys.SHAPE][0], report[ImageStatsKeys.SPACING]) + ] - report[ImageStatsKeys.INTENSITY] = [ - self.ops[ImageStatsKeys.INTENSITY].evaluate(nda_c) for nda_c in nda_croppeds - ] + report[ImageStatsKeys.INTENSITY] = [ + self.ops[ImageStatsKeys.INTENSITY].evaluate(nda_c) for nda_c in nda_croppeds + ] - if not verify_report_format(report, self.get_report_format()): - raise RuntimeError(f"report generated by {self.__class__} differs from the report format.") + if not verify_report_format(report, self.get_report_format()): + raise RuntimeError(f"report generated by {self.__class__} differs from the report format.") - d[self.stats_name] = report + d[self.stats_name] = report + finally: + torch.set_grad_enabled(restore_grad_state) - torch.set_grad_enabled(restore_grad_state) logger.debug(f"Get image stats spent {time.time() - start}") return d diff --git a/tests/apps/test_auto3dseg.py b/tests/apps/test_auto3dseg.py index 6c840e944d..d95ec249ed 100644 --- a/tests/apps/test_auto3dseg.py +++ b/tests/apps/test_auto3dseg.py @@ -539,6 +539,36 @@ def test_seg_summarizer(self): assert str(DataStatsKeys.FG_IMAGE_STATS) in report assert str(DataStatsKeys.LABEL_STATS) in report + def test_image_stats_precomputed_nda_croppeds(self): + # Verify that ImageStats does not crash when nda_croppeds is pre-populated in the dict. + # Previously this caused UnboundLocalError because the variable was only assigned in + # the else branch but used unconditionally. + analyzer = ImageStats(image_key="image") + image = torch.rand(1, 10, 10, 10) + precomputed = [np.random.rand(8, 8, 8)] # simulated pre-cropped foreground + data = {"image": MetaTensor(image), "nda_croppeds": precomputed} + result = analyzer(data) + assert "image_stats" in result + assert verify_report_format(result["image_stats"], analyzer.get_report_format()) + + def test_analyzer_grad_state_restored_after_call(self): + # Verify that ImageStats.__call__ always restores the grad-enabled state it found + # on entry, regardless of which state that was. + analyzer = ImageStats(image_key="image") + image = torch.rand(1, 10, 10, 10) + data = {"image": MetaTensor(image)} + + # grad enabled before call → must still be enabled after + torch.set_grad_enabled(True) + analyzer(data) + assert torch.is_grad_enabled(), "grad state was not restored after ImageStats call" + + # grad disabled before call → must still be disabled after + torch.set_grad_enabled(False) + analyzer(data) + assert not torch.is_grad_enabled(), "grad state was not restored after ImageStats call" + torch.set_grad_enabled(True) # restore for subsequent tests + def tearDown(self) -> None: self.test_dir.cleanup() From e68198515219b4bf759d69cab61e10e232a7061c Mon Sep 17 00:00:00 2001 From: UGBOMEH OGOCHUKWU WILLIAMS Date: Thu, 9 Apr 2026 11:59:05 +0100 Subject: [PATCH 2/3] DCO Remediation Commit for UGBOMEH OGOCHUKWU WILLIAMS I, UGBOMEH OGOCHUKWU WILLIAMS , hereby add my Signed-off-by to this commit: 2774923697b3775a7ecd070b0bc6385f650c8fa1 Signed-off-by: UGBOMEH OGOCHUKWU WILLIAMS From e80119c445ea95dc46f9367fb06dc119fbb72530 Mon Sep 17 00:00:00 2001 From: UGBOMEH OGOCHUKWU WILLIAMS Date: Thu, 9 Apr 2026 15:45:59 +0100 Subject: [PATCH 3/3] Address review feedback on #8809: validate nda_croppeds and add test docstrings - Validate pre-computed nda_croppeds is a list with one entry per channel, raising ValueError with a clear message if not - Convert inline comments to docstrings on test methods to satisfy docstring coverage CI check - Wrap grad-disabled test leg in try/finally so global state is always restored Signed-off-by: UGBOMEH OGOCHUKWU WILLIAMS --- monai/auto3dseg/analyzer.py | 6 ++++++ tests/apps/test_auto3dseg.py | 23 +++++++++++++++-------- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/monai/auto3dseg/analyzer.py b/monai/auto3dseg/analyzer.py index 47467b07e5..2f6e3857ef 100644 --- a/monai/auto3dseg/analyzer.py +++ b/monai/auto3dseg/analyzer.py @@ -261,6 +261,12 @@ def __call__(self, data): nda_croppeds = [get_foreground_image(nda) for nda in ndas] else: nda_croppeds = d["nda_croppeds"] + if not isinstance(nda_croppeds, (list, tuple)) or len(nda_croppeds) != len(ndas): + raise ValueError( + f"Pre-computed 'nda_croppeds' must be a list with one entry per image channel " + f"(expected {len(ndas)}, got " + f"{len(nda_croppeds) if isinstance(nda_croppeds, (list, tuple)) else type(nda_croppeds).__name__})." + ) # perform calculation report = deepcopy(self.get_report_format()) diff --git a/tests/apps/test_auto3dseg.py b/tests/apps/test_auto3dseg.py index d95ec249ed..1b41e84ef4 100644 --- a/tests/apps/test_auto3dseg.py +++ b/tests/apps/test_auto3dseg.py @@ -540,9 +540,11 @@ def test_seg_summarizer(self): assert str(DataStatsKeys.LABEL_STATS) in report def test_image_stats_precomputed_nda_croppeds(self): - # Verify that ImageStats does not crash when nda_croppeds is pre-populated in the dict. - # Previously this caused UnboundLocalError because the variable was only assigned in - # the else branch but used unconditionally. + """Verify ImageStats handles pre-populated nda_croppeds without crashing. + + Previously raised UnboundLocalError because nda_croppeds was only assigned + inside the ``if "nda_croppeds" not in d`` branch but used unconditionally. + """ analyzer = ImageStats(image_key="image") image = torch.rand(1, 10, 10, 10) precomputed = [np.random.rand(8, 8, 8)] # simulated pre-cropped foreground @@ -552,8 +554,11 @@ def test_image_stats_precomputed_nda_croppeds(self): assert verify_report_format(result["image_stats"], analyzer.get_report_format()) def test_analyzer_grad_state_restored_after_call(self): - # Verify that ImageStats.__call__ always restores the grad-enabled state it found - # on entry, regardless of which state that was. + """Verify ImageStats restores torch grad-enabled state on both normal and disabled entry. + + Checks that the try/finally guard correctly restores the state regardless of + whether grad was enabled or disabled before the call. + """ analyzer = ImageStats(image_key="image") image = torch.rand(1, 10, 10, 10) data = {"image": MetaTensor(image)} @@ -565,9 +570,11 @@ def test_analyzer_grad_state_restored_after_call(self): # grad disabled before call → must still be disabled after torch.set_grad_enabled(False) - analyzer(data) - assert not torch.is_grad_enabled(), "grad state was not restored after ImageStats call" - torch.set_grad_enabled(True) # restore for subsequent tests + try: + analyzer(data) + assert not torch.is_grad_enabled(), "grad state was not restored after ImageStats call" + finally: + torch.set_grad_enabled(True) # always restore for subsequent tests def tearDown(self) -> None: self.test_dir.cleanup()