Recursively replaces all instances of `target_class` in `model` with `custom_class`. Args: model (torch.nn.Module): The root module to search within. target_class (type): The class to be replaced. custom_class (type): The class to replace with. strict (bool)
(
model: torch.nn.Module,
target_class: torch.nn.Module,
custom_class: torch.nn.Module,
strict: bool = False,
extra_custom_kwargs: Optional[Dict] = None,
)
| 21 | |
| 22 | |
| 23 | def replace_module_with_custom_class( |
| 24 | model: torch.nn.Module, |
| 25 | target_class: torch.nn.Module, |
| 26 | custom_class: torch.nn.Module, |
| 27 | strict: bool = False, |
| 28 | extra_custom_kwargs: Optional[Dict] = None, |
| 29 | ): |
| 30 | """ |
| 31 | Recursively replaces all instances of `target_class` in `model` with `custom_class`. |
| 32 | |
| 33 | Args: |
| 34 | model (torch.nn.Module): The root module to search within. |
| 35 | target_class (type): The class to be replaced. |
| 36 | custom_class (type): The class to replace with. |
| 37 | strict (bool): Whether to strictly enforce that the keys in `state_dict` match the model. |
| 38 | extra_custom_kwargs: Extra keyword arguments to override or extend the constructor args. |
| 39 | |
| 40 | Example: |
| 41 | >>> class MyDecoder(Decoder): |
| 42 | ... def __init__(self, ...) |
| 43 | ... super().__init__() |
| 44 | ... freqs_cos, freqs_sin = precompute_freqs_cis(...) |
| 45 | ... self.register_buffer("freqs_cos", freqs_cos) |
| 46 | ... self.register_buffer("freqs_sin", freqs_sin) |
| 47 | ... |
| 48 | ... def forward(self, x): |
| 49 | ... .... |
| 50 | >>> model = Decoder() |
| 51 | >>> replace_module_with_custom_class(model, Decoder, MyDecoder) |
| 52 | """ |
| 53 | |
| 54 | def extract_init_args_from_instance(instance): |
| 55 | init_signature = inspect.signature(instance.__init__) |
| 56 | init_params = [ |
| 57 | param |
| 58 | for param in init_signature.parameters.values() |
| 59 | if param.name != "self" |
| 60 | ] |
| 61 | |
| 62 | extracted_args = {} |
| 63 | for param in init_params: |
| 64 | name = param.name |
| 65 | if hasattr(instance, name): |
| 66 | extracted_args[name] = getattr(instance, name) |
| 67 | elif param.default is not inspect.Parameter.empty: |
| 68 | extracted_args[name] = param.default |
| 69 | |
| 70 | return extracted_args |
| 71 | |
| 72 | if extra_custom_kwargs is None: |
| 73 | extra_custom_kwargs = {} |
| 74 | |
| 75 | for name, child in model.named_children(): |
| 76 | if isinstance(child, target_class): |
| 77 | state_dict = child.state_dict() |
| 78 | |
| 79 | original_args = extract_init_args_from_instance(child) |
| 80 | new_module = custom_class(**{**original_args, **extra_custom_kwargs}) |
no test coverage detected