From 6aafc929e9c6d460a2878fea19c4431d23e950bf Mon Sep 17 00:00:00 2001 From: Willy1118 <132340162+Willy1118@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:01:56 +0800 Subject: [PATCH 1/4] Add verify_bundle to validate bundle format (#7067) Add `verify_bundle` to `monai.bundle` so that the bundle format checks used by the model-zoo CI (ci/verify_bundle.py) are available as `python -m monai.bundle verify_bundle`. - "min" mode: required and preferred files, version/changelog consistency, and metadata schema validation. - "full" mode: additionally network input/output and TorchScript export, which can be skipped with `check_net_io` / `check_torchscript`. - The bundle path is temporarily added to `sys.path` in "full" mode so that custom code shipped with the bundle can be imported. - The bundle directory is not modified: the downloaded schema and the test TorchScript export are written to a temporary directory. - model-zoo specific parts (exclusion lists, per-bundle special cases, model_info.json version check) are replaced by arguments or omitted. Also fix `ckpt_export` for GPU-saved checkpoints on CPU-only machines: `_export` loaded the checkpoint with `torch.load` without `map_location`, so a checkpoint saved on GPU could not be exported without CUDA. It is now loaded on CPU and the weights are copied to the device of the network; the loaded checkpoint is passed to ignite's `Checkpoint.load_objects` as a mapping so both code paths are covered. Assisted-by: Claude Code Signed-off-by: Willy1118 <132340162+Willy1118@users.noreply.github.com> --- docs/source/bundle.rst | 1 + monai/bundle/__init__.py | 1 + monai/bundle/__main__.py | 1 + monai/bundle/scripts.py | 225 +++++++++++++++++++++- tests/bundle/test_bundle_verify_bundle.py | 164 ++++++++++++++++ 5 files changed, 390 insertions(+), 2 deletions(-) create mode 100644 tests/bundle/test_bundle_verify_bundle.py diff --git a/docs/source/bundle.rst b/docs/source/bundle.rst index fdf745e9513..d6b6418b456 100644 --- a/docs/source/bundle.rst +++ b/docs/source/bundle.rst @@ -46,6 +46,7 @@ Model Bundle .. autofunction:: get_bundle_info .. autofunction:: get_bundle_versions .. autofunction:: run +.. autofunction:: verify_bundle .. autofunction:: verify_metadata .. autofunction:: verify_net_in_out .. autofunction:: init_bundle diff --git a/monai/bundle/__init__.py b/monai/bundle/__init__.py index 3f3c8d545e4..a7c1315ec1c 100644 --- a/monai/bundle/__init__.py +++ b/monai/bundle/__init__.py @@ -31,6 +31,7 @@ run_workflow, trt_export, update_kwargs, + verify_bundle, verify_metadata, verify_net_in_out, ) diff --git a/monai/bundle/__main__.py b/monai/bundle/__main__.py index 778c9ef2f0c..ae9751ad524 100644 --- a/monai/bundle/__main__.py +++ b/monai/bundle/__main__.py @@ -20,6 +20,7 @@ run, run_workflow, trt_export, + verify_bundle, verify_metadata, verify_net_in_out, ) diff --git a/monai/bundle/scripts.py b/monai/bundle/scripts.py index b2809191281..bc72117e7d4 100644 --- a/monai/bundle/scripts.py +++ b/monai/bundle/scripts.py @@ -15,6 +15,8 @@ import json import os import re +import sys +import tempfile import urllib import warnings from collections.abc import Callable, Mapping, Sequence @@ -1274,6 +1276,223 @@ def verify_net_in_out( logger.info("data shape of network is verified with no error.") +def _find_bundle_file(root_dir: PathLike, name: str, suffixes: Sequence[str] = ("json", "yaml", "yml")) -> Path | None: + """Return the first existing file ``root_dir/name.``, or ``None`` if there is none.""" + for suffix in suffixes: + candidate = Path(root_dir) / f"{name}.{suffix}" + if candidate.is_file(): + return candidate + return None + + +def _verify_bundle_files(bundle_path: Path, check_preferred_files: bool) -> None: + """Check the files required (and, optionally, preferred) by the MONAI Bundle Specification.""" + for file in ("configs/metadata.json", "LICENSE"): + if not (bundle_path / file).is_file(): + raise FileNotFoundError(f"necessary file `{file}` is missing from bundle `{bundle_path}`.") + if check_preferred_files: + if not (bundle_path / "models" / "model.pt").is_file(): + hint = "" + if _find_bundle_file(bundle_path, "large_files") is not None: + hint = " It may be listed in the large_files file of the bundle, set `download_large=True` to fetch it." + raise FileNotFoundError(f"preferred file `models/model.pt` is missing from bundle `{bundle_path}`.{hint}") + if _find_bundle_file(bundle_path / "configs", "inference") is None: + raise FileNotFoundError( + f"preferred file `configs/inference.json` (or .yaml/.yml) is missing from bundle `{bundle_path}`." + ) + + +def _verify_bundle_version(meta_file: Path) -> None: + """Check that `version` and `changelog` exist in the metadata and that the version is in the changelog.""" + metadata = ConfigParser.load_config_file(filepath=meta_file) + for key in ("version", "changelog"): + if key not in metadata: + raise ValueError(f"`{key}` is missing in `{meta_file}`.") + version = metadata["version"] + if version not in metadata["changelog"]: + raise ValueError(f"version `{version}` is missing in the `changelog` of `{meta_file}`.") + + +def verify_bundle( + bundle_path: PathLike | None = None, + mode: str | None = None, + net_id: str | None = None, + config_file: str | None = None, + ckpt_file: str | None = None, + schema_file: PathLike | None = None, + check_preferred_files: bool | None = None, + check_net_io: bool | None = None, + check_torchscript: bool | None = None, + download_large: bool | None = None, + device: str | None = None, + args_file: str | None = None, +) -> None: + """ + Verify that a bundle follows the `MONAI Bundle Specification + `_, so that it can be used by the MONAI Model Zoo + and downstream applications. The bundle directory is not modified: the downloaded schema (unless + `schema_file` is given) and the test TorchScript export are written to a temporary directory. + + The checks, in order: + + - "min" and "full" modes: + - the necessary files ``configs/metadata.json`` and ``LICENSE`` exist, and, if + `check_preferred_files` is True, the preferred files ``models/model.pt`` and + ``configs/inference.json`` (or ``.yaml``/``.yml``) exist. + - ``version`` and ``changelog`` exist in the metadata, and the version is listed in the changelog. + - the metadata is valid against the schema referenced by its ``schema`` field, + see :py:func:`verify_metadata`. + - "full" mode only: + - the network input and output match the ``network_data_format`` of the metadata, + see :py:func:`verify_net_in_out`. Skipped if `check_net_io` is False. + - the checkpoint can be exported to TorchScript and loaded back, see :py:func:`ckpt_export`. + If ``models/model.ts`` exists, it is also loaded. Skipped if `check_torchscript` is False. + + In "full" mode, `bundle_path` is temporarily added to ``sys.path`` so that custom code shipped with + the bundle (for example, ``"$import scripts"`` in the config) can be imported. + + Typical usage examples: + + .. code-block:: bash + + # quick checks of the bundle structure and metadata + python -m monai.bundle verify_bundle --bundle_path + + # all the checks, including network data shape and TorchScript export + python -m monai.bundle verify_bundle --bundle_path --mode full --device cpu + + Args: + bundle_path: root directory of the bundle to verify. Default to ``os.getcwd()``. + mode: "min" or "full", see above. Default to "min". + net_id: ID name of the network component in the config. Default to "network_def". + config_file: filepath of the inference config. Default to ``configs/inference.json`` + (or ``.yaml``/``.yml``) under `bundle_path`. + ckpt_file: filepath of the model checkpoint. Default to ``models/model.pt`` under `bundle_path`. + schema_file: filepath to store the downloaded metadata schema. If the file already exists, it is + reused and not downloaded again. Default to a file in a temporary directory. + check_preferred_files: whether ``models/model.pt`` and the inference config are required. + Default to True. "full" mode needs the inference config regardless, and the checkpoint + unless `check_torchscript` is False. + check_net_io: whether to verify the network input and output in "full" mode. Default to True. + Set it to False for networks whose input or output cannot be described by ``network_data_format``. + check_torchscript: whether to verify the TorchScript export in "full" mode. Default to True. + Set it to False for networks that do not support TorchScript. + download_large: whether to download the files listed in ``large_files.json`` + (or ``.yaml``/``.yml``) under `bundle_path` before verifying, see :py:func:`download_large_files`. + Default to False. + device: target device to run the network checks of "full" mode. + If None, prefer to "cuda" if existing. + args_file: a JSON or YAML file to provide default values for all the args in this function, + so that the command line inputs can be simplified. + + Raises: + ValueError: when `mode` is not supported or the bundle content is invalid. + FileNotFoundError: when a required file of the bundle is missing. + + """ + _args = update_kwargs( + args=args_file, + bundle_path=bundle_path, + mode=mode, + net_id=net_id, + config_file=config_file, + ckpt_file=ckpt_file, + schema_file=schema_file, + check_preferred_files=check_preferred_files, + check_net_io=check_net_io, + check_torchscript=check_torchscript, + download_large=download_large, + device=device, + ) + _log_input_summary(tag="verify_bundle", args=_args) + ( + bundle_path_, + mode_, + net_id_, + config_file_, + ckpt_file_, + schema_file_, + check_preferred_files_, + check_net_io_, + check_torchscript_, + download_large_, + device_, + ) = _pop_args( + _args, + bundle_path=os.getcwd(), + mode="min", + net_id="network_def", + config_file=None, + ckpt_file=None, + schema_file=None, + check_preferred_files=True, + check_net_io=True, + check_torchscript=True, + download_large=False, + device="cuda:0" if is_available() else "cpu", + ) + if mode_ not in ("min", "full"): + raise ValueError(f"unsupported mode `{mode_}`, available options are 'min' and 'full'.") + bundle_root = Path(bundle_path_) + if not bundle_root.is_dir(): + raise FileNotFoundError(f"bundle directory `{bundle_root}` does not exist.") + + if download_large_ and _find_bundle_file(bundle_root, "large_files") is not None: + download_large_files(bundle_path=str(bundle_root)) + + _verify_bundle_files(bundle_root, check_preferred_files=check_preferred_files_) + meta_file = bundle_root / "configs" / "metadata.json" + _verify_bundle_version(meta_file) + + with tempfile.TemporaryDirectory() as tempdir: + schema_path = Path(tempdir) / "schema.json" if schema_file_ is None else Path(schema_file_) + verify_metadata(meta_file=str(meta_file), filepath=str(schema_path)) + if mode_ == "min": + logger.info(f"bundle `{bundle_root}` is verified with no error (mode: min).") + return + + if config_file_ is None: + found = _find_bundle_file(bundle_root / "configs", "inference") + if found is None: + raise FileNotFoundError(f"cannot find `configs/inference.json` (or .yaml/.yml) in `{bundle_root}`.") + config_file_ = str(found) + ckpt_file_ = str(bundle_root / "models" / "model.pt") if ckpt_file_ is None else ckpt_file_ + + # make custom code shipped with the bundle importable, restore `sys.path` afterwards + sys.path.insert(0, str(bundle_root)) + try: + # `bundle_root` is set so that references such as "$@bundle_root + '/models'" resolve to this bundle + if check_net_io_: + verify_net_in_out( + net_id=net_id_, + meta_file=str(meta_file), + config_file=config_file_, + device=device_, + bundle_root=str(bundle_root), + ) + else: + logger.info("skip verifying the network input and output.") + if check_torchscript_: + ts_file = Path(tempdir) / "verify_model.ts" + ckpt_export( + net_id=net_id_, + filepath=str(ts_file), + ckpt_file=ckpt_file_, + meta_file=str(meta_file), + config_file=config_file_, + bundle_root=str(bundle_root), + ) + torch.jit.load(str(ts_file)) + existing_ts = bundle_root / "models" / "model.ts" + if existing_ts.is_file(): + torch.jit.load(str(existing_ts)) + else: + logger.info("skip verifying the TorchScript export.") + finally: + sys.path.remove(str(bundle_root)) + logger.info(f"bundle `{bundle_root}` is verified with no error (mode: full).") + + def _export( converter: Callable, saver: Callable, @@ -1307,11 +1526,13 @@ def _export( """ net = parser.get_parsed_content(net_id) + # map to CPU so that checkpoints saved on GPU can be exported on CPU-only machines, + # the weights are then copied to the device of `net` + ckpt = torch.load(ckpt_file, map_location="cpu", weights_only=True) if has_ignite: # here we use ignite Checkpoint to support nested weights and be compatible with MONAI CheckpointSaver - Checkpoint.load_objects(to_load={key_in_ckpt: net}, checkpoint=ckpt_file) + Checkpoint.load_objects(to_load={key_in_ckpt: net}, checkpoint=ckpt) else: - ckpt = torch.load(ckpt_file, weights_only=True) copy_model_state(dst=net, src=ckpt if key_in_ckpt == "" else ckpt[key_in_ckpt]) # Use the given converter to convert a model and save with metadata, config content diff --git a/tests/bundle/test_bundle_verify_bundle.py b/tests/bundle/test_bundle_verify_bundle.py new file mode 100644 index 00000000000..cf04557a45e --- /dev/null +++ b/tests/bundle/test_bundle_verify_bundle.py @@ -0,0 +1,164 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import json +import os +import shutil +import sys +import tempfile +import unittest +from pathlib import Path + +import torch + +from monai.bundle import ConfigParser, verify_bundle +from tests.test_utils import command_line_tests, download_url_or_skip_test, skip_if_windows, testing_data_config + +TESTS_DIR = Path(__file__).parents[1] +TESTING_DATA = TESTS_DIR / "testing_data" +SCHEMA_FILE = TESTING_DATA / "schema.json" + + +class TestVerifyBundle(unittest.TestCase): + def setUp(self): + self.config = testing_data_config("configs", "test_meta_file") + self.tempdir = tempfile.mkdtemp() + self.bundle = Path(self.tempdir) / "test_bundle" + (self.bundle / "configs").mkdir(parents=True) + (self.bundle / "models").mkdir() + shutil.copy(TESTING_DATA / "metadata.json", self.bundle / "configs" / "metadata.json") + shutil.copy(TESTING_DATA / "inference.json", self.bundle / "configs" / "inference.json") + (self.bundle / "LICENSE").write_text("test license") + parser = ConfigParser() + parser.read_config(str(self.bundle / "configs" / "inference.json")) + torch.save(parser.get_parsed_content("network_def").state_dict(), self.bundle / "models" / "model.pt") + + def tearDown(self): + shutil.rmtree(self.tempdir, ignore_errors=True) + for name in [m for m in sys.modules if m == "scripts" or m.startswith("scripts.")]: + sys.modules.pop(name) + + def _download_schema(self): + download_url_or_skip_test( + url=self.config["url"], + filepath=SCHEMA_FILE, + hash_val=self.config.get("hash_val"), + hash_type=self.config.get("hash_type", "sha256"), + ) + + def _update_metadata(self, **kwargs): + meta_file = self.bundle / "configs" / "metadata.json" + metadata = json.loads(meta_file.read_text()) + metadata.update(kwargs) + meta_file.write_text(json.dumps(metadata)) + + def test_min(self): + self._download_schema() + verify_bundle(bundle_path=str(self.bundle), schema_file=str(SCHEMA_FILE)) + self.assertEqual(sorted(os.listdir(self.bundle)), ["LICENSE", "configs", "models"]) # bundle is unchanged + + def test_full(self): + self._download_schema() + verify_bundle(bundle_path=str(self.bundle), mode="full", schema_file=str(SCHEMA_FILE), device="cpu") + self.assertEqual(os.listdir(self.bundle / "models"), ["model.pt"]) # the test export is not kept + + def test_full_with_custom_code(self): + self._download_schema() + # a bundle network defined in the bundle's own `scripts` package + (self.bundle / "scripts").mkdir() + (self.bundle / "scripts" / "__init__.py").write_text("") + (self.bundle / "scripts" / "net.py").write_text( + "from monai.networks.nets import UNet\n\n\nclass CustomUNet(UNet):\n pass\n" + ) + config_path = self.bundle / "configs" / "inference.json" + config = json.loads(config_path.read_text()) + config["network_def"]["_target_"] = "scripts.net.CustomUNet" + config_path.write_text(json.dumps(config)) + + sys_path = list(sys.path) + verify_bundle(bundle_path=str(self.bundle), mode="full", schema_file=str(SCHEMA_FILE), device="cpu") + self.assertEqual(sys.path, sys_path) # `sys.path` is restored + + def test_skip_net_io(self): + self._download_schema() + # the network outputs 2 channels, so verifying the input and output fails with this metadata + meta_file = self.bundle / "configs" / "metadata.json" + metadata = json.loads(meta_file.read_text()) + metadata["network_data_format"]["outputs"]["pred"]["num_channels"] = 3 + meta_file.write_text(json.dumps(metadata)) + kwargs = {"bundle_path": str(self.bundle), "mode": "full", "schema_file": str(SCHEMA_FILE), "device": "cpu"} + with self.assertRaisesRegex(ValueError, "channel"): + verify_bundle(**kwargs) + verify_bundle(check_net_io=False, **kwargs) + + def test_skip_torchscript(self): + self._download_schema() + # without a checkpoint, the TorchScript export fails + (self.bundle / "models" / "model.pt").unlink() + kwargs = {"bundle_path": str(self.bundle), "mode": "full", "schema_file": str(SCHEMA_FILE), "device": "cpu"} + with self.assertRaises(FileNotFoundError): + verify_bundle(check_preferred_files=False, **kwargs) + verify_bundle(check_preferred_files=False, check_torchscript=False, **kwargs) + + @skip_if_windows + def test_cli(self): + self._download_schema() + cmd = ["coverage", "run", "-m", "monai.bundle", "verify_bundle", "--bundle_path", str(self.bundle)] + cmd += ["--mode", "full", "--schema_file", str(SCHEMA_FILE), "--device", "cpu"] + command_line_tests(cmd) + + def test_missing_license(self): + (self.bundle / "LICENSE").unlink() + with self.assertRaisesRegex(FileNotFoundError, "LICENSE"): + verify_bundle(bundle_path=str(self.bundle)) + + def test_missing_checkpoint(self): + (self.bundle / "models" / "model.pt").unlink() + with self.assertRaisesRegex(FileNotFoundError, "model.pt"): + verify_bundle(bundle_path=str(self.bundle)) + + def test_missing_inference_config(self): + (self.bundle / "configs" / "inference.json").unlink() + with self.assertRaisesRegex(FileNotFoundError, "inference"): + verify_bundle(bundle_path=str(self.bundle)) + + def test_skip_preferred_files(self): + self._download_schema() + (self.bundle / "models" / "model.pt").unlink() + (self.bundle / "configs" / "inference.json").unlink() + verify_bundle(bundle_path=str(self.bundle), schema_file=str(SCHEMA_FILE), check_preferred_files=False) + + def test_version_not_in_changelog(self): + self._update_metadata(version="9.9.9") + with self.assertRaisesRegex(ValueError, "9.9.9"): + verify_bundle(bundle_path=str(self.bundle)) + + def test_missing_changelog(self): + meta_file = self.bundle / "configs" / "metadata.json" + metadata = json.loads(meta_file.read_text()) + metadata.pop("changelog") + meta_file.write_text(json.dumps(metadata)) + with self.assertRaisesRegex(ValueError, "changelog"): + verify_bundle(bundle_path=str(self.bundle)) + + def test_invalid_mode(self): + with self.assertRaisesRegex(ValueError, "mode"): + verify_bundle(bundle_path=str(self.bundle), mode="regular") + + def test_missing_bundle_dir(self): + with self.assertRaises(FileNotFoundError): + verify_bundle(bundle_path=str(self.bundle / "not_exist")) + + +if __name__ == "__main__": + unittest.main() From 7bebc8cc18332bad840de662d703c791f1c65ae6 Mon Sep 17 00:00:00 2001 From: Willy1118 <132340162+Willy1118@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:50:33 +0800 Subject: [PATCH 2/4] Address review: verify checkpoint, keep bundle and sys.modules clean - Check that the checkpoint matches the network with a strict `load_state_dict`, so a wrong checkpoint is reported even without ignite. - Do not write bytecode into the bundle in "full" mode. - Remove the modules imported from the bundle afterwards, so bundles with packages of the same name can be verified in one process. - Load TorchScript files with `map_location="cpu"`. Assisted-by: Claude Code Signed-off-by: Willy1118 <132340162+Willy1118@users.noreply.github.com> --- monai/bundle/scripts.py | 48 +++++++++++-- tests/bundle/test_bundle_verify_bundle.py | 82 ++++++++++++++++++++--- 2 files changed, 116 insertions(+), 14 deletions(-) diff --git a/monai/bundle/scripts.py b/monai/bundle/scripts.py index bc72117e7d4..36d789ce7a9 100644 --- a/monai/bundle/scripts.py +++ b/monai/bundle/scripts.py @@ -1313,6 +1313,30 @@ def _verify_bundle_version(meta_file: Path) -> None: raise ValueError(f"version `{version}` is missing in the `changelog` of `{meta_file}`.") +def _verify_bundle_checkpoint(net_id: str, ckpt_file: str, meta_file: str, config_file: str, bundle_root: str) -> None: + """Check that the checkpoint provides exactly the weights of the network, with matching names and shapes.""" + parser = ConfigParser() + parser.read_config(f=config_file) + parser.read_meta(f=meta_file) + parser["bundle_root"] = bundle_root + net = parser.get_parsed_content(net_id) + ckpt = torch.load(ckpt_file, map_location="cpu", weights_only=True) + try: + net.load_state_dict(ckpt, strict=True) + except (RuntimeError, TypeError) as e: + raise ValueError(f"checkpoint `{ckpt_file}` does not match the weights of network `{net_id}`.") from e + logger.info("checkpoint matches the network with no error.") + + +def _remove_modules_under(path: PathLike) -> None: + """Remove the modules imported from files under `path` from ``sys.modules``.""" + root = os.path.normcase(os.path.realpath(path)) + os.sep + for name, module in list(sys.modules.items()): + file = getattr(module, "__file__", None) + if file and os.path.normcase(os.path.realpath(file)).startswith(root): + sys.modules.pop(name, None) + + def verify_bundle( bundle_path: PathLike | None = None, mode: str | None = None, @@ -1343,13 +1367,16 @@ def verify_bundle( - the metadata is valid against the schema referenced by its ``schema`` field, see :py:func:`verify_metadata`. - "full" mode only: + - if the checkpoint exists, its weights match the network exactly (names and shapes). - the network input and output match the ``network_data_format`` of the metadata, see :py:func:`verify_net_in_out`. Skipped if `check_net_io` is False. - the checkpoint can be exported to TorchScript and loaded back, see :py:func:`ckpt_export`. If ``models/model.ts`` exists, it is also loaded. Skipped if `check_torchscript` is False. In "full" mode, `bundle_path` is temporarily added to ``sys.path`` so that custom code shipped with - the bundle (for example, ``"$import scripts"`` in the config) can be imported. + the bundle (for example, ``"$import scripts"`` in the config) can be imported. No bytecode is written + into the bundle, and the modules imported from the bundle are removed from ``sys.modules`` afterwards, + so that several bundles with packages of the same name can be verified in one process. Typical usage examples: @@ -1458,9 +1485,20 @@ def verify_bundle( config_file_ = str(found) ckpt_file_ = str(bundle_root / "models" / "model.pt") if ckpt_file_ is None else ckpt_file_ - # make custom code shipped with the bundle importable, restore `sys.path` afterwards + # make custom code shipped with the bundle importable without writing bytecode into the bundle, + # restore `sys.path`, the bytecode flag and the imported modules afterwards sys.path.insert(0, str(bundle_root)) + dont_write_bytecode = sys.dont_write_bytecode + sys.dont_write_bytecode = True try: + if Path(ckpt_file_).is_file(): + _verify_bundle_checkpoint( + net_id=net_id_, + ckpt_file=ckpt_file_, + meta_file=str(meta_file), + config_file=config_file_, + bundle_root=str(bundle_root), + ) # `bundle_root` is set so that references such as "$@bundle_root + '/models'" resolve to this bundle if check_net_io_: verify_net_in_out( @@ -1482,14 +1520,16 @@ def verify_bundle( config_file=config_file_, bundle_root=str(bundle_root), ) - torch.jit.load(str(ts_file)) + torch.jit.load(str(ts_file), map_location="cpu") existing_ts = bundle_root / "models" / "model.ts" if existing_ts.is_file(): - torch.jit.load(str(existing_ts)) + torch.jit.load(str(existing_ts), map_location="cpu") else: logger.info("skip verifying the TorchScript export.") finally: sys.path.remove(str(bundle_root)) + sys.dont_write_bytecode = dont_write_bytecode + _remove_modules_under(bundle_root) logger.info(f"bundle `{bundle_root}` is verified with no error (mode: full).") diff --git a/tests/bundle/test_bundle_verify_bundle.py b/tests/bundle/test_bundle_verify_bundle.py index cf04557a45e..c67bb65d4e4 100644 --- a/tests/bundle/test_bundle_verify_bundle.py +++ b/tests/bundle/test_bundle_verify_bundle.py @@ -18,10 +18,11 @@ import tempfile import unittest from pathlib import Path +from unittest import mock import torch -from monai.bundle import ConfigParser, verify_bundle +from monai.bundle import ConfigParser, ckpt_export, verify_bundle from tests.test_utils import command_line_tests, download_url_or_skip_test, skip_if_windows, testing_data_config TESTS_DIR = Path(__file__).parents[1] @@ -72,22 +73,83 @@ def test_full(self): verify_bundle(bundle_path=str(self.bundle), mode="full", schema_file=str(SCHEMA_FILE), device="cpu") self.assertEqual(os.listdir(self.bundle / "models"), ["model.pt"]) # the test export is not kept - def test_full_with_custom_code(self): - self._download_schema() - # a bundle network defined in the bundle's own `scripts` package - (self.bundle / "scripts").mkdir() - (self.bundle / "scripts" / "__init__.py").write_text("") - (self.bundle / "scripts" / "net.py").write_text( - "from monai.networks.nets import UNet\n\n\nclass CustomUNet(UNet):\n pass\n" + def _make_custom_bundle(self, name: str, out_channels: int) -> Path: + """Copy the test bundle to `name`, with a network defined in the bundle's own `scripts` package.""" + bundle = Path(self.tempdir) / name + shutil.copytree(self.bundle, bundle) + (bundle / "scripts").mkdir() + (bundle / "scripts" / "__init__.py").write_text("") + (bundle / "scripts" / "net.py").write_text( + "from monai.networks.nets import UNet\n\n\n" + "class CustomUNet(UNet):\n" + " def __init__(self, **kwargs):\n" + f" kwargs['out_channels'] = {out_channels}\n" + " super().__init__(**kwargs)\n" ) - config_path = self.bundle / "configs" / "inference.json" + config_path = bundle / "configs" / "inference.json" config = json.loads(config_path.read_text()) config["network_def"]["_target_"] = "scripts.net.CustomUNet" config_path.write_text(json.dumps(config)) + # save a checkpoint matching the custom network, without leaving it imported or cached + sys.path.insert(0, str(bundle)) + dont_write_bytecode, sys.dont_write_bytecode = sys.dont_write_bytecode, True + try: + parser = ConfigParser() + parser.read_config(str(config_path)) + torch.save(parser.get_parsed_content("network_def").state_dict(), bundle / "models" / "model.pt") + finally: + sys.path.remove(str(bundle)) + sys.dont_write_bytecode = dont_write_bytecode + for module in [m for m in sys.modules if m == "scripts" or m.startswith("scripts.")]: + sys.modules.pop(module) + return bundle + def test_full_with_custom_code(self): + self._download_schema() + bundle = self._make_custom_bundle("custom_bundle", out_channels=2) sys_path = list(sys.path) - verify_bundle(bundle_path=str(self.bundle), mode="full", schema_file=str(SCHEMA_FILE), device="cpu") + verify_bundle(bundle_path=str(bundle), mode="full", schema_file=str(SCHEMA_FILE), device="cpu") self.assertEqual(sys.path, sys_path) # `sys.path` is restored + self.assertNotIn("scripts", sys.modules) # the bundle's modules are not kept + self.assertEqual(list(bundle.rglob("__pycache__")), []) # no bytecode is written into the bundle + + def test_bundles_with_same_package_name(self): + self._download_schema() + # both bundles have a `scripts` package, only the first one matches the 2 output channels of the metadata + bundle_ok = self._make_custom_bundle("bundle_ok", out_channels=2) + bundle_bad = self._make_custom_bundle("bundle_bad", out_channels=3) + kwargs = {"mode": "full", "schema_file": str(SCHEMA_FILE), "device": "cpu"} + verify_bundle(bundle_path=str(bundle_ok), **kwargs) + # the second bundle must be verified with its own `scripts`, not the one imported for the first bundle + with self.assertRaisesRegex(ValueError, "channel"): + verify_bundle(bundle_path=str(bundle_bad), **kwargs) + + def test_wrong_checkpoint(self): + self._download_schema() + torch.save({"unrelated.weight": torch.zeros(3)}, self.bundle / "models" / "model.pt") + kwargs = {"bundle_path": str(self.bundle), "mode": "full", "schema_file": str(SCHEMA_FILE), "device": "cpu"} + with self.assertRaisesRegex(ValueError, "does not match"): + verify_bundle(**kwargs) + # also when the TorchScript export, which loads the checkpoint differently, is skipped + with self.assertRaisesRegex(ValueError, "does not match"): + verify_bundle(check_torchscript=False, **kwargs) + + def test_torchscript_loaded_on_cpu(self): + self._download_schema() + # export a TorchScript model into the bundle, then check every `torch.jit.load` maps it to CPU + ckpt_export( + net_id="network_def", + filepath=str(self.bundle / "models" / "model.ts"), + ckpt_file=str(self.bundle / "models" / "model.pt"), + meta_file=str(self.bundle / "configs" / "metadata.json"), + config_file=str(self.bundle / "configs" / "inference.json"), + bundle_root=str(self.bundle), + ) + with mock.patch("torch.jit.load", wraps=torch.jit.load) as jit_load: + verify_bundle(bundle_path=str(self.bundle), mode="full", schema_file=str(SCHEMA_FILE), device="cpu") + self.assertEqual(jit_load.call_count, 2) # the test export and `models/model.ts` + for call in jit_load.call_args_list: + self.assertEqual(call.kwargs.get("map_location"), "cpu") def test_skip_net_io(self): self._download_schema() From 2f7a91591acde1bf4ffe0e2e1df768e8144958ce Mon Sep 17 00:00:00 2001 From: Willy1118 <132340162+Willy1118@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:41:32 +0800 Subject: [PATCH 3/4] Isolate the bundle's modules from existing modules of the same name - Take the modules whose top-level name is provided by the bundle out of `sys.modules` while verifying, so the bundle's own code is imported instead of a cached module of the same name, and put them back after. - Move the `sys.path`, bytecode and module handling into a context manager. Assisted-by: Claude Code Signed-off-by: Willy1118 <132340162+Willy1118@users.noreply.github.com> --- monai/bundle/scripts.py | 59 ++++++++++++++++++----- tests/bundle/test_bundle_verify_bundle.py | 18 +++++++ 2 files changed, 64 insertions(+), 13 deletions(-) diff --git a/monai/bundle/scripts.py b/monai/bundle/scripts.py index 36d789ce7a9..68f170a8f4e 100644 --- a/monai/bundle/scripts.py +++ b/monai/bundle/scripts.py @@ -12,6 +12,7 @@ from __future__ import annotations import ast +import importlib import json import os import re @@ -19,7 +20,8 @@ import tempfile import urllib import warnings -from collections.abc import Callable, Mapping, Sequence +from collections.abc import Callable, Iterator, Mapping, Sequence +from contextlib import contextmanager from functools import partial from pathlib import Path from pydoc import locate @@ -1337,6 +1339,44 @@ def _remove_modules_under(path: PathLike) -> None: sys.modules.pop(name, None) +@contextmanager +def _bundle_import_context(bundle_root: Path) -> Iterator[None]: + """ + Make the custom code shipped with the bundle importable, isolated from the modules of the process. + + `bundle_root` is added to ``sys.path`` and no bytecode is written into the bundle. The modules whose + top-level name is provided by the bundle (for example ``scripts``) are taken out of ``sys.modules``, + so that the bundle's own code is imported instead of a cached module of the same name. + Afterwards, ``sys.path`` and the bytecode flag are restored, the modules imported from the bundle + are removed, and the modules taken out are put back. + """ + names = set() + for item in bundle_root.iterdir(): + name = item.stem if item.is_file() and item.suffix == ".py" else item.name if item.is_dir() else "" + if name.isidentifier(): + names.add(name) + + def _from_bundle(module_name: str) -> bool: + return module_name.partition(".")[0] in names + + saved_modules = {k: v for k, v in sys.modules.items() if _from_bundle(k)} + for k in saved_modules: + sys.modules.pop(k) + sys.path.insert(0, str(bundle_root)) + dont_write_bytecode = sys.dont_write_bytecode + sys.dont_write_bytecode = True + importlib.invalidate_caches() + try: + yield + finally: + sys.path.remove(str(bundle_root)) + sys.dont_write_bytecode = dont_write_bytecode + for k in [k for k in sys.modules if _from_bundle(k)]: + sys.modules.pop(k) + _remove_modules_under(bundle_root) + sys.modules.update(saved_modules) + + def verify_bundle( bundle_path: PathLike | None = None, mode: str | None = None, @@ -1375,8 +1415,9 @@ def verify_bundle( In "full" mode, `bundle_path` is temporarily added to ``sys.path`` so that custom code shipped with the bundle (for example, ``"$import scripts"`` in the config) can be imported. No bytecode is written - into the bundle, and the modules imported from the bundle are removed from ``sys.modules`` afterwards, - so that several bundles with packages of the same name can be verified in one process. + into the bundle. The bundle's code is imported in isolation: modules of the same name already in + ``sys.modules`` are not used and are restored afterwards, and the modules imported from the bundle + are removed, so that several bundles with packages of the same name can be verified in one process. Typical usage examples: @@ -1485,12 +1526,8 @@ def verify_bundle( config_file_ = str(found) ckpt_file_ = str(bundle_root / "models" / "model.pt") if ckpt_file_ is None else ckpt_file_ - # make custom code shipped with the bundle importable without writing bytecode into the bundle, - # restore `sys.path`, the bytecode flag and the imported modules afterwards - sys.path.insert(0, str(bundle_root)) - dont_write_bytecode = sys.dont_write_bytecode - sys.dont_write_bytecode = True - try: + # make custom code shipped with the bundle importable, isolated from the modules of the process + with _bundle_import_context(bundle_root): if Path(ckpt_file_).is_file(): _verify_bundle_checkpoint( net_id=net_id_, @@ -1526,10 +1563,6 @@ def verify_bundle( torch.jit.load(str(existing_ts), map_location="cpu") else: logger.info("skip verifying the TorchScript export.") - finally: - sys.path.remove(str(bundle_root)) - sys.dont_write_bytecode = dont_write_bytecode - _remove_modules_under(bundle_root) logger.info(f"bundle `{bundle_root}` is verified with no error (mode: full).") diff --git a/tests/bundle/test_bundle_verify_bundle.py b/tests/bundle/test_bundle_verify_bundle.py index c67bb65d4e4..60529d9ca2c 100644 --- a/tests/bundle/test_bundle_verify_bundle.py +++ b/tests/bundle/test_bundle_verify_bundle.py @@ -124,6 +124,24 @@ def test_bundles_with_same_package_name(self): with self.assertRaisesRegex(ValueError, "channel"): verify_bundle(bundle_path=str(bundle_bad), **kwargs) + def test_existing_module_with_same_name(self): + self._download_schema() + bundle_ok = self._make_custom_bundle("bundle_ok", out_channels=2) + bundle_bad = self._make_custom_bundle("bundle_bad", out_channels=3) + # a `scripts` package that does not match the metadata is already imported before verifying + sys.path.insert(0, str(bundle_bad)) + try: + import scripts.net as existing_net + finally: + sys.path.remove(str(bundle_bad)) + existing_modules = {k: v for k, v in sys.modules.items() if k == "scripts" or k.startswith("scripts.")} + # the bundle must be verified with its own `scripts`, and the existing modules are kept afterwards + verify_bundle(bundle_path=str(bundle_ok), mode="full", schema_file=str(SCHEMA_FILE), device="cpu") + self.assertIs(sys.modules["scripts.net"], existing_net) + self.assertEqual( + {k: v for k, v in sys.modules.items() if k == "scripts" or k.startswith("scripts.")}, existing_modules + ) + def test_wrong_checkpoint(self): self._download_schema() torch.save({"unrelated.weight": torch.zeros(3)}, self.bundle / "models" / "model.pt") From 8319afbe0ec23b31b7aabb811a31978479023cf8 Mon Sep 17 00:00:00 2001 From: Willy1118 <132340162+Willy1118@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:59:08 +0800 Subject: [PATCH 4/4] Restore the modules imported from the bundle before verifying - Keep the modules that were imported from the bundle's files before the verification, for example when the bundle itself is imported as a package, and put them back after the cleanup. Assisted-by: Claude Code Signed-off-by: Willy1118 <132340162+Willy1118@users.noreply.github.com> --- monai/bundle/scripts.py | 23 ++++++++++++++--------- tests/bundle/test_bundle_verify_bundle.py | 20 ++++++++++++++++++++ 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/monai/bundle/scripts.py b/monai/bundle/scripts.py index 68f170a8f4e..bc0eddeec54 100644 --- a/monai/bundle/scripts.py +++ b/monai/bundle/scripts.py @@ -1330,13 +1330,15 @@ def _verify_bundle_checkpoint(net_id: str, ckpt_file: str, meta_file: str, confi logger.info("checkpoint matches the network with no error.") -def _remove_modules_under(path: PathLike) -> None: - """Remove the modules imported from files under `path` from ``sys.modules``.""" +def _modules_under(path: PathLike) -> dict[str, Any]: + """Return the modules in ``sys.modules`` imported from files under `path`.""" root = os.path.normcase(os.path.realpath(path)) + os.sep + modules = {} for name, module in list(sys.modules.items()): file = getattr(module, "__file__", None) if file and os.path.normcase(os.path.realpath(file)).startswith(root): - sys.modules.pop(name, None) + modules[name] = module + return modules @contextmanager @@ -1348,7 +1350,8 @@ def _bundle_import_context(bundle_root: Path) -> Iterator[None]: top-level name is provided by the bundle (for example ``scripts``) are taken out of ``sys.modules``, so that the bundle's own code is imported instead of a cached module of the same name. Afterwards, ``sys.path`` and the bytecode flag are restored, the modules imported from the bundle - are removed, and the modules taken out are put back. + are removed, and the modules that existed before (including the ones imported from files of the + bundle under another name, for example when the bundle itself is imported as a package) are put back. """ names = set() for item in bundle_root.iterdir(): @@ -1359,9 +1362,12 @@ def _bundle_import_context(bundle_root: Path) -> Iterator[None]: def _from_bundle(module_name: str) -> bool: return module_name.partition(".")[0] in names - saved_modules = {k: v for k, v in sys.modules.items() if _from_bundle(k)} - for k in saved_modules: + # the modules imported from the bundle's files before are kept, the shadowing ones are taken out + saved_modules = _modules_under(bundle_root) + shadowing_modules = {k: v for k, v in sys.modules.items() if _from_bundle(k)} + for k in shadowing_modules: sys.modules.pop(k) + saved_modules.update(shadowing_modules) sys.path.insert(0, str(bundle_root)) dont_write_bytecode = sys.dont_write_bytecode sys.dont_write_bytecode = True @@ -1371,9 +1377,8 @@ def _from_bundle(module_name: str) -> bool: finally: sys.path.remove(str(bundle_root)) sys.dont_write_bytecode = dont_write_bytecode - for k in [k for k in sys.modules if _from_bundle(k)]: - sys.modules.pop(k) - _remove_modules_under(bundle_root) + for k in [k for k in sys.modules if _from_bundle(k)] + list(_modules_under(bundle_root)): + sys.modules.pop(k, None) sys.modules.update(saved_modules) diff --git a/tests/bundle/test_bundle_verify_bundle.py b/tests/bundle/test_bundle_verify_bundle.py index 60529d9ca2c..299548a4d99 100644 --- a/tests/bundle/test_bundle_verify_bundle.py +++ b/tests/bundle/test_bundle_verify_bundle.py @@ -142,6 +142,26 @@ def test_existing_module_with_same_name(self): {k: v for k, v in sys.modules.items() if k == "scripts" or k.startswith("scripts.")}, existing_modules ) + def test_bundle_imported_as_package(self): + self._download_schema() + bundle = self._make_custom_bundle("my_bundle", out_channels=2) + (bundle / "__init__.py").write_text("") + # the bundle itself is already imported as a package before verifying + sys.path.insert(0, self.tempdir) + try: + import my_bundle + import my_bundle.scripts.net as bundle_net + finally: + sys.path.remove(self.tempdir) + try: + verify_bundle(bundle_path=str(bundle), mode="full", schema_file=str(SCHEMA_FILE), device="cpu") + # the original module instances are kept + self.assertIs(sys.modules["my_bundle"], my_bundle) + self.assertIs(sys.modules["my_bundle.scripts.net"], bundle_net) + finally: + for name in [m for m in sys.modules if m == "my_bundle" or m.startswith("my_bundle.")]: + sys.modules.pop(name) + def test_wrong_checkpoint(self): self._download_schema() torch.save({"unrelated.weight": torch.zeros(3)}, self.bundle / "models" / "model.pt")