Helper function for :py:class:`monai.networks.utils.replace_modules`.
(
parent: torch.nn.Module,
name: str,
new_module: torch.nn.Module,
out: list[tuple[str, torch.nn.Module]],
strict_match: bool = True,
match_device: bool = True,
)
| 1091 | |
| 1092 | |
| 1093 | def _replace_modules( |
| 1094 | parent: torch.nn.Module, |
| 1095 | name: str, |
| 1096 | new_module: torch.nn.Module, |
| 1097 | out: list[tuple[str, torch.nn.Module]], |
| 1098 | strict_match: bool = True, |
| 1099 | match_device: bool = True, |
| 1100 | ) -> None: |
| 1101 | """ |
| 1102 | Helper function for :py:class:`monai.networks.utils.replace_modules`. |
| 1103 | """ |
| 1104 | if match_device: |
| 1105 | devices = list({i.device for i in parent.parameters()}) |
| 1106 | # if only one device for whole of model |
| 1107 | if len(devices) == 1: |
| 1108 | new_module.to(devices[0]) |
| 1109 | idx = name.find(".") |
| 1110 | # if there is "." in name, call recursively |
| 1111 | if idx != -1: |
| 1112 | parent_name = name[:idx] |
| 1113 | parent = getattr(parent, parent_name) |
| 1114 | name = name[idx + 1 :] |
| 1115 | _out: list[tuple[str, torch.nn.Module]] = [] |
| 1116 | _replace_modules(parent, name, new_module, _out) |
| 1117 | # prepend the parent name |
| 1118 | out += [(f"{parent_name}.{r[0]}", r[1]) for r in _out] |
| 1119 | # no "." in module name, do the actual replacing |
| 1120 | else: |
| 1121 | if strict_match: |
| 1122 | old_module = getattr(parent, name) |
| 1123 | setattr(parent, name, new_module) |
| 1124 | out += [(name, old_module)] |
| 1125 | else: |
| 1126 | for mod_name, _ in parent.named_modules(): |
| 1127 | if name in mod_name: |
| 1128 | _replace_modules(parent, mod_name, deepcopy(new_module), out, strict_match=True) |
| 1129 | |
| 1130 | |
| 1131 | def replace_modules( |
no outgoing calls
no test coverage detected
searching dependent graphs…