MCPcopy Create free account
hub / github.com/huggingface/diffusers / new_forward

Method new_forward

src/diffusers/hooks/mag_cache.py:301–361  ·  view source on GitHub ↗
(self, module: torch.nn.Module, *args, **kwargs)

Source from the content-addressed store, hash-verified

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
345 elif out_hidden.ndim == 3 and in_hidden.ndim == 3 and out_hidden.shape[2] == in_hidden.shape[2]:
346 diff = in_hidden.shape[1] - out_hidden.shape[1]
347 if diff == 0:
348 residual = out_hidden - in_hidden
349 else:
350 residual = out_hidden - in_hidden # Fallback to matching tail
351 else:
352 # Fallback for completely mismatched shapes
353 residual = out_hidden
354
355 if self.config.calibrate:
356 self._perform_calibration_step(state, residual)
357
358 state.previous_residual = residual

Callers

nothing calls this directly

Calls 5

_advance_stepMethod · 0.95
set_contextMethod · 0.80
get_stateMethod · 0.45

Tested by

no test coverage detected