MCPcopy Create free account
hub / github.com/pytorch/executorch / _replace_modules

Function _replace_modules

backends/mlx/llm/source_transformation.py:32–53  ·  view source on GitHub ↗

Recursively replace all instances of target_type using factory.

(
    module: nn.Module,
    target_type: type,
    factory: Callable[[nn.Module], nn.Module],
    label: str,
)

Source from the content-addressed store, hash-verified

30
31
32def _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
56def replace_et_kv_cache_with_mlx(

Callers 2

Calls 2

_recurseFunction · 0.85
infoMethod · 0.80

Tested by

no test coverage detected