如何在ms-swift 微调训练deepseekvl2时使用sageattention

sageattention低比特量化注意力机制,比FlashAttention快5 倍 实现了 5 倍相比于 FlashAttention 的即插即用的推理加速(此前的 SageAttention V1/V2/V2++ 分别达到了 2.1,3,3.9 倍的加速效果),比如在 RTX 5090 上,SageAttention3 达到了 1040 TOPS 的速度,甚至是比 RTX 5090 昂贵十几倍的 H100 上使用 Hopper 独有的 FlashAttention3 还要快 1.65 倍! 阅读详情

        sageattention 据说比flash_atten_2还要快很多。 但是如何在deepseekvl2这训练这里把它用上呢?

        1.本质上sageattention是sdpa,SDPA的全称为Scaled Dot-Product Attention, 属于乘性注意力机制, 简单一句话来说就是,根据Query (Q)与Key之间的匹配度来对Value进行加权,而事实上不管是Query, Key还是Value都来自于输入,因此所谓的SDPA本质上是对输入信息信息进行重组。

       2. sageattention使用了Triton这个包,它可以把python的代码编译成目标机器码,大大加速这个运算的速度。

        3. 从官方例子可以看到,它本质的工作原理就是简单的替换torch.nn.functional.scaled_dot_product_attention这个函数,示例如下:

from sageattention import sageattn
import torch.nn.functional as F
。。。
    F.scaled_dot_product_attention = sageattn

        所以,要用上sageatten,其实只需要原来的模型支持sdpa的注意力机制即可。

        但很不幸,从deepseekvl2官方开源github可以看到DeepseekVLV2ForCausalLM和DeepseekV2ForCausalLM都是不支持sdpa的,这个两个类都没有声明_supports_sdpa = True

ATTENTION_CLASSES = {
    "eager": DeepseekV2Attention,
    "flash_attention_2": DeepseekV2FlashAttention2,

    "mla_eager": DeepseekV2Attention,
    "mla_flash_attention_2": DeepseekV2FlashAttention2,

    "mha_eager": LlamaAttention,
    "mha_flash_attention_2": LlamaFlashAttention2
}

        这个attention_class也没有sdpa的实现。

        因此,deepseekvl2无法直接简单使用sageattion,我们需要改一下deepseek的开源代码,才有可能用上sageattion.

        修改步骤如下:

1. 首先要让DeepseekVLV2ForCausalLM和DeepseekV2ForCausalLM先支持sdpa,添加_supports_sdpa,这样transformers/modeling_utils.py的_check_and_enable_sdpa才可以检查通过.

class DeepseekV2ForCausalLM(DeepseekV2PreTrainedModel):
    _tied_weights_keys = ["lm_head.weight"]
    _supports_sdpa = True
class DeepseekVLV2ForCausalLM(DeepseekVLV2PreTrainedModel):
    _supports_sdpa = True

2.然后在DeepSeek-VL2/deepseek_vl2/models/modeling_deepseek.py添加sdpa的attention的实现类,我们让它继承LlamaAttention,如下,其实这个直接抄的LlamaSdpaAttention,copy是为了修改方便,实现如下:


class DeepSeekSdpaAttention(LlamaAttention):
    """
    Deepseek attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `DeepseekV2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    """

    # Adapted from LlamaAttention.forward
    def forward(
        self,
        hidden_states: torch.Tensor,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_value: Optional[Cache] = None,
        output_attentions: bool = False,
        use_cache: bool = False,
        cache_position: Optional[torch.LongTensor] = None,
        position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,  # will become mandatory in v4.46
        **kwargs,
    ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
        if output_attentions:
            # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
            logger.warning_once(
                "LlamaModel is using LlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
                'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
            )
            return super().forward(
                hidden_states=hidden_states,
                attention_mask=attention_mask,
                position_ids=position_ids,
                past_key_value=past_key_value,
                output_attentions=output_attentions,
                use_cache=use_cache,
                cache_position=cache_position,
                position_embeddings=position_embeddings,
            )

        bsz, q_len, _ = hidden_states.size()

        query_states = self.q_proj(hidden_states)
        key_states = self.k_proj(hidden_states)
        value_states = self.v_proj(hidden_states)

        # use -1 to infer num_heads and num_key_value_heads as they may vary if tensor parallel is used
        query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
        key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
        value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)

        if position_embeddings is None:
            logger.warning_once(
                "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
                "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
                "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
                "removed and `position_embeddings` will be mandatory."
            )
            cos, sin = self.rotary_emb(value_states, position_ids)
        else:
            if isinstance(position_embeddings, torch.Tensor):
                cos, sin = self.rotary_emb(value_states, position_ids)
            else:
                cos, sin = position_embeddings


        query_states, key_states = apply_rotary_pos_emb2(query_states, key_states, cos, sin)

        if past_key_value is not None:
            # sin and cos are specific to RoPE models; cache_position needed for the static cache
            cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
            key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)

        key_states = repeat_kv(key_states, self.num_key_value_groups)
        value_states = repeat_kv(value_states, self.num_key_value_groups)

        causal_mask = attention_mask
        if attention_mask is not None:
            causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]

        # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
        # Reference: https://github.com/pytorch/pytorch/issues/112577.
        if query_states.device.type == "cuda" and causal_mask is not None:
            query_states = query_states.contiguous()
            key_states = key_states.contiguous()
            value_states = value_states.contiguous()

        # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
        # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
        is_causal = True  #if causal_mask is None and q_len > 1 else False

        attn_output = sageattn(
            query_states,
            key_states,
            value_states,
            attn_mask=causal_mask,
            dropout_p=self.attention_dropout if self.training else 0.0,
            is_causal=is_causal,
        )

        attn_output = attn_output.transpose(1, 2).contiguous()
        attn_output = attn_output.view(bsz, q_len, -1)

        attn_output = self.o_proj(attn_output)

        return attn_output, None, past_key_value

3. 修改modeling_deepseek.py的ATTENTION_CLASSES,加上sdpa支持,如下:


ATTENTION_CLASSES = {
    "eager": DeepseekV2Attention,
    "flash_attention_2": DeepseekV2FlashAttention2,

    "mla_eager": DeepseekV2Attention,
    "mla_flash_attention_2": DeepseekV2FlashAttention2,

    "mha_eager": LlamaAttention,
    "mha_flash_attention_2": LlamaFlashAttention2,
    "mha_sdpa": DeepSeekSdpaAttention
}

4.使用的sageattion和Triton的版本如下:

Name: sageattention
Version: 1.0.6

Name: triton
Version: 3.2.0

5. 训练测试,

swift sft  --model "deepseek-ai/deepseek-vl2-tiny"  --dataset  ../TEST.json  --attn_impl sdp

。。。
using attn_implementation: mha_sdpa
[INFO:swift] model.hf_device_map: {'': device(type='cuda', index=0)}

。。。
[INFO:swift] End time of running main: 2025-03-28 10:43:29.304164

成功进行了训练。

SageAttention2:实现精确的4位注意力以加速推理 SageAttention2的出现,正是为了应对这一挑战,通过引入4位量化技术和其他精度增强方法,显著提升了注意力计算的速度,而不损失精度。虽然SageAttention通过将QK⊤量化为INT8,并使用FP16进行P V的矩阵乘法实现了显著的加速效果,但它存在两个主要的局限性:首先,INT8的计算速度仅为INT4的一半;SageAttention2在SageAttention的基础上,通过将矩阵Q, K量化为INT4,并将矩阵P, V量化为FP8,进一步提升了注意力计算的效率。 阅读详情

相关推荐

华为防火墙双ISP出口实战:如何用策略路由实现电信联通流量自动切换(附配置截图)

本文详细解析了华为防火墙在双ISP环境下的智能选路技术,通过策略路由与健康检测的深度应用,实现电信联通流量的自动切换。文章包含实战配置截图,帮助企业解决切换延迟、路径劣化等核心挑战,提升业务连续性。

backprop5master的博客 644

Windows下成功安装SageAttention和triton

是一种「高效节能版」的注意力机制, 通过稀疏化和 GPU 内核优化让视频生成模型更快、更省显存, 相当于 FlashAttention 的“下一代”。在执行tcc.exe的时候报错。SageAttention 安装成功之后,就可以在Windows环境下启用加速功能了,一般会有比较明显的提速效果。红色框中选中的文件适用于cuda 为12.8,torch为2.8.0,Python为3.13。比如我的Pytorch是2.8,可以安装Triton3.4。必须根据自己环境来选择合适的文件,这里基本涵盖了常见的版本。

TonyNotes的博客 6572

ESP32天线阵列实现Wi-Fi空间成像与无直视定位

Wi-Fi信道状态信息(CSI)是OFDM系统中表征多径传播特性的基础物理层参数,其复数值包含幅度与相位,可反映无线环境的空间特征。基于CSI的射频感知技术,通过提取子载波级信道响应,结合阵列信号处理,实现到达角(AoA)估计与深度映射,本质是将通信链路重构为空间域传感器。该技术无需专用雷达硬件,具备低成本、被动式、隐私友好等工程优势,在室内定位、行为识别、仓储导航等场景具有广泛落地价值。本文聚焦ESP32平台,详解多芯片相位同步、CSI零拷贝采集、嵌入式MUSIC算法及信道图谱轻量化部署等关键实现。

weixin_30632267的博客 236

【亲测免费】 SageAttention 使用教程

SageAttention 是一个开源项目,旨在通过量化注意力机制来加速深度学习模型的推理过程,而不牺牲模型的端到端性能。该项目提供了优化的内核,支持不同GPU架构,包括Ampere、Ada和Hopper,通过INT8和FP8量化技术,实现了对QK^T和PV的加速处理。 ## 2. 项目快速启动 ### 环境准备 确保你的环境中安装了以下依赖: - Python >= 3.9 - PyTor...

gitblog_00216的博客 3319

深入STM32 USB OTG FS:从官方MSC例程到实战双存储设备移植全记录

本文详细解析了STM32 USB OTG FS在双存储设备开发中的实战应用,从协议栈底层机制到SD卡/SPI Flash同步挂载的实现。通过优化SDIO接口和SPI Flash驱动,结合USB MSC类的关键实现,提供了完整的解决方案和性能优化策略,适合嵌入式开发者参考。

weixin_28366475的博客 371

Flutter模块打包AAR集成Android原生项目实践

跨平台开发框架Flutter通过将UI组件渲染为原生代码实现高性能表现,其核心优势在于一套代码可同时运行在iOS和Android平台。在工程实践中,将Flutter模块打包为AAR(Android Archive)进行集成,成为混合开发的主流方案。这种方案既保留了原生项目的稳定性,又能渐进式引入Flutter的高效开发特性。通过配置MethodChannel实现原生与Dart代码通信,开发者可以灵活控制Flutter引擎生命周期,优化内存占用和渲染性能。对于电商、社交等需要快速迭代的业务场景,该方案能显著提

weixin_34025051的博客 399

大模型论文 | 清华推出SageAttention2,性能比FlashAttention2和xformers飙升3-5倍

AI大模型作为人工智能领域的重要技术突破,正成为推动各行各业创新和转型的关键力量。抓住AI大模型的风口,掌握AI大模型的知识和技能将变得越来越重要。学习AI大模型是一个系统的过程,需要从基础开始,逐步深入到更高级的技术。这里给大家精心整理了一份全面的AI大模型学习资源,包括:AI大模型全套学习路线图(从入门到实战)、精品AI大模型学习书籍手册、视频教程、实战学习、面试题等,资料免费分享!

Androiddddd的博客 2131

绿标短网址app.10086.cn/xxxxx移动短网址缩短接口网址api调用php方式解析

绿标短网址app.10086.cn/xxxxx 移动网缩短接口网址api调用php方式解析 app.10086.cn是移动网站的接口,可以制作移动网等第三方官方网站域名的任意生成接口,由于是认证企业,可以再抖音 微信 qq等第三方渠道正常打开不拦截提示,第三方网址,头条文章等,效果非常号,这里记录下api接口,纯技术php生成,具体规则可以去抖音的开放平台去申请对应接口 。这里用我php模拟抓包获取方式 GET http://www.app10086cn.cn/?i=app.10068.cnHTTP/1.1

qq_20300095的博客 5908

Windows系统安装SageAttention详细教程:Wheel文件安装指南

本文详细介绍Windows系统安装SageAttention的wheel文件方法。SageAttention是清华大学开发的高效注意力机制库,相比FlashAttention能提速2-5倍。文章推荐使用预编译wheel文件安装,可避免编译问题、安装快速且稳定。提供了HuggingFace Hub、GitHub等多个wheel文件下载地址,并给出版本选择指南。详细说明环境准备、安装步骤和验证方法,包括Python版本检查、CUDA匹配等关键点。同时总结了常见问题解决方案,如版本不匹配、CUDA兼容性等。最后强

AITechLab 的博客 6889

Delphi 12社区版免费了!手把手教你搭建跨平台开发环境(Windows/macOS/Android/iOS)

本文详细介绍了如何利用新发布的Delphi 12社区版,免费搭建支持Windows、macOS、Android和iOS的跨平台开发环境。内容涵盖从环境准备、安装、配置各平台SDK(包括Android与macOS/iOS的PAServer连接),到创建首个FireMonkey跨平台应用、集成数据库以及调试部署的完整实战流程,帮助开发者零成本启动高效开发。

butter的博客 979

OceanBase备租户创建(二):通过BACKUP DATABASE PLUS ARCHIVELOG

OceanBase数据库备租户创建方法二:通过BACKUP DATABASE PLUS ARCHIVELOG功能实现,特别适用于社区版和单机版部署模式。

Sebastien23的博客 542

SageAttention:提升神经网络性能的注意力机制

SageAttention:提升神经网络性能的注意力机制 项目介绍 在当今深度学习领域,注意力机制已成为提升模型性能的重要手段。SageAttention 是一个开源项目,旨在为神经网络提供高效、灵活的注意力模块,帮助研究人员和开发者构建更加强大和精准的模型。该项目的目标是简化注意力机制的应用,并推动深度学习领域的发展。 项目技术分析 SageAttention 的核心是基于图注意力机制(Grap...

gitblog_00133的博客 524

DISM进行系统修复,进度条卡在63.2%的解决方法

一时用不了软件,安装修复的时候也出现问题 DISM一直卡在63.2%,等了好久时间,直接强制退出寻找最终的解决方案

码农研究僧的博客 1万+

DeepSeek-VL2使用swift微调的环境搭建和微调过程

最大模型用8张卡跑起来很难,需要降低--lora_rank、--lora_alpha、--max_length、--deepspeed、--per_device_train_batch_size、--gradient_accumulation_steps、--dataloader_num_workers才能刚好跑起来,虽然跑起来了,但训练速度却非常的慢。模型合并后,将模型复制到deepseek-vl2/deepseek-ai/目录下,使用deepseek-vl2的web.demo可以跑一下看看运行效果。

盛世芳华 3106

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

Comfyui中安装SageAttention(for Wan2.2)的记录

本文分享了安装SageAttention和Triton的复杂过程。作者指出这些组件存在严格的版本依赖关系,本地编译需要匹配CUDA toolkit、Python环境(需完整库文件)及特定版本的MSVC buildtools(2022版)。经过与ChatGPT反复调试后环境混乱,最终建议直接使用预编译轮子(附GitHub链接),强调需匹配本地Python、Torch和CUDA版本,这比自行搭建环境更高效。文中提供了woct0rdho维护的Triton和SageAttention的Windows预编译版本仓库地

聚梦小课堂 5074

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

在Windows中安装sage-attn的记录(含为ComfyUI安装)

#工作记录运行项目显示报错输出之一:但是直接pip install sage-attn尝试安装则同样会报错:翻找了大量资料和尝试了大量方法之后,终于找到正确的安装命令是: 安装完成之后, “Sage Attn is not installed!”的这个报错消除了: 显示 sage-attn已安装!有效参考资料之一:常规命令: ComfyUI 命令: Conda 环境:

AITechLab 的博客 4965

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

ComfyUI-bleh项目中SageAttention加速模块的技术解析

ComfyUI-bleh项目中SageAttention加速模块的技术解析 背景介绍 ComfyUI-bleh是一个基于ComfyUI的扩展项目,其中包含了一个名为SageAttention的优化模块。这个模块旨在通过改进注意力机制的计算方式来提升图像生成模型的推理速度。本文将深入分析该模块的技术特点、适用场景以及实际效果。 SageAttention的工作原理 SageAttention是一种针...

gitblog_07369的博客 1012

SageAttention2原理和计算过程

概述SageAttention2 是一种高效的自注意力机制优化方案,通过结合离群值平滑(Outlier Smoothing)和逐线程 INT4 量化(Per-thread INT4 Quantization),显著提升 Transformer 模型的推理效率,同时保持较高的模型精度。该方法特别适用于大语言模型(LLMs)和高吞吐量推理场景。核心创新点Thorough Outlier Smoothing(离群值平滑)问题背景。

jerwey的博客 1418

普通 Attention、FlashAttention、SageAttention的区别

教科书实现,现在几乎不用。

一抹烟霞的博客 1079

【mmodel/xDit】SageAttention: 多模态大模型中的高效量化注意力机制

SageAttention是一种创新的量化注意力机制,通过矩阵级INT8/FP4量化和K矩阵平滑技术,在几乎无损精度的前提下实现2-5倍加速。其核心在于: 差异化量化策略: Q矩阵直接量化 K矩阵先平滑后量化以消除异常值影响 V矩阵直接量化 关键优化技术: 分块量化策略(1×16)提高局部精度 K矩阵平滑降低量化误差 混合精度计算流程(QK计算用INT8,Softmax用FP16) 显著优势: 相比FlashAttention2速度提升2-5倍 端到端精度损失<0.5% 广泛硬件兼容性 该技术特别适用

qq_20707221的博客 1701

SageAttention量化注意力机制:实现3倍速度提升的安装配置指南

SageAttention是一款革命性的量化注意力优化框架,通过先进的量化技术在不损失精度的前提下,将注意力机制的计算速度提升2.1-3.1倍,相比FlashAttention2和xformers分别实现2.7-5.1倍的性能加速。本指南将详细介绍如何快速部署这一高效工具。 ## 环境准备与硬件要求 ### 系统环境检查清单 在开始安装之前,请确保您的系统满足以下基本要求: - **Pyt

gitblog_00202的博客 571

Sageattention window wheel 下载与安装

Sageattention window 下载与安装

sunjunqing的专栏 874

即插即用!清华提出8比特注意力:SageAttention,两倍加速于FlashAttention2,端到端任务均不掉点!...

点击下方卡片,关注“CVer”公众号AI/CV重磅干货,第一时间送达点击进入—>【Mamba/多模态/扩散】交流群添加微信号:CVer2233,小助手会拉你进群!扫描下方二维码,加入CVer学术星球!可以获得最新顶会/顶刊上的论文idea和CV从入门到精通资料,及最前沿应用!发论文/搞科研/涨薪,强烈推荐!转载自:机器之心论文第一作者张金涛来自清华大学计算机系,论文通讯作者陈键飞副教授及其他...

阿木寺的博客 4013

清华大学团队升级SageAttention,即插即用,4比特量化三倍加速不掉点!

大模型(LLM)是一种人工智能模型,旨在理解和生成人类语言。它们在大量的文本数据上进行训练,可以执行广泛的任务,包括文本总结、翻译、情感分析等等。LLM的特点是规模庞大,包含数十亿的参数,帮助它们学习语言数据中的复杂模式。这些模型通常基于深度学习架构,如转化器,这有助于它们在各种NLP任务上取得令人印象深刻的表现。本周大模型周报精选了7篇论文,分别来自清华大学的SageAttention2,腾讯的DRT-o1…

AI_Conf的博客 1179

ComfyUI 和 Sage Attention & Triton 加速,极简安装指南。

ComfyUI 和 Sage Attention & Triton 加速,极简安装指南。

给我来碗鱼丸粗面 1829

视频生成加速与量化:SageAttention——量化版的FlashAttention2

本文揭示了视频生成速度慢的核心瓶颈在于注意力计算的O(N²)复杂度。FlashAttention系列通过分块计算和显存优化实现了长序列运行,但直接量化会导致严重精度损失。SageAttention创新性地采用K矩阵平滑、FP16累加器和自适应量化三项技术,在RTX4090上实现了2.1倍加速,同时保持精度无损。该方法为消费级显卡上的高效视频生成提供了新思路,显著降低了技术应用门槛。

weixin_51097521的博客 688
上一篇: Stable Diffusion API /sdapi/v1/txt2img的完整参数列表及其说明
下一篇: 如何在huggingface安装指定的版本的transformer
aerror
博客等级 码龄23年 393粉丝 193原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值