Applies MagCache to a given module (typically a Transformer). Args: module (`torch.nn.Module`): The module to apply MagCache to. config (`MagCacheConfig`): The configuration for MagCache.
(module: torch.nn.Module, config: MagCacheConfig)
| 395 | |
| 396 | |
| 397 | def apply_mag_cache(module: torch.nn.Module, config: MagCacheConfig) -> None: |
| 398 | """ |
| 399 | Applies MagCache to a given module (typically a Transformer). |
| 400 | |
| 401 | Args: |
| 402 | module (`torch.nn.Module`): |
| 403 | The module to apply MagCache to. |
| 404 | config (`MagCacheConfig`): |
| 405 | The configuration for MagCache. |
| 406 | """ |
| 407 | # Initialize registry on the root module so the Pipeline can set context. |
| 408 | HookRegistry.check_if_exists_or_initialize(module) |
| 409 | |
| 410 | state_manager = StateManager(MagCacheState, (), {}) |
| 411 | remaining_blocks = [] |
| 412 | |
| 413 | for name, submodule in module.named_children(): |
| 414 | if name not in _ALL_TRANSFORMER_BLOCK_IDENTIFIERS or not isinstance(submodule, torch.nn.ModuleList): |
| 415 | continue |
| 416 | for index, block in enumerate(submodule): |
| 417 | remaining_blocks.append((f"{name}.{index}", block)) |
| 418 | |
| 419 | if not remaining_blocks: |
| 420 | logger.warning("MagCache: No transformer blocks found to apply hooks.") |
| 421 | return |
| 422 | |
| 423 | # Handle single-block models |
| 424 | if len(remaining_blocks) == 1: |
| 425 | name, block = remaining_blocks[0] |
| 426 | logger.info(f"MagCache: Applying Head+Tail Hooks to single block '{name}'") |
| 427 | _apply_mag_cache_block_hook(block, state_manager, config, is_tail=True) |
| 428 | _apply_mag_cache_head_hook(block, state_manager, config) |
| 429 | return |
| 430 | |
| 431 | head_block_name, head_block = remaining_blocks.pop(0) |
| 432 | tail_block_name, tail_block = remaining_blocks.pop(-1) |
| 433 | |
| 434 | logger.info(f"MagCache: Applying Head Hook to {head_block_name}") |
| 435 | _apply_mag_cache_head_hook(head_block, state_manager, config) |
| 436 | |
| 437 | for name, block in remaining_blocks: |
| 438 | _apply_mag_cache_block_hook(block, state_manager, config) |
| 439 | |
| 440 | logger.info(f"MagCache: Applying Tail Hook to {tail_block_name}") |
| 441 | _apply_mag_cache_block_hook(tail_block, state_manager, config, is_tail=True) |
| 442 | |
| 443 | |
| 444 | def _apply_mag_cache_head_hook(block: torch.nn.Module, state_manager: StateManager, config: MagCacheConfig) -> None: |
searching dependent graphs…