尧图网络科技YAOTU DIGITAL 获取报价
获取报价
首页 / 资讯中心 / 文章详情

LMDeploy 离线推理 Pipeline 完全指南:从 Hello World 到 logits、PPL 与 LoRA 实战

发布时间:2026/9/27 17:16:35

资讯中心
01
ARTICLE

LMDeploy 离线推理 Pipeline 完全指南:从 Hello World 到 logits、PPL 与 LoRA 实战

LMDeploy 离线推理 Pipeline 完全指南:从 Hello World 到 logits、PPL 与 LoRA 实战
人工智能大模型模型推理服务推理引擎本地部署模型量化【免费下载链接】lmdeployLMDeploy is a toolkit for compressing, deploying, and serving LLMs.项目地址https://gitcode.com/gh_mirrors/lm/lmdeploy点击查看免费下载LMDeploy 的lmdeploy.pipeline是面向离线批处理推理的 Python API 层它屏蔽了 TurboMind 与 PyTorch 两套后端引擎的差异让开发者可以用统一的接口完成模型加载、张量并行、采样控制、流式输出、困惑度PPL评估以及 LoRA 适配器推理等任务。本篇指南以 pipeline.md 为核心骨架结合 pipeline.py 与 messages.py 等源码完整演示 Pipeline 的每一个用法并深入讲解其背后的参数机制与实现原理。读完本文你将能够独立编写可运行的离线推理脚本并理解各配置项对显存、吞吐与生成行为的具体影响。Pipeline 是什么一站式离线推理入口在进入代码之前先看清 Pipeline 的定位。从 pipeline.py 的Pipeline类实现可以看出它是面向用户的门面facade层构造时接收model_path本地目录或 Hugging Face 模型 id、可选的backend_config、chat_template_config、log_level、trust_remote_code与speculative_config等参数若模型路径不存在于本地会自动通过get_model下载权重backend_config.download_dir/revision可控制下载目录与版本内部会调用 archs.py 的autoget_backend_config自动选择后端引擎优先使用 TurboMind若模型不被 TurboMind 支持或 TurboMind 未编译则回退到 PyTorch 引擎对于视觉语言模型如 InternVL、Qwen2.5-VL 等get_task会识别出 VLM 架构并切换到VLAsyncEngine因此同一个pipeline()也能直接跑多模态推理。也就是说pipeline()一行代码背后完成了模型下载 → 后端选择 → 引擎实例化 → 异步事件循环启动的全过程这也是它如此易用的根本原因。完整的 API 细节可参考仓库内的 pipeline.rst。Hello World最小可运行示例最简单的用法如下from lmdeploy import pipeline pipe pipeline(internlm/internlm2_5-7b-chat) response pipe([Hi, pls intro yourself, Shanghai is]) print(response)这里有两个值得注意的机制批处理输入传入一个 prompt 列表Pipeline.__call__pipeline.py会转交给infer返回与输入一一对应的Response列表如果只传单个字符串则返回单个Response_is_single负责判断见 pipeline.py。K/V cache 自动分配Pipeline 默认会按固定比例预留显存给 K/V cache这个比例由TurbomindEngineConfig.cache_max_entry_count决定。如果推理时出现 OOM第一反应通常是调低这个比例具体策略见下一节。Response对象定义见 messages.py携带text、generate_token_len、input_token_len、finish_reason、token_ids、logprobs、logits、last_hidden_state等字段方便后续程序化处理。理解 K/V cache 显存比例cache_max_entry_count 的前世今生TurbomindEngineConfig.cache_max_entry_count的语义在 LMDeploy 演进过程中发生过一次重要变化理解它有助于排查 OOMv0.2.0 lmdeploy v0.2.1默认值为0.5表示按 GPU总显存的 50% 分配 K/V cache。此时若在一张显存小于 40G 的卡上部署 7B 模型就可能出现 OOM。遇到 OOM 时应主动调低比例例如降到 20%from lmdeploy import pipeline, TurbomindEngineConfig # decrease the ratio of the k/v cache occupation to 20% backend_config TurbomindEngineConfig(cache_max_entry_count0.2) pipe pipeline(internlm/internlm2_5-7b-chat, backend_configbackend_config) response pipe([Hi, pls intro yourself, Shanghai is]) print(response)lmdeploy v0.2.1分配策略改为按 GPU空闲显存比例预留默认值调整为0.8。若仍出现 OOM同样调小该比例即可。当前仓库中TurbomindEngineConfig.cache_max_entry_count默认值即0.8messages.pyPyTorch 引擎的PytorchEngineConfig.cache_max_entry_count同样默认0.8messages.py。从源码层面看这个比例是如何生效的在 PyTorch 引擎中显存分配逻辑位于 executor/base.py其核心计算是available_mems int((free_mem - runtime_cache_size) * cache_max_entry_count)即从当前空闲显存中按比例扣出 K/V cache 空间与文档描述完全一致。此外当cache_max_entry_count为大于 0 的整数时它还被解释为 K/V block 的总块数见 messages.py 的注释。需要补充的两个相关参数cache_block_seq_lenTurboMind默认 64messages.py每个 K/V block 容纳的 token 数cache_chunk_size默认 -1messages.pyblock manager 申请 K/V block 的块策略。它们与cache_max_entry_count共同决定了可缓存的序列长度与批处理容量。设置张量并行Tensor Parallelism单卡显存放不下模型时可以通过TurbomindEngineConfig(tp2)启用 2 卡张量并行将模型权重切分到多张 GPU 上from lmdeploy import pipeline, TurbomindEngineConfig backend_config TurbomindEngineConfig(tp2) pipe pipeline(internlm/internlm2_5-7b-chat, backend_configbackend_config) response pipe([Hi, pls intro yourself, Shanghai is]) print(response)关于tp有几点源码层面的说明TurbomindEngineConfig.tp默认1messages.py校验要求tp 1除tp外messages.py 还定义了dp数据并行、cp上下文并行、ep专家并行面向 MoE 模型等维度多卡场景下可组合使用在 PyTorch 引擎下若tp1需要配合进程启动约束见文末 FAQ 的if __name__ __main__说明。设置采样参数GenerationConfig 详解推理质量主要靠GenerationConfig控制。以下示例设置了典型采样参数from lmdeploy import pipeline, GenerationConfig, TurbomindEngineConfig backend_config TurbomindEngineConfig(tp2) gen_config GenerationConfig(top_p0.8, top_k40, temperature0.8, max_new_tokens1024) pipe pipeline(internlm/internlm2_5-7b-chat, backend_configbackend_config) response pipe([Hi, pls intro yourself, Shanghai is], gen_configgen_config) print(response)GenerationConfig的完整字段定义在 messages.py除了示例中用到的四个参数以下是常用字段的默认值与语义参数默认值语义max_new_tokens512单次生成的最大新 token 数do_sampleFalse是否使用采样为False时走贪心解码top_p1.0核采样nucleus sampling概率质量取值[0, 1]top_k50只考虑概率最高的前 k 个 token需 0min_p0.0最小 token 概率按最高概率 token 缩放取值[0, 1]典型值0.01~0.2temperature0.8采样温度取值[0, 2]repetition_penalty1.0重复惩罚大于 1 抑制重复ignore_eosFalse是否忽略 EOS token 继续生成random_seedNone采样随机种子stop_words/bad_wordsNone停止词 / 禁用词字符串形式内部会经convert_stop_bad_words_to_ids转成 token idstop_token_ids/bad_token_idsNone停止 token / 禁用 token idmin_new_tokensNone最少生成的 token 数skip_special_tokensTrue解码时是否去掉特殊 tokenlogprobsNone每个输出 token 返回的 top logprob 数量response_formatNone结构化输出json_schema/regex_schema/structural_tagoutput_logitsNone取all或generation返回 logitsoutput_last_hidden_stateNone取all或generation返回最后一层 hidden stateinclude_stop_str_in_outputFalse输出中是否包含停止字符串repetition_ngram_size/repetition_ngram_threshold0/0n-gram 重复早停最新 size 个 token 重复 threshold 次即停止GenerationConfig.__post_init__messages.py会做合法性校验例如top_p必须在[0,1]、temperature必须在[0,2]、logprob_start_len不能小于 -1因此传入非法值会直接抛断言错误而不是静默生效。此外gen_config既可以传单个GenerationConfig应用于整批输入也可以传一个与 prompts 等长的GenerationConfig列表为批内每条 prompt 定制不同的生成策略见 pipeline.py 的展开逻辑。使用 OpenAI 格式的 Promptpipeline支持直接传入 OpenAI 风格的对话消息结构[{role, content}, ...]这比拼接纯文本 prompt 更规范尤其在多轮对话场景下from lmdeploy import pipeline, GenerationConfig, TurbomindEngineConfig backend_config TurbomindEngineConfig(tp2) gen_config GenerationConfig(top_p0.8, top_k40, temperature0.8, max_new_tokens1024) pipe pipeline(internlm/internlm2_5-7b-chat, backend_configbackend_config) prompts [[{ role: user, content: Hi, pls intro yourself }], [{ role: user, content: Shanghai is }]] response pipe(prompts, gen_configgen_config) print(response)在 pipeline.py 中所有输入字符串、dict 或 dict 列表都会先经过MultimodalProcessor.format_prompts统一归一化为消息列表格式再交给引擎的preprocess按模型的 chat template 渲染成实际输入 token。这也解释了为什么字符串 prompt 与消息结构 prompt 可以混用它们在进入引擎前都被转换为同一种内部表示。流式输出stream_infer离线批处理同样支持流式返回适合边生成边消费例如实时打印、逐步组装结果。stream_infer返回一个生成器逐个产出Responsefrom lmdeploy import pipeline, GenerationConfig, TurbomindEngineConfig backend_config TurbomindEngineConfig(tp2) gen_config GenerationConfig(top_p0.8, top_k40, temperature0.8, max_new_tokens1024) pipe pipeline(internlm/internlm2_5-7b-chat, backend_configbackend_config) prompts [[{ role: user, content: Hi, pls intro yourself }], [{ role: user, content: Shanghai is }]] for item in pipe.stream_infer(prompts, gen_configgen_config): print(item)从实现上看stream_inferpipeline.py内部把每个请求封装为异步任务通过队列将引擎产生的增量Response源源不断送回主线程_infer方法见 pipeline.py批内并发上限受backend_config.max_batch_size控制_get_limiterpipeline.py。此外Pipeline.chat方法pipeline.py也基于stream_infer实现了带会话历史的流式多轮对话并支持stream_responseTrue时返回迭代器。获取生成 token 的 logits若需要做二次采样、打分或调试可以开启output_logitsgeneration之后从每个Response.logits中取回张量from lmdeploy import pipeline, GenerationConfig pipe pipeline(internlm/internlm2_5-7b-chat) gen_configGenerationConfig(output_logitsgeneration, max_new_tokens10) response pipe([Hi, pls intro yourself, Shanghai is], gen_configgen_config) logits [x.logits for x in response]注意两点output_logits支持all与generation两个取值前者覆盖 prompt 与生成 token后者只包含生成 tokenResponse中对应字段为logitstorch.Tensormessages.py在 PyTorch 引擎下pytorch/messages.py 对output_logits有限制仅支持all且要求max_new_tokens 0否则会被降级并输出警告。因此若要跨引擎通用建议使用generationTurboMind 侧在 turbomind.py 中通过_get_offset计算 logits 的起始偏移。获取最后一层 hidden states类似地开启output_last_hidden_stategeneration可以拿到最后一层即 embedding 输出层的 hidden state适用于特征提取、嵌入计算等场景from lmdeploy import pipeline, GenerationConfig pipe pipeline(internlm/internlm2_5-7b-chat) gen_configGenerationConfig(output_last_hidden_stategeneration, max_new_tokens10) response pipe([Hi, pls intro yourself, Shanghai is], gen_configgen_config) hidden_states [x.last_hidden_state for x in response]对应的Response字段为last_hidden_statemessages.py。TurboMind 引擎在 turbomind.py 中通过_get_offset计算 hidden state 的起始位置与 logits 的处理方式一致。提示在 PyTorch 引擎下output_logits或output_last_hidden_state取all时需要与enable_prefix_caching配合时注意——async_engine.py 中的逻辑显示开启前缀缓存时这两类全量输出会触发告警提示实际使用建议保持默认前缀缓存关闭或只取generation。计算困惑度 PPLPipeline 提供get_ppl方法直接基于 token id 序列计算困惑度perplexityfrom transformers import AutoTokenizer from lmdeploy import pipeline model_repoid_or_path internlm/internlm2_5-7b-chat pipe pipeline(model_repoid_or_path) tokenizer AutoTokenizer.from_pretrained(model_repoid_or_path, trust_remote_codeTrue) messages [ {role: user, content: Hello, how are you?}, ] input_ids tokenizer.apply_chat_template(messages) # ppl is a list of float numbers ppl pipe.get_ppl(input_ids) print(ppl)使用注意事项原文档明确提示输入过长可能 OOMinput_ids太长时可能触发显存溢出请谨慎使用返回值语义get_ppl返回的是未做指数运算的交叉熵损失cross entropy loss并非严格意义上的 exp 后的困惑度值需要时请自行转换。源码佐证get_ppl实现于 pipeline.py它会将输入统一为list[list[int]]并通过asyncio.gather并发调用引擎的async_get_ppl引擎侧实现位于 async_engine.py其内部通过GenerationConfig(return_pplTrue)让引擎输出未归一化的交叉熵ce_loss见 messages.py 的EngineOutput.ce_loss说明。此外async_get_ppl在开启前缀缓存或投机解码speculative decoding时不可用async_engine.py如需计算 PPL 请保持这两项关闭。使用 PyTorch 引擎除默认的 TurboMind 引擎外也可以显式选择 PyTorch 引擎适合 TurboMind 暂不支持的模型、或需要自定义模块的场景。使用前需安装 tritonpip install triton2.1.0然后通过PytorchEngineConfig初始化from lmdeploy import pipeline, GenerationConfig, PytorchEngineConfig backend_config PytorchEngineConfig(session_len2048) gen_config GenerationConfig(top_p0.8, top_k40, temperature0.8, max_new_tokens1024) pipe pipeline(internlm/internlm2_5-7b-chat, backend_configbackend_config) prompts [[{ role: user, content: Hi, pls intro yourself }], [{ role: user, content: Shanghai is }]] response pipe(prompts, gen_configgen_config) print(response)PytorchEngineConfigmessages.py的常用字段包括字段默认值说明session_lenNone最大会话长度显式设置可避免序列过长被截断tp/dp/ep1/1/1张量并行 / 数据并行 / 专家并行cache_max_entry_count0.8K/V cache 占空闲显存比例校验要求0 x 1比 TurboMind 更严格block_size64paging cache 块大小num_cpu_blocks/num_gpu_blocks0/0手动指定 block 数量为 0 时按环境自动分配max_prefill_token_num8192每次 prefill 的 token 数prefill_interval16prefill 执行间隔adaptersNoneLoRA 适配器配置dict[name, path]quant_policyNONEK/V cache 量化策略int44、int88、fp816、fp8_e5m217eager_modeFalse是否关闭图模式CUDA Graphdevice_typecuda推理设备可取值cuda/ascend/maca/cambcustom_module_mapNone用户自定义 nn 模块映射替换原模型模块enable_prefix_cachingFalse前缀缓存prompt 复用enable_mp_engineFalse多进程引擎模式引擎的选择并非二选一冲突即使不传backend_configarchs.py 的autoget_backend也会根据模型架构自动判断——TurboMind 支持则用 TurboMind否则回退 PyTorch显式传入PytorchEngineConfig则强制走 PyTorch 引擎。结合 LoRA 进行推理PyTorch 引擎支持在推理时挂载 LoRA 适配器。先在PytorchEngineConfig.adapters中声明适配器键为自定义名称值为 LoRA 权重路径再在pipe()调用时通过adapter_name指定from lmdeploy import pipeline, GenerationConfig, PytorchEngineConfig backend_config PytorchEngineConfig(session_len2048, adaptersdict(lora_name_1chenchi/lora-chatglm2-6b-guodegang)) gen_config GenerationConfig(top_p0.8, top_k40, temperature0.8, max_new_tokens1024) pipe pipeline(THUDM/chatglm2-6b, backend_configbackend_config) prompts [[{ role: user, content: 您猜怎么着 }]] response pipe(prompts, gen_configgen_config, adapter_namelora_name_1) print(response)源码层面的实现细节PytorchEngineConfig.adapters是dict[str, str]messages.py键值分别为适配器名与路径/模型 id引擎初始化时engine.py 会下载不存在的适配器权重并通过AdapterManager统一管理_build_adapter_managerengine.pyengine_checker.py也会校验适配器路径是否存在engine_checker.pyadapter_name贯穿infer→stream_infer→ 引擎generate的整个调用链最终在engine_instance.pyengine_instance.py中生效若 LoRA 权重自带对应的 chat template可先将该 chat template 注册进 LMDeploy然后直接用 chat template 名称作为adapter_name详见文末 FAQ。更完整的 LoRA 服务化说明可参考 api_server_lora.md。释放 Pipeline 资源Pipeline 持有 GPU 显存与内部线程。建议在不再使用时显式释放有两种等价方式方式一调用close()from lmdeploy import pipeline pipe pipeline(internlm/internlm2_5-7b-chat) response pipe([Hi, pls intro yourself, Shanghai is]) print(response) pipe.close()方式二使用with上下文管理器from lmdeploy import pipeline with pipeline(internlm/internlm2_5-7b-chat) as pipe: response pipe([Hi, pls intro yourself, Shanghai is]) print(response)close()的实现pipeline.py会依次关闭内部事件循环线程internal_thread.close()与异步引擎async_engine.close()with语法则通过__enter__/__exit__pipeline.py在退出代码块时自动调用close()推荐在脚本化场景中优先使用。常见问题 FAQRuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase此错误出现在 PyTorch 后端且tp 1的多进程场景。请确保 Python 脚本中包含if __name__ __main__:原因在于多线程 / 多进程环境下初始化代码可能被每个新进程重复执行if __name__ __main__:可以保证初始化逻辑只在主程序中运行一次避免子进程在 fork 引导阶段未完成时再次触发进程启动。如何自定义 chat template请参考 chat_template.md其中详细介绍了 chat template 的注册与自定义流程。LoRA 权重带 chat template 怎么办如果 LoRA 的权重带有对应的 chat template可以先把该 chat template 注册到 LMDeploy之后直接用 chat template 名称作为adapter_name传入即可无需额外配置。小结lmdeploy.pipeline将模型下载、后端自动选择TurboMind / PyTorch、引擎实例化与异步调度全部封装进一个统一接口pipeline()负责初始化pipe()/stream_infer()负责批量与流式推理get_ppl()负责困惑度评估close()/with负责资源释放。围绕它本文覆盖了 K/V cache 显存比例的历史演进与调优、GenerationConfig全套采样参数、OpenAI 格式 prompt、logits 与 hidden states 导出、PyTorch 引擎切换、LoRA 推理以及常见报错排查。如需进一步探索可以继续阅读 pipeline.rstAPI 参考、pipeline.pyPipeline 实现与 messages.py全部配置类定义并结合 test_pipeline_func.py 等测试用例验证行为。赞分享人工智能大模型模型推理服务推理引擎本地部署模型量化【免费下载链接】lmdeployLMDeploy is a toolkit for compressing, deploying, and serving LLMs.项目地址https://gitcode.com/gh_mirrors/lm/lmdeploy点击查看免费下载相关推荐LangChain4j 实战使用 GoogleCloudStorageDocumentLoader 从 GCS 存储桶加载文档LangChain4j 实战使用 GoogleCloudStorageDocumentLoader 从 GCS 存储桶加载文档 本文以 LangChain4j人工智能大模型模型推理服务推理引擎本地部署模型量化InternLM/lmdeploy 大语言模型离线推理 Pipeline 使用指南InternLM/lmdeploy 大语言模型离线推理 Pipeline 使用指南 前言 在现代人工智能应用中大语言模型 LLM 的推理部署是一个关键环节。I人工智能大模型模型推理服务推理引擎本地部署模型量化EvoDiff vs 传统方法为什么离散扩散模型是下一代蛋白质设计的优选EvoDiff vs 传统方法为什么离散扩散模型是下一代蛋白质设计的优选 在蛋白质工程领域传统方法如结构预测模型如AlphaFold和基于模板的设计工MLOps机器学习后端工作流自动化AI Agent创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
02
RELATED NEWS

相关资讯

更多网站建设与数字化升级内容

03
WHY YAOTU

想打造同款高转化官网?

懂行业、懂生意,从建站到增长一站式陪跑

◈

场景化定制

不做模板站,围绕你的业务场景量身设计,小众不撞款。

◐

营销型架构

以转化目标组织内容与路径,让官网真正带来询盘。

▲

全周期服务

设计、开发、运营、运维一体,上线只是开始。

免费获取你的建站方案

留下需求,专属顾问 24 小时内为你输出方案建议。