当前位置: 首页 > article >正文

LLM 推理优化:加速与量化

LLM 推理优化加速与量化1. 技术分析1.1 LLM 推理挑战LLM 推理面临的主要挑战推理挑战 计算量大: O(n²d) 内存占用高: 参数 KV Cache 延迟要求: 实时应用需求1.2 推理优化方法方法原理加速比精度损失量化降低精度2-4x小蒸馏知识迁移1.5-2x小剪枝移除冗余1.5-3x中编译优化算子融合1.2-1.5x无1.3 KV Cache 优化KV Cache 存储中间结果避免重复计算KV Cache 每步推理: 新增1个token的K/V 复用之前所有token的K/V 内存: O(n * d * heads)2. 核心功能实现2.1 量化实现import torch import torch.nn as nn class QuantizedLinear(nn.Module): def __init__(self, weight, biasNone, bits4): super().__init__() self.bits bits self.weight self._quantize(weight, bits) self.bias bias def _quantize(self, weight, bits): scale (weight.max() - weight.min()) / (2**bits - 1) zero_point -weight.min() / scale quantized torch.round(weight / scale zero_point) quantized torch.clamp(quantized, 0, 2**bits - 1) return { values: quantized.to(torch.int8), scale: scale, zero_point: zero_point } def _dequantize(self): return self.weight[values].float() * self.weight[scale] - self.weight[zero_point] def forward(self, x): weight self._dequantize() return F.linear(x, weight, self.bias) class GPTQQuantizer: def __init__(self, model): self.model model def quantize(self, bits4): for name, module in self.model.named_modules(): if isinstance(module, nn.Linear): self._quantize_layer(module, bits) def _quantize_layer(self, layer, bits): H layer.weight.data rows, cols H.shape quantized torch.zeros(rows, cols, dtypetorch.int8) scales torch.zeros(rows) zeros torch.zeros(rows) for i in range(rows): row H[i] max_val row.abs().max() scale max_val / (2**(bits-1) - 1) zeros[i] 0 quantized_row torch.round(row / scale).to(torch.int8) quantized[i] quantized_row scales[i] scale layer.weight nn.Parameter(quantized) layer.register_buffer(scales, scales) layer.register_buffer(zeros, zeros)2.2 推理优化class OptimizedTransformer: def __init__(self, model): self.model model self.kv_cache {} def forward(self, input_ids, past_key_valuesNone): batch_size, seq_len input_ids.shape if past_key_values is None: past_key_values {} outputs [] for layer_idx, layer in enumerate(self.model.layers): key flayer_{layer_idx} if key in past_key_values: past_k, past_v past_key_values[key] else: past_k, past_v None, None output, new_k, new_v layer( input_ids, past_keypast_k, past_valuepast_v ) past_key_values[key] (new_k, new_v) input_ids output return output, past_key_values class FlashAttention: def __init__(self, causalTrue): self.causal causal def forward(self, Q, K, V): batch_size, heads, seq_len, d_k Q.shape Q Q.transpose(1, 2).reshape(batch_size * heads, seq_len, d_k) K K.transpose(1, 2).reshape(batch_size * heads, seq_len, d_k) V V.transpose(1, 2).reshape(batch_size * heads, seq_len, d_k) output self._flash_attention(Q, K, V) output output.reshape(batch_size, heads, seq_len, d_k).transpose(1, 2) return output def _flash_attention(self, Q, K, V): import flash_attn output flash_attn.flash_attn_func( Q, K, V, causalself.causal, return_attn_probsFalse ) return output2.3 编译优化class TorchCompileOptimizer: def __init__(self, model): self.model model def optimize(self, modereduce-overhead): self.model torch.compile(self.model, modemode) def compile_with_inductor(self): self.model torch.compile(self.model, backendinductor) class ONNXExporter: def __init__(self, model): self.model model def export(self, output_path): dummy_input torch.randint(0, 1000, (1, 32)) torch.onnx.export( self.model, dummy_input, output_path, opset_version15, input_names[input_ids], output_names[logits], dynamic_axes{ input_ids: {0: batch_size, 1: seq_len}, logits: {0: batch_size, 1: seq_len} } ) class TensorRTConverter: def __init__(self, model): self.model model def convert(self, output_path, precisionfp16): import tensorrt as trt builder trt.Builder(trt.Logger(trt.Logger.WARNING)) network builder.create_network() parser trt.OnnxParser(network, builder.logger) onnx_path output_path.replace(.engine, .onnx) self._export_onnx(onnx_path) with open(onnx_path, rb) as f: parser.parse(f.read()) config builder.create_builder_config() config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, 1 30) if precision fp16: config.set_flag(trt.BuilderFlag.FP16) engine builder.build_engine(network, config) with open(output_path, wb) as f: f.write(engine.serialize()) def _export_onnx(self, path): ONNXExporter(self.model).export(path)3. 性能对比3.1 量化方法对比方法精度加速比内存节省适用场景FP3232位1x0%训练FP1616位2x50%推理BF1616位2x50%训练/推理INT88位4x75%推理INT44位8x87%推理3.2 推理框架对比框架速度兼容性易用性PyTorch1x好高TensorRT2-4x中低ONNX Runtime1.5-2x好中TFLite2-3x中高3.3 KV Cache 影响序列长度KV Cache 内存推理时间(首token)推理时间(后续token)64128MB50ms10ms256512MB150ms10ms10242GB500ms10ms4. 最佳实践4.1 推理优化流程def optimize_for_inference(model, config): optimizer InferenceOptimizer(model) if config.get(quantize, False): optimizer.quantize(config[bits]) if config.get(compile, False): optimizer.compile() if config.get(flash_attention, False): optimizer.enable_flash_attention() return optimizer.model class InferenceOptimizer: def __init__(self, model): self.model model def quantize(self, bits4): quantizer GPTQQuantizer(self.model) quantizer.quantize(bits) def compile(self): compiler TorchCompileOptimizer(self.model) compiler.compile_with_inductor() def enable_flash_attention(self): self._replace_attention() def _replace_attention(self): for name, module in self.model.named_modules(): if attention in name.lower() and isinstance(module, nn.Module): module.forward self._flash_attention_forward4.2 部署建议class LLMDeployer: def __init__(self, model, config): self.model model self.config config def deploy(self): optimized_model optimize_for_inference(self.model, self.config) if self.config[platform] api: self._deploy_as_api(optimized_model) elif self.config[platform] edge: self._deploy_to_edge(optimized_model) def _deploy_as_api(self, model): from fastapi import FastAPI app FastAPI() app.post(/generate) def generate(prompt: str): return {response: model.generate(prompt)} return app def _deploy_to_edge(self, model): converter TensorRTConverter(model) converter.convert(model.engine, precisionfp16)5. 总结LLM 推理优化是部署的关键量化最有效的优化方法KV Cache避免重复计算Flash Attention内存高效的注意力计算编译优化进一步提升性能对比数据如下INT4 量化可实现 8 倍加速Flash Attention 可节省 30-50% 内存TensorRT 可再提升 2-4 倍速度推荐组合使用多种优化方法

相关文章:

LLM 推理优化:加速与量化

LLM 推理优化:加速与量化 1. 技术分析 1.1 LLM 推理挑战 LLM 推理面临的主要挑战: 推理挑战计算量大: O(nd)内存占用高: 参数 KV Cache延迟要求: 实时应用需求1.2 推理优化方法 方法原理加速比精度损失量化降低精度2-4x小蒸馏知识迁移1.5-2x小剪枝移除冗…...

2026校招技术岗薪资大盘点:AI方向白菜价40w起,这个方向却跌破20w

上周帮学弟看offer,吓了一跳。某大厂给AI对齐岗的校招白菜价,总包42w。同一个公司,传统测试开发岗,开出了18w。差了不止一倍。这不是个例。我翻了牛客网五月最新的offer帖,又问了几个在阿里、字节、美团的朋友&#xf…...

从Token泛滥到 Token 极度节俭:2026程序员必须掌握的推理成本优化指南

最近三个月,我身边越来越多的技术团队开始感受到一种压力。不是模型不够强,是账单涨得太快。我们组上个月刚把几个核心业务切到某新模型,效果确实好,但推理成本翻了4倍。老板问了一句:这钱能不能省一半?会议…...

从树莓派Pico到Linux开发板:手把手教你移植MPU6050 I2C驱动(附完整源码)

从树莓派Pico到Linux开发板:MPU6050 I2C驱动移植实战指南 当你在树莓派Pico上轻松驱动了MPU6050传感器后,想要将这个功能迁移到Linux开发板上时,可能会发现两者之间的差异远比想象中大。本文将带你深入理解Linux内核驱动框架,并手…...

Tauri+Next.js桌面应用开发:从零构建轻量级跨平台工具

1. 项目概述:一个现代桌面应用开发的“瑞士军刀” 如果你正在寻找一个能让你用熟悉的Web技术栈(Next.js React)快速构建高性能、跨平台桌面应用的开箱即用模板,那么 kvnxiao/tauri-nextjs-template 绝对值得你花时间深入研究。…...

Modern C++ Template 包管理器集成:Conan与Vcpkg最佳实践

Modern C Template 包管理器集成:Conan与Vcpkg最佳实践 【免费下载链接】modern-cpp-template A template for modern C projects using CMake, Clang-Format, CI, unit testing and more, with support for downstream inclusion. 项目地址: https://gitcode.com…...

kkFileView容器网络性能优化:基于SR-IOV的硬件加速终极指南

kkFileView容器网络性能优化:基于SR-IOV的硬件加速终极指南 【免费下载链接】kkFileView Universal File Online Preview Project based on Spring-Boot 项目地址: https://gitcode.com/GitHub_Trending/kk/kkFileView 在现代云原生应用中,容器化…...

如何利用OR-Tools优化出版业:印刷调度与分销路线的完整指南

如何利用OR-Tools优化出版业:印刷调度与分销路线的完整指南 【免费下载链接】or-tools Googles Operations Research tools: 项目地址: https://gitcode.com/gh_mirrors/or/or-tools OR-Tools是Google开发的强大开源运筹学工具库,能够帮助出版企业…...

如何10分钟搞定300张照片的智能水印处理?

如何10分钟搞定300张照片的智能水印处理? 【免费下载链接】semi-utils 一个批量添加相机机型和拍摄参数的工具,后续「可能」添加其他功能。 项目地址: https://gitcode.com/gh_mirrors/se/semi-utils 作为一名摄影爱好者,你是否曾为给…...

shadcn-ui-expansions Infinite Scroll 实现原理:构建高性能无限滚动列表的完整指南

shadcn-ui-expansions Infinite Scroll 实现原理:构建高性能无限滚动列表的完整指南 【免费下载链接】shadcn-ui-expansions More components built on top of shadcn-ui. 项目地址: https://gitcode.com/gh_mirrors/sh/shadcn-ui-expansions shadcn-ui-expa…...

Bootstrap 4到Bootstrap 5最核心的变化是什么.txt

响应式开发应统一管理断点变量与媒体查询mixin、限制嵌套层级≤3层并用BEM语法扁平化、禁用跨文件extend改用include、分离布局与视觉响应逻辑,核心在于职责边界清晰化。响应式断点写死在媒体查询里,改起来像修水管直接把 768px、1024px 这类数值散落在各…...

大麦网自动化购票系统:Python脚本实现高效票务获取完整指南

大麦网自动化购票系统:Python脚本实现高效票务获取完整指南 【免费下载链接】Automatic_ticket_purchase 大麦网抢票脚本 项目地址: https://gitcode.com/GitHub_Trending/au/Automatic_ticket_purchase 在当今热门演出票务市场,手动抢票的成功率…...

Windows热键冲突检测:快速定位被占用快捷键的终极指南

Windows热键冲突检测:快速定位被占用快捷键的终极指南 【免费下载链接】hotkey-detective A small program for investigating stolen key combinations under Windows 7 and later. 项目地址: https://gitcode.com/gh_mirrors/ho/hotkey-detective 你是否曾…...

3步掌握:微信数据本地解密与恢复完整方案

3步掌握:微信数据本地解密与恢复完整方案 【免费下载链接】WechatDecrypt 微信消息解密工具 项目地址: https://gitcode.com/gh_mirrors/we/WechatDecrypt 你是否曾因更换手机而丢失珍贵的微信聊天记录?或者不小心删除了重要的商务对话&#xff1…...

代码开挂:IT人的超能力技能树

好的,这是一份关于“写代码像开挂:IT人的超能力技能树”的技术文章大纲:标题: 写代码如开挂:解锁IT人的超能力技能树导语: 想象一下,写代码不再是枯燥的敲键盘,而是像在游戏中开启“…...

变附着系数AGV横摆稳定性控制【附程序】

✨ 长期致力于无人搬运车、横摆稳定性、变附着系数、路面附着系数估计、直接横摆力矩控制研究工作,擅长数据搜集与处理、建模仿真、程序编写、仿真设计。 ✅ 专业定制毕设、代码 ✅ 如需沟通交流,点击《获取方式》 (1)自适应无迹卡…...

trade ai编辑器使用规范

Spring Cloud 代码生成规范 v1.0 角色定义 您是一位经验丰富的Spring Cloud架构师,专注于: 严格遵循Java 17 Spring Boot 3.2.4 Spring Cloud Alibaba技术栈实现高内聚低耦合的微服务架构确保生成的代码与项目现有规范100%兼容 核心架构原则依赖注入: …...

保姆级教程:在VMware Workstation 16 Pro上为ArchLinux配置完整的拖放和剪贴板共享

在VMware Workstation Pro上为ArchLinux配置无缝交互功能全指南 对于追求极致效率的开发者而言,虚拟机与宿主机之间的隔阂常常成为工作流中的瓶颈。想象一下,当你在宿主机上浏览到一个关键的技术文档,却无法直接将链接分享到虚拟机中的开发环…...

终极指南:如何将SVProgressHUD与Xcode Cloud完美集成

终极指南:如何将SVProgressHUD与Xcode Cloud完美集成 【免费下载链接】SVProgressHUD A clean and lightweight progress HUD for your iOS and tvOS app. 项目地址: https://gitcode.com/gh_mirrors/sv/SVProgressHUD SVProgressHUD是一个轻量级、简洁美观的…...

SARScape处理Sentinel-1数据实战:手把手教你如何检查和编辑SBAS连接图(Connection Graph)

SARScape处理Sentinel-1数据的SBAS连接图深度解析与实战优化 当处理Sentinel-1数据的SBAS-InSAR分析时,连接图(Connection Graph)的质量直接影响最终形变监测结果的可靠性。许多用户在完成数据预处理后,面对复杂的点线图和报告文件…...

为 Hermes Agent 配置 Taotoken 自定义提供商接入指南

🚀 告别海外账号与网络限制!稳定直连全球优质大模型,限时半价接入中。 👉 点击领取海量免费额度 为 Hermes Agent 配置 Taotoken 自定义提供商接入指南 Hermes Agent 是一个功能强大的 AI 智能体开发框架,支持通过自定…...

Python包管理‘备胎’方案:除了pip install,你的whl本地仓库建好了吗?

Python包管理‘备胎’方案:构建企业级whl本地仓库的完整实践 当团队开发遇到内网隔离、依赖版本锁死或跨国镜像访问延迟时,临时四处搜寻whl文件就像在代码仓库里玩扫雷——每次pip install都可能是场冒险。真正的工程化解决方案,是把散落在百…...

告别U盘!用CentOS 7.9 + iPXE + dnsmasq搭建一个能装CentOS/AlmaLinux/Ubuntu的万能网络启动盘

告别U盘!用CentOS 7.9 iPXE dnsmasq搭建万能网络启动环境 每次机房新设备到货或系统升级时,运维人员最头疼的就是反复制作不同系统的启动U盘。传统方式不仅效率低下,还常遇到U盘兼容性问题。本文将分享如何利用一台闲置的CentOS 7.9服务器&…...

别再手动画线了!用AutoCAD VBA脚本自动生成船体型线图(附完整代码)

别再手动画线了!用AutoCAD VBA脚本自动生成船体型线图(附完整代码) 船舶设计工程师们,是否厌倦了在AutoCAD中反复绘制相同的型线图?那些看似简单的横剖线、纵剖线和肋骨型线,往往消耗大量时间在机械性操作上…...

3分钟告别网盘限速:免费开源油猴脚本使用指南

3分钟告别网盘限速:免费开源油猴脚本使用指南 【免费下载链接】baiduyun 油猴脚本 - 一个免费开源的网盘下载助手 项目地址: https://gitcode.com/gh_mirrors/ba/baiduyun 还在为网盘下载速度慢如蜗牛而烦恼吗?想要摆脱客户端的束缚,直…...

全民可玩的超元力迷你沙盘赛车,解锁轻量化竞速游乐新风口

如今的休闲娱乐市场,大众早已不满足于单调的电玩游戏、普通亲子游乐,更偏爱有参与感、有操控感、有竞技氛围的实体互动项目。超元力迷你沙盘赛车凭借真实驾驶体验、轻量化落地条件、多人互动竞技属性,迅速出圈成为文旅游乐、商业综合体、亲子…...

从点亮LED到驱动电机:用ESP32和SimpleFOC库开启你的第一个硬件项目

从点亮LED到驱动电机:用ESP32和SimpleFOC库开启你的第一个硬件项目 当你第一次拿到ESP32开发板时,或许会被它小巧的尺寸和丰富的接口所迷惑——这块比拇指大不了多少的电路板,真的能像宣传的那样轻松控制电机吗?作为过来人&#…...

从串行到以太网:SEMI E37 HSMS协议如何重塑半导体设备通信

1. 半导体设备通信的进化史:从串口到以太网 十年前我第一次接触半导体设备通信时,车间里密密麻麻的串口线让我印象深刻。每条产线上十几台设备,每台设备背后都拖着几根九针串口线,像蜘蛛网一样缠绕在一起。当时最头疼的就是排查通…...

Bayard查询DSL完全手册:9种查询类型详解与实战案例

Bayard查询DSL完全手册:9种查询类型详解与实战案例 【免费下载链接】bayard A full-text search and indexing server written in Rust. 项目地址: https://gitcode.com/gh_mirrors/ba/bayard Bayard是一个使用Rust编写的高性能全文搜索和索引服务器&#xf…...

YOLOv8-face人脸检测模型ONNX转换实战:从训练到部署全流程

YOLOv8-face人脸检测模型ONNX转换实战:从训练到部署全流程 【免费下载链接】yolov8-face yolov8 face detection with landmark 项目地址: https://gitcode.com/gh_mirrors/yo/yolov8-face 想要将YOLOv8-face人脸检测模型快速部署到生产环境吗?ON…...