Find all modules of a certain class (or union of classes) that are direct or indirect descendants of other modules of a certain class (or union of classes). Returns all matching modules, along with the parent of those moduless and the names they are referenced by.
(
model,
ancestor_class: Optional[Set[str]] = None,
search_class: List[Type[nn.Module]] = [nn.Linear],
exclude_children_of: Optional[List[Type[nn.Module]]] = [
LoRACompatibleLinear,
LoRACompatibleConv,
LoRALinearLayer,
LoRAConv2dLayer,
],
)
| 232 | |
| 233 | |
| 234 | def _find_modules_v2( |
| 235 | model, |
| 236 | ancestor_class: Optional[Set[str]] = None, |
| 237 | search_class: List[Type[nn.Module]] = [nn.Linear], |
| 238 | exclude_children_of: Optional[List[Type[nn.Module]]] = [ |
| 239 | LoRACompatibleLinear, |
| 240 | LoRACompatibleConv, |
| 241 | LoRALinearLayer, |
| 242 | LoRAConv2dLayer, |
| 243 | ], |
| 244 | ): |
| 245 | """ |
| 246 | Find all modules of a certain class (or union of classes) that are direct or |
| 247 | indirect descendants of other modules of a certain class (or union of classes). |
| 248 | |
| 249 | Returns all matching modules, along with the parent of those moduless and the |
| 250 | names they are referenced by. |
| 251 | """ |
| 252 | |
| 253 | # Get the targets we should replace all linears under |
| 254 | if ancestor_class is not None: |
| 255 | ancestors = (module for module in model.modules() if module.__class__.__name__ in ancestor_class) |
| 256 | else: |
| 257 | # this, incase you want to naively iterate over all modules. |
| 258 | ancestors = [module for module in model.modules()] |
| 259 | |
| 260 | # For each target find every linear_class module that isn't a child of a LoraInjectedLinear |
| 261 | for ancestor in ancestors: |
| 262 | for fullname, module in ancestor.named_modules(): |
| 263 | if any([isinstance(module, _class) for _class in search_class]): |
| 264 | # Find the direct parent if this is a descendant, not a child, of target |
| 265 | *path, name = fullname.split(".") |
| 266 | parent = ancestor |
| 267 | flag = False |
| 268 | while path: |
| 269 | try: |
| 270 | parent = parent.get_submodule(path.pop(0)) |
| 271 | except: |
| 272 | flag = True |
| 273 | break |
| 274 | if flag: |
| 275 | continue |
| 276 | # Skip this linear if it's a child of a LoraInjectedLinear |
| 277 | if exclude_children_of and any([isinstance(parent, _class) for _class in exclude_children_of]): |
| 278 | continue |
| 279 | # Otherwise, yield it |
| 280 | yield parent, name, module |
| 281 | |
| 282 | |
| 283 | _find_modules = _find_modules_v2 |
nothing calls this directly
no outgoing calls
no test coverage detected