| 169 | |
| 170 | |
| 171 | class MagCacheHeadHook(ModelHook): |
| 172 | _is_stateful = True |
| 173 | |
| 174 | def __init__(self, state_manager: StateManager, config: MagCacheConfig): |
| 175 | self.state_manager = state_manager |
| 176 | self.config = config |
| 177 | self._metadata = None |
| 178 | |
| 179 | def initialize_hook(self, module): |
| 180 | unwrapped_module = unwrap_module(module) |
| 181 | self._metadata = TransformerBlockRegistry.get(unwrapped_module.__class__) |
| 182 | return module |
| 183 | |
| 184 | @torch.compiler.disable |
| 185 | def new_forward(self, module: torch.nn.Module, *args, **kwargs): |
| 186 | if self.state_manager._current_context is None: |
| 187 | self.state_manager.set_context("inference") |
| 188 | |
| 189 | arg_name = self._metadata.hidden_states_argument_name |
| 190 | hidden_states = self._metadata._get_parameter_from_args_kwargs(arg_name, args, kwargs) |
| 191 | |
| 192 | state: MagCacheState = self.state_manager.get_state() |
| 193 | state.head_block_input = hidden_states |
| 194 | |
| 195 | should_compute = True |
| 196 | |
| 197 | if self.config.calibrate: |
| 198 | # Never skip during calibration |
| 199 | should_compute = True |
| 200 | else: |
| 201 | # MagCache Logic |
| 202 | current_step = state.step_index |
| 203 | if current_step >= len(self.config.mag_ratios): |
| 204 | current_scale = 1.0 |
| 205 | else: |
| 206 | current_scale = self.config.mag_ratios[current_step] |
| 207 | |
| 208 | retention_step = int(self.config.retention_ratio * self.config.num_inference_steps + 0.5) |
| 209 | |
| 210 | if current_step >= retention_step: |
| 211 | state.accumulated_ratio *= current_scale |
| 212 | state.accumulated_steps += 1 |
| 213 | state.accumulated_err += abs(1.0 - state.accumulated_ratio) |
| 214 | |
| 215 | if ( |
| 216 | state.previous_residual is not None |
| 217 | and state.accumulated_err <= self.config.threshold |
| 218 | and state.accumulated_steps <= self.config.max_skip_steps |
| 219 | ): |
| 220 | should_compute = False |
| 221 | else: |
| 222 | state.accumulated_ratio = 1.0 |
| 223 | state.accumulated_steps = 0 |
| 224 | state.accumulated_err = 0.0 |
| 225 | |
| 226 | state.should_compute = should_compute |
| 227 | |
| 228 | if not should_compute: |
no outgoing calls
no test coverage detected
searching dependent graphs…