Repository navigation
Keep argument boundaries when building Auto3DSeg commands #9234
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
garciadias
wants to merge
16
commits into
Project-MONAI:dev
Choose a base branch
from
garciadias:fix/auto3dseg-cmd-argv
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
ba56a6d
Move test_image_filter.py
garciadias 5216b7a
Merge remote-tracking branch 'origin/dev' into dev
garciadias eacd783
Merge remote-tracking branch 'origin/dev' into dev
garciadias c64825f
Merge remote-tracking branch 'upstream/dev' into dev
garciadias 66b6c17
Merge remote-tracking branch 'origin/dev' into dev
garciadias 19cab57
Merge remote-tracking branch 'upstream/dev' into dev
garciadias df6db69
Merge remote-tracking branch 'upstream/dev' into dev
garciadias 432d979
Keep argument boundaries when building Auto3DSeg commands
garciadias d65679c
Build the expected train.py path with os.path.join in the test
garciadias d6e6e37
Merge a restored device_setting into the current defaults
garciadias 473ed4c
Merge branch 'dev' into fix/auto3dseg-cmd-argv
ericspod 1e70ebe
Merge branch 'dev' into fix/auto3dseg-cmd-argv
ericspod 947b033
Validate BundleAlgo state keys without a constructed instance
garciadias fb77255
Keep device_setting consistent when restoring a partial state
garciadias d9b5c54
Merge remote-tracking branch 'origin/dev' into fix/auto3dseg-cmd-argv
garciadias 0722cec
DCO Remediation Commit for R. Garcia-Dias <rafaelagd@gmail.com>
garciadias File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| # 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 shlex | ||
| import unittest | ||
| from unittest import mock | ||
|
|
||
| from monai.apps.auto3dseg.bundle_gen import BundleAlgo | ||
| from monai.apps.auto3dseg.ensemble_builder import EnsembleRunner | ||
| from monai.auto3dseg.utils import _prepare_cmd_default, _run_cmd_torchrun, check_and_set_optional_args | ||
|
|
||
|
|
||
| def _device_setting(n_devices: int = 1) -> dict: | ||
| return { | ||
| "CUDA_VISIBLE_DEVICES": ",".join(str(i) for i in range(n_devices)), | ||
| "n_devices": n_devices, | ||
| "NUM_NODES": 1, | ||
| "MN_START_METHOD": "bcprun", | ||
| "CMD_PREFIX": "", | ||
| } | ||
|
|
||
|
|
||
| class TestOptionalArgs(unittest.TestCase): | ||
| def test_plain_values_keep_their_tokens(self): | ||
| """Values without special characters produce the same arguments as before.""" | ||
| cmd = _prepare_cmd_default("train.py run", num_epochs=2, lr=0.1, config_file=["a.yaml", "b.yaml"]) | ||
| self.assertEqual( | ||
| shlex.split(cmd), | ||
| ["python", "train.py", "run", "--num_epochs=2", "--lr=0.1", "--config_file='a.yaml,b.yaml'"], | ||
| ) | ||
|
|
||
| def test_value_with_whitespace_is_one_argument(self): | ||
| for value in ("/data/my dir", "/tmp/x\t--work_dir\t/other", "a b --c=d"): | ||
| with self.subTest(value=value): | ||
| args = shlex.split(check_and_set_optional_args({"work_dir": value})) | ||
| self.assertEqual(args, [f"--work_dir={value}"]) | ||
|
|
||
| def test_torchrun_keeps_argument_boundaries(self): | ||
| cmd = "train.py run" + check_and_set_optional_args({"output_dir": "/tmp/a b"}) | ||
| with mock.patch("monai.auto3dseg.utils.run_cmd") as run: | ||
| _run_cmd_torchrun(cmd, nnodes=1, nproc_per_node=2) | ||
| self.assertEqual( | ||
| run.call_args.args[0], | ||
| ["torchrun", "--nnodes", "1", "--nproc_per_node", "2", "train.py", "run", "--output_dir=/tmp/a b"], | ||
| ) | ||
|
|
||
|
|
||
| class TestEnsembleRunnerCommand(unittest.TestCase): | ||
| def _runner(self, work_dir: str, **kwargs) -> EnsembleRunner: | ||
| runner = EnsembleRunner.__new__(EnsembleRunner) | ||
| runner.data_src_cfg_name = "input.yaml" | ||
| runner.work_dir = work_dir | ||
| runner.num_fold = 5 | ||
| runner.ensemble_method_name = "AlgoEnsembleBestByFold" | ||
| runner.kwargs = kwargs | ||
| runner.device_setting = _device_setting(n_devices=2) | ||
| return runner | ||
|
|
||
| def test_values_stay_single_arguments(self): | ||
| work_dir = "/tmp/my work\t--work_dir\t/elsewhere" | ||
| runner = self._runner(work_dir, sigmoid="True --output_dir=/elsewhere") | ||
| with mock.patch("monai.apps.auto3dseg.ensemble_builder._run_cmd_torchrun") as run: | ||
| runner._create_cmd() | ||
| args = shlex.split(run.call_args.args[0]) | ||
| self.assertEqual(args[args.index("--work_dir") + 1], work_dir) | ||
| self.assertEqual(args.count("--work_dir"), 1) | ||
| self.assertIn("--sigmoid=True --output_dir=/elsewhere", args) | ||
| self.assertFalse(any(a.startswith("--output_dir") for a in args)) | ||
|
|
||
|
|
||
| class TestBundleAlgoCommand(unittest.TestCase): | ||
| def test_output_path_with_whitespace_is_one_argument(self): | ||
| algo = BundleAlgo(template_path=None) | ||
| algo.output_path = "/tmp/my algo" | ||
| algo.device_setting = _device_setting(n_devices=1) | ||
| with mock.patch("monai.apps.auto3dseg.bundle_gen.run_cmd") as run: | ||
| algo.train({"num_epochs": 1}) | ||
| args = run.call_args.args[0] | ||
| self.assertEqual(args[:3], ["python", "/tmp/my algo/scripts/train.py", "run"]) | ||
| self.assertIn("--num_epochs=1", args) | ||
|
|
||
|
|
||
| class TestBundleAlgoLoadState(unittest.TestCase): | ||
| def test_round_trip(self): | ||
| algo = BundleAlgo(template_path="/templates") | ||
| algo.name = "segresnet_0" | ||
| algo.device_setting = _device_setting(n_devices=2) | ||
| state = algo.state_dict() | ||
| restored = BundleAlgo() | ||
| restored.load_state_dict(state) | ||
| self.assertEqual(restored.state_dict(), state) | ||
|
|
||
| def test_unknown_key_is_rejected(self): | ||
| with self.assertRaisesRegex(ValueError, "Unexpected keys"): | ||
| BundleAlgo().load_state_dict({"train": "x"}) | ||
|
|
||
| def test_malformed_device_setting_is_rejected(self): | ||
| for setting in ( | ||
| {"n_devices": "2 --master_port 1"}, | ||
| {"NUM_NODES": "1 2"}, | ||
| {"CUDA_VISIBLE_DEVICES": "0 --x"}, | ||
| {"CMD_PREFIX": ["python"]}, | ||
| {"OTHER": 1}, | ||
| "not a dict", | ||
| ): | ||
| with self.subTest(setting=setting): | ||
| with self.assertRaises(ValueError): | ||
| BundleAlgo().load_state_dict({"device_setting": setting}) | ||
|
|
||
| def test_numeric_strings_are_converted(self): | ||
| algo = BundleAlgo() | ||
| algo.load_state_dict({"device_setting": {"n_devices": "2", "NUM_NODES": "1", "CUDA_VISIBLE_DEVICES": "0,1"}}) | ||
| self.assertEqual(algo.device_setting["n_devices"], 2) | ||
| self.assertEqual(algo.device_setting["NUM_NODES"], 1) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.