-
Notifications
You must be signed in to change notification settings - Fork 75
feat: Sage Attention Algorithm #455
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
Open
Marius-Graml
wants to merge
8
commits into
main
Choose a base branch
from
feat/sage-attn
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
7894df2
Add sage attention algorithm to pruna framework by using diffusers at…
0c59782
Add compatibility for sage-attn with torch-compile
c8eda60
Add tests für sage attn algorithm
Marius-Graml 69c9679
Change formatting using ruff
Marius-Graml 03ed96b
Quick commit, add sage_attn2++ as reference paper, add cachers and qu…
Marius-Graml e7414aa
Add target modules including hyperparameter for excluding first and l…
Marius-Graml 16aa7f4
Add doc strings to functions and methods
Marius-Graml b6cb7c2
Refactor sage_attn to use target_modules utilities
Marius-Graml 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
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
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,184 @@ | ||
| # Copyright 2025 - Pruna AI GmbH. 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 __future__ import annotations | ||
|
|
||
| from collections.abc import Iterable | ||
| from typing import Any, List | ||
|
|
||
| import torch | ||
| from diffusers import DiffusionPipeline | ||
|
|
||
| from pruna.algorithms.base.pruna_base import PrunaAlgorithmBase | ||
| from pruna.algorithms.base.tags import AlgorithmTag as tags | ||
| from pruna.config.smash_config import SmashConfigPrefixWrapper | ||
| from pruna.config.target_modules import TARGET_MODULES_TYPE, TargetModules, map_targeted_nn_roots | ||
| from pruna.engine.save import SAVE_FUNCTIONS | ||
| from pruna.logging.logger import pruna_logger | ||
|
|
||
|
|
||
| class SageAttn(PrunaAlgorithmBase): | ||
| """ | ||
| Replace torch.nn.functional.scaled_dot_product_attention with sage_attn. | ||
|
|
||
| SageAttention is a fast and memory-efficient attention mechanism. It applies the flash attention mechanism | ||
| in combination with quantization and smoothing to speed up attention computations. | ||
| """ | ||
|
|
||
| algorithm_name: str = "sage_attn" | ||
| group_tags: list[str] = [tags.KERNEL] | ||
| save_fn = SAVE_FUNCTIONS.reapply | ||
| references: dict[str, str] = { | ||
| "Paper (SA2++)": "https://arxiv.org/pdf/2505.21136v3", | ||
| "GitHub": "https://github.com/thu-ml/SageAttention", | ||
| "Kernel Hub": "https://huggingface.co/kernels-community/sage_attention", | ||
| } | ||
| tokenizer_required: bool = False | ||
| processor_required: bool = False | ||
| runs_on: list[str] = ["cuda", "accelerate"] | ||
| dataset_required: bool = False | ||
| compatible_before: Iterable[str] = [tags.QUANTIZER] | ||
| compatible_after: Iterable[str] = ["torch_compile", tags.CACHER] | ||
|
|
||
| def model_check_fn(self, model: Any) -> bool: | ||
| """ | ||
| Check if the model has an attention mechanism that can be replaced with sage_attn. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| model : Any | ||
| The model to check. | ||
|
|
||
| Returns | ||
| ------- | ||
| bool | ||
| True if the model is a valid model for the algorithm, False otherwise. | ||
| """ | ||
| if not isinstance(model, DiffusionPipeline) or not hasattr(model, "components"): | ||
| return False | ||
|
|
||
| return any( | ||
| hasattr(component, "set_attention_backend") and component.dtype in (torch.bfloat16, torch.float16) | ||
| for component in model.components.values() | ||
| ) | ||
|
|
||
| def _apply(self, model: Any, smash_config: SmashConfigPrefixWrapper) -> Any: | ||
| """ | ||
| Wrap the model to use SageAttention where possible. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| model : Any | ||
| The model to wrap. | ||
| smash_config : SmashConfigPrefixWrapper | ||
| The configuration for the application of the algorithm. | ||
|
|
||
| Returns | ||
| ------- | ||
| Any | ||
| The wrapped model. | ||
| """ | ||
| target_modules = smash_config["target_modules"] | ||
|
|
||
| if target_modules is None: | ||
| target_modules = self.get_model_dependent_hyperparameter_defaults( | ||
| model, | ||
| smash_config | ||
| ) # for consistency, not used yet | ||
|
|
||
| def apply_sage_attn( | ||
| root_name: str | None, | ||
| root_nn_module: torch.nn.Module, | ||
| relative_target_paths: List[str], | ||
| ) -> torch.nn.Module: | ||
| """ | ||
| Apply the SageAttention backend to targeted submodules of a root module. | ||
|
|
||
| For each relative submodule path, this function retrieves the corresponding | ||
| submodule from ``root_nn_module`` and applies | ||
| ``set_attention_backend("sage_hub")`` if the method is available. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| root_name : str or None | ||
| The attribute name of the root module within the model (used for identification). | ||
| May be ``None`` if the model itself is a ``torch.nn.Module``. | ||
| root_nn_module : torch.nn.Module | ||
| The root torch.nn.module containing the targeted submodules. | ||
| relative_target_paths : List[str] | ||
| Relative paths of submodules (with respect to ``root_nn_module``) to consider. | ||
|
|
||
| Returns | ||
| ------- | ||
| torch.nn.Module | ||
| The root ntorch.nn.module with the SageAttention backend applied where supported. | ||
| """ | ||
| for rel_path in relative_target_paths: | ||
| try: | ||
| sub_module = root_nn_module.get_submodule(rel_path) | ||
| except AttributeError: | ||
| # safety net: should not happen, | ||
| # since the paths come from named_modules() | ||
| continue | ||
| if hasattr(sub_module, "set_attention_backend"): | ||
| sub_module.set_attention_backend("sage_hub") | ||
| else: | ||
| pruna_logger.warning(f"Module {root_name}.{rel_path} does not have a set_attention_backend method" | ||
| "and will not be replaced with SageAttention") | ||
| return root_nn_module | ||
|
|
||
| return map_targeted_nn_roots(apply_sage_attn, model, target_modules) | ||
|
|
||
| def get_hyperparameters(self) -> list: | ||
| """ | ||
| Get the list of configurable hyperparameters for this algorithm. | ||
|
|
||
| Returns | ||
| ------- | ||
| list | ||
| A list of hyperparameter objects (e.g., Boolean, TargetModules) used by the | ||
| configuration system. | ||
| """ | ||
| return [ | ||
| TargetModules(name="target_modules", default_value=None), | ||
| ] | ||
|
|
||
| def get_model_dependent_hyperparameter_defaults( | ||
| self, | ||
| model: Any, | ||
| smash_config: SmashConfigPrefixWrapper, | ||
| ) -> TARGET_MODULES_TYPE: | ||
| """ | ||
| Get model-dependent default hyperparameters for this algorithm. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| model : Any | ||
| The model/pipeline instance for which defaults should be computed. | ||
| smash_config : SmashConfigPrefixWrapper | ||
| The configuration wrapper passed to the algorithm. It can be used to read other | ||
| algorithm settings when selecting defaults. | ||
|
|
||
| Returns | ||
| ------- | ||
| TARGET_MODULES_TYPE | ||
| A dictionary with keys "include" and "exclude" defining which modules should be | ||
| targeted by default. | ||
| """ | ||
| # So far, everything is included and nothing is excluded | ||
| # Filtering is done in the _apply method by the set_attention_backend method | ||
| include = ["*"] | ||
| exclude = [] | ||
|
|
||
| return {"include": include, "exclude": exclude} | ||
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,16 @@ | ||
| import pytest | ||
|
|
||
| from pruna.algorithms.sage_attn import SageAttn | ||
|
|
||
| from .base_tester import AlgorithmTesterBase | ||
|
|
||
|
|
||
| @pytest.mark.high | ||
| class TestSageAttn(AlgorithmTesterBase): | ||
| """Test the sage attention kernel.""" | ||
|
|
||
| models = ["flux_tiny", "wan_tiny_random"] | ||
| reject_models = ["opt_tiny_random"] | ||
| allow_pickle_files = False | ||
| algorithm_class = SageAttn | ||
| metrics = ["latency"] |
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.