| 1 | # Copyright 2025 the LlamaFactory team. |
| 2 | # |
| 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | # you may not use this file except in compliance with the License. |
| 5 | # You may obtain a copy of the License at |
| 6 | # |
| 7 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | # |
| 9 | # Unless required by applicable law or agreed to in writing, software |
| 10 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | # See the License for the specific language governing permissions and |
| 13 | # limitations under the License. |
| 14 | |
| 15 | from enum import Enum |
| 16 | from typing import TYPE_CHECKING |
| 17 | |
| 18 | from transformers.utils import is_flash_attn_2_available, is_torch_sdpa_available |
| 19 | |
| 20 | from ..framework import logging |
| 21 | |
| 22 | if TYPE_CHECKING: |
| 23 | from transformers import PretrainedConfig |
| 24 | |
| 25 | from ..hparams import ModelArguments |
| 26 | |
| 27 | logger = logging.get_logger(__name__) |
| 28 | |
| 29 | |
| 30 | class AttentionFunction(str, Enum): |
| 31 | AUTO = "auto" |
| 32 | DISABLED = "disabled" |
| 33 | SDPA = "sdpa" |
| 34 | FA2 = "fa2" |
| 35 | |
| 36 | |
| 37 | def configure_attn_implementation( |
| 38 | config: "PretrainedConfig", model_args: "ModelArguments" |
| 39 | ) -> None: |
| 40 | if model_args.flash_attn == AttentionFunction.AUTO: |
| 41 | return |
| 42 | |
| 43 | elif model_args.flash_attn == AttentionFunction.DISABLED: |
| 44 | requested_attn_implementation = "eager" |
| 45 | |
| 46 | elif model_args.flash_attn == AttentionFunction.SDPA: |
| 47 | if not is_torch_sdpa_available(): |
| 48 | logger.warning_rank0("torch>=2.1.1 is required for SDPA attention.") |
| 49 | return |
| 50 | |
| 51 | requested_attn_implementation = "sdpa" |
| 52 | elif model_args.flash_attn == AttentionFunction.FA2: |
| 53 | if not is_flash_attn_2_available(): |
| 54 | logger.warning_rank0("FlashAttention-2 is not installed.") |
| 55 | return |
| 56 | |
| 57 | requested_attn_implementation = "flash_attention_2" |
| 58 | else: |
| 59 | raise NotImplementedError(f"Unknown attention type: {model_args.flash_attn}") |
| 60 | |
| 61 | setattr(config, "_attn_implementation", requested_attn_implementation) |