MCPcopy Index your code
hub / github.com/huggingface/diffusers / MagCacheBlockHook

Class MagCacheBlockHook

src/diffusers/hooks/mag_cache.py:287–394  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

285
286
287class MagCacheBlockHook(ModelHook):
288 def __init__(self, state_manager: StateManager, is_tail: bool = False, config: MagCacheConfig = None):
289 super().__init__()
290 self.state_manager = state_manager
291 self.is_tail = is_tail
292 self.config = config
293 self._metadata = None
294
295 def initialize_hook(self, module):
296 unwrapped_module = unwrap_module(module)
297 self._metadata = TransformerBlockRegistry.get(unwrapped_module.__class__)
298 return module
299
300 @torch.compiler.disable
301 def new_forward(self, module: torch.nn.Module, *args, **kwargs):
302 if self.state_manager._current_context is None:
303 self.state_manager.set_context("inference")
304 state: MagCacheState = self.state_manager.get_state()
305
306 if not state.should_compute:
307 arg_name = self._metadata.hidden_states_argument_name
308 hidden_states = self._metadata._get_parameter_from_args_kwargs(arg_name, args, kwargs)
309
310 if self.is_tail:
311 # Still need to advance step index even if we skip
312 self._advance_step(state)
313
314 if self._metadata.return_encoder_hidden_states_index is not None:
315 encoder_hidden_states = self._metadata._get_parameter_from_args_kwargs(
316 "encoder_hidden_states", args, kwargs
317 )
318 max_idx = max(
319 self._metadata.return_hidden_states_index, self._metadata.return_encoder_hidden_states_index
320 )
321 ret_list = [None] * (max_idx + 1)
322 ret_list[self._metadata.return_hidden_states_index] = hidden_states
323 ret_list[self._metadata.return_encoder_hidden_states_index] = encoder_hidden_states
324 return tuple(ret_list)
325
326 return hidden_states
327
328 output = self.fn_ref.original_forward(*args, **kwargs)
329
330 if self.is_tail:
331 # Calculate residual for next steps
332 if isinstance(output, tuple):
333 out_hidden = output[self._metadata.return_hidden_states_index]
334 else:
335 out_hidden = output
336
337 in_hidden = state.head_block_input
338
339 if in_hidden is None:
340 return output
341
342 # Determine residual
343 if out_hidden.shape == in_hidden.shape:
344 residual = out_hidden - in_hidden

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…