-
Notifications
You must be signed in to change notification settings - Fork 6.1k
First Block Cache #11180
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
First Block Cache #11180
Changes from all commits
Commits
Show all changes
33 commits
Select commit
Hold shift + click to select a range
406b106
update
a-r-r-o-w dd69b41
modify flux single blocks to make compatible with cache techniques (w…
a-r-r-o-w 7ab424a
remove debug logs
a-r-r-o-w d71fe55
update
a-r-r-o-w 2557238
cache context for different batches of data
a-r-r-o-w 0e232ac
fix hs residual bug for single return outputs; support ltx
a-r-r-o-w 41b0c47
fix controlnet flux
a-r-r-o-w 1f33ca2
support flux, ltx i2v, ltx condition
a-r-r-o-w 315e357
Merge branch 'main' into integrations/first-block-cache-2
a-r-r-o-w c76e1cc
update
a-r-r-o-w 46619ea
update
a-r-r-o-w ff5f2ee
Update docs/source/en/api/cache.md
a-r-r-o-w aa8e328
Merge branch 'main' into integrations/first-block-cache-2
a-r-r-o-w ca715a9
Update src/diffusers/hooks/hooks.py
a-r-r-o-w 701cf86
Merge branch 'main' into integrations/first-block-cache-2
a-r-r-o-w 3dde07a
address review comments pt. 1
a-r-r-o-w f731664
address review comments pt. 2
a-r-r-o-w 169bb0d
cache context refacotr; address review pt. 3
a-r-r-o-w 38a6039
Merge branch 'main' into integrations/first-block-cache-2
a-r-r-o-w 1f3e02f
Merge branch 'main' into integrations/first-block-cache-2
a-r-r-o-w 2ed59c1
Merge branch 'main' into integrations/first-block-cache-2
a-r-r-o-w 0a44380
address review comments
a-r-r-o-w fb229b5
metadata registration with decorators instead of centralized
a-r-r-o-w 82fa9df
Merge branch 'main' into integrations/first-block-cache-2
a-r-r-o-w 367fdef
support cogvideox
a-r-r-o-w 495fddb
support mochi
a-r-r-o-w 153cf0c
fix
a-r-r-o-w a5fe2bd
remove unused function
a-r-r-o-w b8317da
remove central registry based on review
a-r-r-o-w 5ac3d64
Merge branch 'main' into integrations/first-block-cache-2
a-r-r-o-w ad6322a
Merge branch 'main' into integrations/first-block-cache-2
a-r-r-o-w 9189815
update
a-r-r-o-w 4a7556e
Merge branch 'main' into integrations/first-block-cache-2
a-r-r-o-w File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
# Copyright 2024 The HuggingFace Team. All rights reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
from ..models.attention_processor import Attention, MochiAttention | ||
|
||
|
||
_ATTENTION_CLASSES = (Attention, MochiAttention) | ||
|
||
_SPATIAL_TRANSFORMER_BLOCK_IDENTIFIERS = ("blocks", "transformer_blocks", "single_transformer_blocks", "layers") | ||
_TEMPORAL_TRANSFORMER_BLOCK_IDENTIFIERS = ("temporal_transformer_blocks",) | ||
_CROSS_TRANSFORMER_BLOCK_IDENTIFIERS = ("blocks", "transformer_blocks", "layers") | ||
|
||
_ALL_TRANSFORMER_BLOCK_IDENTIFIERS = tuple( | ||
{ | ||
*_SPATIAL_TRANSFORMER_BLOCK_IDENTIFIERS, | ||
*_TEMPORAL_TRANSFORMER_BLOCK_IDENTIFIERS, | ||
*_CROSS_TRANSFORMER_BLOCK_IDENTIFIERS, | ||
} | ||
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,264 @@ | ||
# Copyright 2025 The HuggingFace Team. All rights reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import inspect | ||
from dataclasses import dataclass | ||
from typing import Any, Callable, Dict, Type | ||
|
||
|
||
@dataclass | ||
class AttentionProcessorMetadata: | ||
skip_processor_output_fn: Callable[[Any], Any] | ||
|
||
|
||
@dataclass | ||
class TransformerBlockMetadata: | ||
return_hidden_states_index: int = None | ||
return_encoder_hidden_states_index: int = None | ||
|
||
_cls: Type = None | ||
_cached_parameter_indices: Dict[str, int] = None | ||
|
||
def _get_parameter_from_args_kwargs(self, identifier: str, args=(), kwargs=None): | ||
kwargs = kwargs or {} | ||
if identifier in kwargs: | ||
return kwargs[identifier] | ||
if self._cached_parameter_indices is not None: | ||
return args[self._cached_parameter_indices[identifier]] | ||
if self._cls is None: | ||
raise ValueError("Model class is not set for metadata.") | ||
parameters = list(inspect.signature(self._cls.forward).parameters.keys()) | ||
parameters = parameters[1:] # skip `self` | ||
self._cached_parameter_indices = {param: i for i, param in enumerate(parameters)} | ||
if identifier not in self._cached_parameter_indices: | ||
raise ValueError(f"Parameter '{identifier}' not found in function signature but was requested.") | ||
index = self._cached_parameter_indices[identifier] | ||
if index >= len(args): | ||
raise ValueError(f"Expected {index} arguments but got {len(args)}.") | ||
return args[index] | ||
|
||
|
||
class AttentionProcessorRegistry: | ||
_registry = {} | ||
# TODO(aryan): this is only required for the time being because we need to do the registrations | ||
# for classes. If we do it eagerly, i.e. call the functions in global scope, we will get circular | ||
# import errors because of the models imported in this file. | ||
_is_registered = False | ||
|
||
@classmethod | ||
def register(cls, model_class: Type, metadata: AttentionProcessorMetadata): | ||
cls._register() | ||
cls._registry[model_class] = metadata | ||
|
||
@classmethod | ||
def get(cls, model_class: Type) -> AttentionProcessorMetadata: | ||
cls._register() | ||
if model_class not in cls._registry: | ||
raise ValueError(f"Model class {model_class} not registered.") | ||
return cls._registry[model_class] | ||
|
||
@classmethod | ||
def _register(cls): | ||
if cls._is_registered: | ||
return | ||
cls._is_registered = True | ||
_register_attention_processors_metadata() | ||
|
||
|
||
class TransformerBlockRegistry: | ||
_registry = {} | ||
# TODO(aryan): this is only required for the time being because we need to do the registrations | ||
# for classes. If we do it eagerly, i.e. call the functions in global scope, we will get circular | ||
# import errors because of the models imported in this file. | ||
_is_registered = False | ||
|
||
@classmethod | ||
def register(cls, model_class: Type, metadata: TransformerBlockMetadata): | ||
cls._register() | ||
metadata._cls = model_class | ||
cls._registry[model_class] = metadata | ||
|
||
@classmethod | ||
def get(cls, model_class: Type) -> TransformerBlockMetadata: | ||
cls._register() | ||
if model_class not in cls._registry: | ||
raise ValueError(f"Model class {model_class} not registered.") | ||
return cls._registry[model_class] | ||
|
||
@classmethod | ||
def _register(cls): | ||
if cls._is_registered: | ||
return | ||
cls._is_registered = True | ||
_register_transformer_blocks_metadata() | ||
|
||
|
||
def _register_attention_processors_metadata(): | ||
from ..models.attention_processor import AttnProcessor2_0 | ||
from ..models.transformers.transformer_cogview4 import CogView4AttnProcessor | ||
|
||
# AttnProcessor2_0 | ||
AttentionProcessorRegistry.register( | ||
model_class=AttnProcessor2_0, | ||
metadata=AttentionProcessorMetadata( | ||
skip_processor_output_fn=_skip_proc_output_fn_Attention_AttnProcessor2_0, | ||
), | ||
) | ||
|
||
# CogView4AttnProcessor | ||
AttentionProcessorRegistry.register( | ||
model_class=CogView4AttnProcessor, | ||
metadata=AttentionProcessorMetadata( | ||
skip_processor_output_fn=_skip_proc_output_fn_Attention_CogView4AttnProcessor, | ||
), | ||
) | ||
|
||
|
||
def _register_transformer_blocks_metadata(): | ||
a-r-r-o-w marked this conversation as resolved.
Show resolved
Hide resolved
|
||
from ..models.attention import BasicTransformerBlock | ||
from ..models.transformers.cogvideox_transformer_3d import CogVideoXBlock | ||
from ..models.transformers.transformer_cogview4 import CogView4TransformerBlock | ||
from ..models.transformers.transformer_flux import FluxSingleTransformerBlock, FluxTransformerBlock | ||
from ..models.transformers.transformer_hunyuan_video import ( | ||
HunyuanVideoSingleTransformerBlock, | ||
HunyuanVideoTokenReplaceSingleTransformerBlock, | ||
HunyuanVideoTokenReplaceTransformerBlock, | ||
HunyuanVideoTransformerBlock, | ||
) | ||
from ..models.transformers.transformer_ltx import LTXVideoTransformerBlock | ||
from ..models.transformers.transformer_mochi import MochiTransformerBlock | ||
from ..models.transformers.transformer_wan import WanTransformerBlock | ||
|
||
# BasicTransformerBlock | ||
TransformerBlockRegistry.register( | ||
model_class=BasicTransformerBlock, | ||
metadata=TransformerBlockMetadata( | ||
return_hidden_states_index=0, | ||
return_encoder_hidden_states_index=None, | ||
), | ||
) | ||
|
||
# CogVideoX | ||
TransformerBlockRegistry.register( | ||
model_class=CogVideoXBlock, | ||
metadata=TransformerBlockMetadata( | ||
return_hidden_states_index=0, | ||
return_encoder_hidden_states_index=1, | ||
), | ||
) | ||
|
||
# CogView4 | ||
TransformerBlockRegistry.register( | ||
model_class=CogView4TransformerBlock, | ||
metadata=TransformerBlockMetadata( | ||
return_hidden_states_index=0, | ||
return_encoder_hidden_states_index=1, | ||
), | ||
) | ||
|
||
# Flux | ||
TransformerBlockRegistry.register( | ||
model_class=FluxTransformerBlock, | ||
metadata=TransformerBlockMetadata( | ||
return_hidden_states_index=1, | ||
return_encoder_hidden_states_index=0, | ||
), | ||
) | ||
TransformerBlockRegistry.register( | ||
model_class=FluxSingleTransformerBlock, | ||
metadata=TransformerBlockMetadata( | ||
return_hidden_states_index=1, | ||
return_encoder_hidden_states_index=0, | ||
), | ||
) | ||
|
||
# HunyuanVideo | ||
TransformerBlockRegistry.register( | ||
model_class=HunyuanVideoTransformerBlock, | ||
metadata=TransformerBlockMetadata( | ||
return_hidden_states_index=0, | ||
return_encoder_hidden_states_index=1, | ||
), | ||
) | ||
TransformerBlockRegistry.register( | ||
model_class=HunyuanVideoSingleTransformerBlock, | ||
metadata=TransformerBlockMetadata( | ||
return_hidden_states_index=0, | ||
return_encoder_hidden_states_index=1, | ||
), | ||
) | ||
TransformerBlockRegistry.register( | ||
model_class=HunyuanVideoTokenReplaceTransformerBlock, | ||
metadata=TransformerBlockMetadata( | ||
return_hidden_states_index=0, | ||
return_encoder_hidden_states_index=1, | ||
), | ||
) | ||
TransformerBlockRegistry.register( | ||
model_class=HunyuanVideoTokenReplaceSingleTransformerBlock, | ||
metadata=TransformerBlockMetadata( | ||
return_hidden_states_index=0, | ||
return_encoder_hidden_states_index=1, | ||
), | ||
) | ||
|
||
# LTXVideo | ||
TransformerBlockRegistry.register( | ||
model_class=LTXVideoTransformerBlock, | ||
metadata=TransformerBlockMetadata( | ||
return_hidden_states_index=0, | ||
return_encoder_hidden_states_index=None, | ||
), | ||
) | ||
|
||
# Mochi | ||
TransformerBlockRegistry.register( | ||
model_class=MochiTransformerBlock, | ||
metadata=TransformerBlockMetadata( | ||
return_hidden_states_index=0, | ||
return_encoder_hidden_states_index=1, | ||
), | ||
) | ||
|
||
# Wan | ||
TransformerBlockRegistry.register( | ||
model_class=WanTransformerBlock, | ||
metadata=TransformerBlockMetadata( | ||
return_hidden_states_index=0, | ||
return_encoder_hidden_states_index=None, | ||
), | ||
) | ||
|
||
|
||
# fmt: off | ||
def _skip_attention___ret___hidden_states(self, *args, **kwargs): | ||
a-r-r-o-w marked this conversation as resolved.
Show resolved
Hide resolved
|
||
hidden_states = kwargs.get("hidden_states", None) | ||
if hidden_states is None and len(args) > 0: | ||
hidden_states = args[0] | ||
return hidden_states | ||
|
||
|
||
def _skip_attention___ret___hidden_states___encoder_hidden_states(self, *args, **kwargs): | ||
hidden_states = kwargs.get("hidden_states", None) | ||
encoder_hidden_states = kwargs.get("encoder_hidden_states", None) | ||
if hidden_states is None and len(args) > 0: | ||
hidden_states = args[0] | ||
if encoder_hidden_states is None and len(args) > 1: | ||
encoder_hidden_states = args[1] | ||
return hidden_states, encoder_hidden_states | ||
|
||
|
||
_skip_proc_output_fn_Attention_AttnProcessor2_0 = _skip_attention___ret___hidden_states | ||
_skip_proc_output_fn_Attention_CogView4AttnProcessor = _skip_attention___ret___hidden_states___encoder_hidden_states | ||
# fmt: on |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.