Skip to content
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

5852 fixes partial callable config parser #5854

Merged
merged 4 commits into from
Jan 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion monai/bundle/config_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ def resolve_module_name(self):
config = dict(self.get_config())
target = config.get("_target_")
if not isinstance(target, str):
raise ValueError("must provide a string for the `_target_` of component to instantiate.")
return target # for feature discussed in project-monai/monai#5852

module = self.locator.get_component_module_name(target)
if module is None:
Expand Down
8 changes: 3 additions & 5 deletions monai/utils/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from collections.abc import Callable, Collection, Hashable, Mapping
from functools import partial, wraps
from importlib import import_module
from inspect import isclass, isfunction, ismethod
from inspect import isclass
from pkgutil import walk_packages
from pydoc import locate
from re import match
Expand Down Expand Up @@ -226,8 +226,7 @@ def instantiate(path: str, **kwargs):
for `partial` function.

"""

component = locate(path)
component = locate(path) if isinstance(path, str) else path
if component is None:
raise ModuleNotFoundError(f"Cannot locate class or function path: '{path}'.")
try:
Expand All @@ -241,8 +240,7 @@ def instantiate(path: str, **kwargs):
pdb.set_trace()
if isclass(component):
return component(**kwargs)
# support regular function, static method and class method
if isfunction(component) or (ismethod(component) and isclass(getattr(component, "__self__", None))):
if callable(component): # support regular function, static method and class method
return partial(component, **kwargs)
except Exception as e:
raise RuntimeError(f"Failed to instantiate '{path}' with kwargs: {kwargs}") from e
Expand Down
2 changes: 1 addition & 1 deletion requirements-min.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Requirements for minimal tests
-r requirements.txt
setuptools>=50.3.0,!=60.0.0,!=60.6.0
setuptools>=50.3.0,!=66.0.0,!=60.6.0
coverage>=5.5
parameterized
12 changes: 12 additions & 0 deletions tests/test_config_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,14 @@ def test_lambda_reference(self):
result = trans(np.ones(64))
self.assertTupleEqual(result.shape, (1, 8, 8))

def test_non_str_target(self):
configs = {
"fwd": {"_target_": "$@model().forward", "x": "$torch.rand(1, 3, 256, 256)"},
"model": {"_target_": "monai.networks.nets.resnet.resnet18", "pretrained": False, "spatial_dims": 2},
}
self.assertTrue(callable(ConfigParser(config=configs).fwd))
self.assertTupleEqual(tuple(ConfigParser(config=configs).fwd().shape), (1, 400))

def test_error_instance(self):
config = {"transform": {"_target_": "Compose", "transforms_wrong_key": []}}
parser = ConfigParser(config=config)
Expand All @@ -274,6 +282,10 @@ def test_get_via_attributes(self):
result = trans(np.ones(64))
self.assertTupleEqual(result.shape, (1, 8, 8))

def test_builtin(self):
config = {"import statements": "$import math", "calc": {"_target_": "math.isclose", "a": 0.001, "b": 0.001}}
self.assertEqual(ConfigParser(config).calc(), True)


if __name__ == "__main__":
unittest.main()