-
Notifications
You must be signed in to change notification settings - Fork 61
Add static FP8 attention support #1045
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
Changes from all commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
46749f0
add attention quant
yiliu30 f743ffb
add ut
yiliu30 a81b514
add llama patch
yiliu30 157f6d1
correct fp8
yiliu30 586462f
add utils
yiliu30 591549b
merge main
yiliu30 65a467e
fix shape
yiliu30 da1fe7f
tmp
yiliu30 4f3b0a3
clean code
yiliu30 ae3a4aa
Merge branch 'main' into quant-attn
yiliu30 ceca38a
add ut
yiliu30 a49c09b
clean
yiliu30 90bf465
Merge branch 'quant-attn' of https://github.com/intel/auto-round into…
yiliu30 adc5cb3
fix
yiliu30 a61bd65
refine
yiliu30 c4bfce0
clean
yiliu30 478eef0
fix
yiliu30 5ed5f72
fix
yiliu30 53f6ae8
fix
yiliu30 741f818
fix
yiliu30 ae6cec5
fix alias tensor
yiliu30 ffa5ac5
fix ut
yiliu30 c7d72d5
Merge branch 'main' into quant-attn
yiliu30 641089d
Merge branch 'main' into quant-attn
yiliu30 61ca489
Merge branch 'main' into quant-attn
yiliu30 b698ec4
update
yiliu30 3b36353
fix
yiliu30 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,190 @@ | ||
| # Copyright (c) 2025 Red Hat AI, vLLM Project and Intel Corporation | ||
yiliu30 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| # | ||
| # 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. | ||
|
|
||
| # NOTICE: The design adapted from: | ||
| # https://github.com/vllm-project/compressed-tensors/pull/491 | ||
|
|
||
|
|
||
| import contextlib | ||
| import inspect | ||
| from functools import partial | ||
| from typing import Callable, Optional | ||
| from weakref import ref | ||
|
|
||
| import torch | ||
| from torch import Tensor | ||
| from torch.nn import Module | ||
| from torch.utils.hooks import RemovableHandle | ||
| from transformers import AttentionInterface, PretrainedConfig, PreTrainedModel | ||
| from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS | ||
|
|
||
| from auto_round.experimental.kv_cache import kvcache_quant_context | ||
| from auto_round.experimental.utils import ( | ||
| is_attention_module, | ||
| per_tensor_fp8_qdq, | ||
| update_parameter_data, | ||
| ) | ||
| from auto_round.utils import logger | ||
|
|
||
| __all__ = [ | ||
| "QuantizedAttentionImpl", | ||
| "initialize_hooked_attention", | ||
| "IMPL_ATTR", | ||
| "attention_quant_ctx", | ||
| ] | ||
|
|
||
|
|
||
| IMPL_ATTR = "impl" | ||
| HOOKED_ATTENTION_NAME = "ct_hooked_attention" | ||
| QUERY_SCALE_NAME = "q_scale" | ||
| QUERY_MAX_NAME = "q_max" | ||
|
|
||
|
|
||
| class QuantizedAttentionImpl(torch.nn.Module): | ||
| """ | ||
| QuantizedAttentionImpl module which wraps the functionality of the original | ||
| attention implementation. Unlike the original attention function, this | ||
| implementation is a `torch.nn.Module` which can be hooked to trigger | ||
| transforms and calibration hooks. | ||
|
|
||
| This module works by being registered as a submodule to attention modules via | ||
| `initialize_hooked_attention`, registering a new attention implementation function | ||
| which calls this module, then setting the model attention implementation to the new | ||
| function. After triggering hooks and quantization, this module calls the original | ||
| attention implementation function. | ||
|
|
||
| :param attn_module: parent attention module | ||
| """ | ||
|
|
||
| _original_impl = "sdpa" | ||
|
|
||
| def __init__(self, config: PretrainedConfig, attn_module: Module): | ||
| super().__init__() | ||
| self.config = config | ||
| self.attn_module = ref(attn_module) # avoid circular references | ||
| # register query max | ||
| device = next(attn_module.parameters()).device | ||
| initial_max = torch.tensor([float("-inf")], device=device) | ||
| update_parameter_data(attn_module, initial_max, QUERY_MAX_NAME) | ||
| initial_scale = torch.tensor([0.0], device=device) | ||
| update_parameter_data(attn_module, initial_scale, QUERY_SCALE_NAME) | ||
|
|
||
| def forward( | ||
| self, | ||
| module: Module, | ||
| query: Tensor, | ||
| key: Tensor, | ||
| value: Tensor, | ||
| *args, | ||
| **kwargs, | ||
| ): | ||
| cur_query_max = query.abs().max() | ||
| query_max = torch.max( | ||
| getattr(module, QUERY_MAX_NAME).data, | ||
| cur_query_max.detach().to(getattr(module, QUERY_MAX_NAME).data.device), | ||
| ) | ||
| update_parameter_data(module, query_max, QUERY_MAX_NAME) | ||
| query, query_scale = per_tensor_fp8_qdq(query, tensor_max=query_max) | ||
| update_parameter_data(module, query_scale.squeeze(0), QUERY_SCALE_NAME) | ||
yiliu30 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| # original attention | ||
| return ALL_ATTENTION_FUNCTIONS[self._original_impl]( | ||
| module, | ||
| query, | ||
| key, | ||
| value, | ||
| *args, | ||
| **kwargs, | ||
| ) | ||
|
|
||
|
|
||
| # ----- initialize ----- # | ||
|
|
||
|
|
||
| def _ct_hooked_attention(module: Module, *args, **kwargs): | ||
| if hasattr(module, IMPL_ATTR): | ||
| return module.impl(module, *args, **kwargs) | ||
| else: | ||
| return ALL_ATTENTION_FUNCTIONS[_original_impl](module, *args, **kwargs) # pylint: disable=E0601 | ||
|
|
||
|
|
||
| def initialize_hooked_attention(module: Module, config): | ||
| """ | ||
| Initialize `QuantizedAttentionImpl` and `QuantizedKVCache` instances | ||
| attached to attention | ||
|
|
||
| :param model: parent model of attention module | ||
| :param module: attention module to initialize with | ||
| """ | ||
| if not hasattr(module, IMPL_ATTR): | ||
| module.register_module(IMPL_ATTR, QuantizedAttentionImpl(config, module)) | ||
| if config._attn_implementation != HOOKED_ATTENTION_NAME: | ||
| # assumes only one model at a time | ||
| global _original_impl | ||
| _original_impl = config._attn_implementation | ||
| # Add new implementation to AttentionInterface(mapping) | ||
| AttentionInterface.register(HOOKED_ATTENTION_NAME, _ct_hooked_attention) | ||
| config._attn_implementation = HOOKED_ATTENTION_NAME | ||
|
|
||
| # initialize_hooked_kv_cache(model, module) | ||
|
|
||
|
|
||
| def prep_attention_module_for_calibration(module: torch.nn.Module, config): | ||
| if is_attention_module(module): | ||
| logger.trace(f"Preparing attention module {module.__class__.__name__} for calibration") | ||
| initialize_hooked_attention(module, config) | ||
|
|
||
|
|
||
| # # ----- hooks ----- # | ||
|
|
||
|
|
||
| # def register_query_hook(module: Module, hook: Callable[[Module, Tensor], Optional[Tensor]]) -> RemovableHandle: | ||
| # """ | ||
| # Register a hook which takes post-rope query states as an argument and | ||
| # returns the modified query states or `None` | ||
|
|
||
| # :param module: attention module to add hook to | ||
| # :param hook: query hook function | ||
| # """ | ||
| # impl = getattr(module, IMPL_ATTR) | ||
|
|
||
| # def _hook(impl: QuantizedAttentionImpl, args, kwargs): | ||
| # bound = inspect.signature(impl.forward).bind(*args, **kwargs) | ||
| # value = hook(module, bound.arguments["query"]) | ||
| # if value is not None: | ||
| # bound.arguments["query"] = value | ||
|
|
||
| # return bound.args, bound.kwargs | ||
yiliu30 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| # return impl.register_forward_pre_hook(_hook, with_kwargs=True) | ||
|
|
||
|
|
||
yiliu30 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| def clean_up_hooked_attention(module, model): | ||
| if is_attention_module(module): | ||
| # Cleanup phase: Restore the original attention implementation | ||
| if hasattr(model.config, "_attn_implementation") and hasattr(model, "_original_impl"): | ||
| model.config._attn_implementation = model._original_impl | ||
| del model._original_impl | ||
|
|
||
|
|
||
| @contextlib.contextmanager | ||
| def attention_quant_ctx(model: PreTrainedModel, static_attention_dtype=torch.float8_e4m3fn): | ||
| try: | ||
| # Setup phase: Initialize hooked attention | ||
| prepare_fn = partial(prep_attention_module_for_calibration, config=model.config) | ||
| model.apply(prepare_fn) | ||
| with kvcache_quant_context(model, static_kv_dtype=static_attention_dtype): | ||
| yield model | ||
| finally: | ||
| clean_fn = partial(clean_up_hooked_attention, model=model) | ||
| model.apply(clean_fn) | ||
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Does __main__.py also need add this parameter?