attn_implementation 是Hugging Face Transformers库中的一个参数,用于指定注意力机制Attention的具体实现方式。这个参数的主要作用是让用户能够选择不同版本的注意力实现,以优化性能、内存适用活兼容性

代码如下:

model = AutoModelForCausalLM.from_pretrained(
    actor_model_path,
    # device_map={'':device},
    torch_dtype=torch.bfloat16,
    attn_implementation="flash_attention_2",
    use_cache=False)

底层代码:

attn_implementation (`str`, *optional*):
                The attention implementation to use in the model (if relevant). Can be any of `"eager"` (manual implementation of the attention), `"sdpa"` (using [`F.scaled_dot_product_attention`](https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention.html)), or `"flash_attention_2"` (using [Dao-AILab/flash-attention](https://github.com/Dao-AILab/flash-attention)). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual `"eager"` implementation.

参数取值以及含义:
(1)eager  --默认值
使用标准的PyTorch实现
兼容性最好,支持所有模型和硬件
内存效率相对较低
(2)sapa  --Scaled Dot Product Attention
使用 PyTorch 2.0+ 的 F.scaled_dot_product_attention()
更好的性能,支持 flash attention、memory-efficient attention 等
需要 PyTorch 2.0+ 和兼容的硬件
(3)flash_attention_2
使用 FlashAttention-v2 实现
极高的内存效率和计算速度
需要兼容的GPU(如A100、H100等)
显著减少内存占用,支持更长的序列
 

欢迎点赞收藏关注,你的支持是我输出的动力

Logo

中国智能体开发者社区,聚焦智能体与大模型开发,提供前沿资讯、实用工具链、开源项目及行业案例。通过技术沙龙、开发者大赛等活动,促进经验交流与协作,助力开发者快速构建创新智能应用。

更多推荐