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

Method new_forward

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

Source from the content-addressed store, hash-verified

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:
229 logger.debug(f"MagCache: Skipping step {state.step_index}")
230 # Apply MagCache: Output = Input + Previous Residual
231
232 output = hidden_states
233 res = state.previous_residual
234
235 if res.device != output.device:
236 res = res.to(output.device)
237
238 # Attempt to apply residual handling shape mismatches (e.g., text+image vs image only)
239 if res.shape == output.shape:
240 output = output + res
241 elif (
242 output.ndim == 3

Callers

nothing calls this directly

Calls 4

set_contextMethod · 0.80
get_stateMethod · 0.45
toMethod · 0.45

Tested by

no test coverage detected