Recursively replace all instances of target_type using factory.
(
module: nn.Module,
target_type: type,
factory: Callable[[nn.Module], nn.Module],
label: str,
)
| 30 | |
| 31 | |
| 32 | def _replace_modules( |
| 33 | module: nn.Module, |
| 34 | target_type: type, |
| 35 | factory: Callable[[nn.Module], nn.Module], |
| 36 | label: str, |
| 37 | ) -> nn.Module: |
| 38 | """Recursively replace all instances of target_type using factory.""" |
| 39 | |
| 40 | def _recurse(parent: nn.Module) -> int: |
| 41 | count = 0 |
| 42 | for name, child in list(parent.named_children()): |
| 43 | if isinstance(child, target_type): |
| 44 | setattr(parent, name, factory(child)) |
| 45 | count += 1 |
| 46 | else: |
| 47 | count += _recurse(child) |
| 48 | return count |
| 49 | |
| 50 | count = _recurse(module) |
| 51 | if count > 0: |
| 52 | logger.info(f"Replaced {count} {label}") |
| 53 | return module |
| 54 | |
| 55 | |
| 56 | def replace_et_kv_cache_with_mlx( |
no test coverage detected