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

LMDeploy 奖励模型推理指南:离线打分与 /pooling 在线服务部署实战

发布时间:2026/9/27 9:10:25

资讯中心
01
ARTICLE

LMDeploy 奖励模型推理指南:离线打分与 /pooling 在线服务部署实战

LMDeploy 奖励模型推理指南:离线打分与 /pooling 在线服务部署实战
人工智能大模型模型推理服务推理引擎本地部署模型量化【免费下载链接】lmdeployLMDeploy is a toolkit for compressing, deploying, and serving LLMs.项目地址https://gitcode.com/gh_mirrors/lm/lmdeploy点击查看免费下载奖励模型Reward Model是 RLHF/RLVR 训练链路中的关键组件用于为模型生成的回复输出标量质量分数。本文围绕 LMDeploy 对奖励模型的支持展开覆盖受支持的模型清单、离线pipeline.get_reward_score打分、在线lmdeploy serve api_server/pooling接口部署并深入源码解释得分头与分数计算原理。读完本文你将掌握在 LMDeploy 中完成奖励模型从加载、打分到 API 服务的完整实战方案并理解其背后的实现细节。一、支持的奖励模型一览LMDeploy 目前支持以下奖励模型详见 reward_models.mdModelSizeSupported Inference EngineQwen2.5-Math-RM72BPyTorchInternLM2-Reward1.8B, 7B, 20BPyTorchPOLAR1.8B, 7BPyTorch需要注意的关键约束推理引擎仅支持 PyTorch上表所有奖励模型都标注为PyTorch因此在启动引擎时无论是离线pipeline还是在线 API 服务都必须显式使用 PyTorch 后端即--backend pytorch或PytorchEngineConfig。Turbomind 引擎不支持奖励模型推理。架构白名单从源码看奖励分数接口对模型架构有明确校验。pipeline.py 中get_reward_score仅接受[InternLM2ForRewardModel, Qwen2ForRewardModel]两种架构其余架构会抛出ValueError。也就是说Qwen2.5-Math-RM 走Qwen2ForRewardModel路径InternLM2-Reward 走InternLM2ForRewardModel路径可以推断 POLAR 系列与 InternLM2 同源的检查点同样经由InternLM2ForRewardModel路径加载。二、实现原理得分头Score Head与推理链路奖励模型与普通因果语言模型的核心区别在于输出头它不输出词表上的 logits而是把最后一层隐藏状态映射为标量分数。LMDeploy 在 module_map.py 中注册了两种奖励模型架构其实现分别位于1. InternLM2ForRewardModelinternlm2_reward.py 复用InternLM2Model骨干在其上额外挂载一个v_head# 简化示意原文见 internlm2_reward.py self.model InternLM2Model(config, dtypedtype, devicedevice) self.v_head build_rowwise_linear(config.hidden_size, 1, biasFalse, dtypedtype, devicedevice)v_head是一个hidden_size - 1的线性层get_logits直接返回self.v_head(hidden_states)即每个 token 位置对应一个标量序列最终的奖励分数取最后一个 token 位置的输出。另外该实现会拒绝 vision embedding 输入InternLM2RewardModel does not support vision embedding因此不要向奖励模型传入图像等多模态输入。2. Qwen2ForRewardModelqwen2_reward.py 复用Qwen2Model骨干输出头是一个两层的 MLP# 简化示意原文见 qwen2_reward.py self.num_labels 1 self.score nn.Sequential( build_rowwise_linear(config.hidden_size, config.hidden_size, biasTrue, ...), nn.ReLU(), build_rowwise_linear(config.hidden_size, self.num_labels, biasTrue, ...), )get_logits返回self.score(hidden_states)同样对每个 token 位置输出 1 维标量。3. 分数计算链路无论是离线还是在线底层都汇聚到 async_engine.py 的async_get_reward_score其计算方式为logits await self.async_get_logits(input_idsinput_ids) logits [x.squeeze() for x in logits] scores [x[-1].cpu().item() for x in logits]即前向传播得到每个 token 的 logits形状为[seq_len]取序列最后一个 token 位置的标量作为整条对话的奖励分数。与之配套的 async_get_logits 在构造GenerationConfig时设置了max_new_tokens0PyTorch 后端与top_k1源码注释说明top_k1是必需的因为 PyTorch 引擎在奖励模型上进行 top-k 采样阶段会发生崩溃而奖励打分本质上只做一次前向不需要真实生成。三、离线推理pipeline.get_reward_score离线场景使用pipeline的get_reward_score接口一次调用即可得到标量分数。以下以internlm/internlm2-1_8b-reward为例示例源自 reward_models.md此处补充了完整注释与可运行细节from transformers import AutoTokenizer from lmdeploy import pipeline, PytorchEngineConfig model_path internlm/internlm2-1_8b-reward # 构造一条问题 参考答案的完整对话。 # 奖励模型需要为整个对话打分因此聊天模板必须以 assistant 的回复结尾 chat [ {role: system, content: Please reason step by step, and put your final answer within \\boxed{}.}, {role: user, content: Janet’s ducks lay 16 eggs per day. She eats three for breakfast every morning and bakes muffins for her friends every day with four. She sells the remainder at the farmers market daily for $2 per fresh duck egg. How much in dollars does she make every day at the farmers market?}, {role: assistant, content: To determine how much Janet makes from selling the duck eggs at the farmers market, we need to follow these steps:\n\n1. Calculate the total number of eggs laid by the ducks each day.\n2. Determine how many eggs Janet eats and bakes for herself each day.\n3. Find out how many eggs are left to be sold.\n4. Calculate the revenue from selling the remaining eggs at $2 per egg.\n\nLets start with the first step:\n\n1. Janets ducks lay 16 eggs per day.\n\nNext, we calculate how many eggs Janet eats and bakes for herself each day:\n\n2. Janet eats 3 eggs for breakfast every morning.\n3. Janet bakes 4 eggs for her friends every day.\n\nSo, the total number of eggs Janet eats and bakes for herself each day is:\n\\[ 3 4 7 \\text{ eggs} \\]\n\nNow, we find out how many eggs are left to be sold:\n\\[ 16 - 7 9 \\text{ eggs} \\]\n\nFinally, we calculate the revenue from selling the remaining eggs at $2 per egg:\n\\[ 9 \\times 2 18 \\text{ dollars} \\]\n\nTherefore, Janet makes 18 dollars every day at the farmers market.} ] tokenizer AutoTokenizer.from_pretrained(model_path, trust_remote_codeTrue) # 用聊天模板把消息列表转成字符串。 # 注意add_generation_prompt 必须为 False # 奖励模型要打分的是完整的问答对话而不是待续写的对话开头 # 因此不能像生成任务那样附加 assistant 生成提示符 conversation_str tokenizer.apply_chat_template( chat, tokenizeFalse, add_generation_promptFalse ) input_ids tokenizer.encode( conversation_str, add_special_tokensFalse ) if __name__ __main__: # 原文档示例中的 tp 为外部变量实际使用时请替换为具体整数 # 例如单卡为 tp1多卡张量并行可按 GPU 数量设置 tp 1 engine_config PytorchEngineConfig(tptp) with pipeline(model_path, backend_configengine_config) as pipe: score pipe.get_reward_score(input_ids) print(fscore: {score})关键 API 说明见 pipeline.pyget_reward_score(input_ids)的输入是token id 列表既可以传单个list[int]也可以传list[list[int]]批量。返回值为list[float]即使只传入一条序列返回值也是长度为 1 的列表。内部实现会先校验async_engine.arch是否属于[InternLM2ForRewardModel, Qwen2ForRewardModel]不属于则抛错随后把输入归一化为list[list[int]]调用async_get_logits做一次前向再取每条序列最后一个 token 的 logit作为分数。批量离线打分get_reward_score原生支持批量输入可直接对多条候选回复一次性打分适合在 RLHF 数据筛选中对同一问题的多个模型回复批量评分batch_ids [ tokenizer.encode(tokenizer.apply_chat_template(chat_a, tokenizeFalse, add_generation_promptFalse), add_special_tokensFalse), tokenizer.encode(tokenizer.apply_chat_template(chat_b, tokenizeFalse, add_generation_promptFalse), add_special_tokensFalse), ] with pipeline(model_path, backend_configPytorchEngineConfig(tp1)) as pipe: scores pipe.get_reward_score(batch_ids) # 返回与输入一一对应的分数列表 print(scores)四、在线推理API 服务与 /pooling 接口1. 启动服务奖励模型同样支持以 OpenAI 兼容 API 的方式对外提供打分服务PyTorch 后端lmdeploy serve api_server internlm/internlm2-1_8b-reward --backend pytorch服务默认监听0.0.0.0:23333。对于 72B 级别的 Qwen2.5-Math-RM可配合张量并行参数如--tp 8在多卡上加载。2. 通过 /pooling 获取奖励分数奖励模型使用/pooling接口而非/generate获取分数其输入格式与 Embeddings API 兼容参见 auxiliary.py 中的实现说明。最简单的调用方式curl http://0.0.0.0:23333/pooling \ -H Content-Type: application/json \ -d { model: internlm/internlm2-1_8b-reward, input: Who are you? }3. 请求协议字段根据 protocol.py 中的PoolingRequest定义请求体支持如下字段字段类型说明modelstr \| None模型名可从/v1/models查询缺省时使用引擎加载的模型名inputstr \| list[str] \| list[int] \| list[list[int]]待打分的输入支持纯文本、文本列表、token id 列表或批量 token id 列表encoding_formatfloat \| base64编码格式默认floatdimensionsint \| None可选维度userstr \| None可选用户标识服务端在 pooling 端点 中会把输入统一归一化为list[list[int]]字符串用tokenizer.encode分词list[str]逐条分词list[int]视为单条 token id 序列list[list[int]]直接作为批量。随后调用async_engine.async_get_reward_score批量打分。4. 响应格式响应遵循PoolingResponse结构{ id: pool-xxxxxxxx, object: list, created: 1700000000, model: internlm/internlm2-1_8b-reward, data: [ {index: 0, object: pooling, data: 0.83} ], usage: {prompt_tokens: 12, completion_tokens: 0, cached_tokens: 0} }data数组中的每个元素与input中的每一条输入一一对应data字段即该条对话的奖励分数usage记录了消耗的 prompt token 数。5. 批量打分示例与 Embeddings API 一致/pooling支持一次请求对多条候选回复打分适合作为在线批处理评分通道curl http://0.0.0.0:23333/pooling \ -H Content-Type: application/json \ -d { model: internlm/internlm2-1_8b-reward, input: [ This is the first candidate response to be scored., This is the second candidate response to be scored. ] }五、进阶配置与实践要点1. 引擎配置参数奖励模型离线与在线推理均使用 PyTorch 引擎常用配置参数见 PytorchEngineConfigtp张量并行度默认 1。72B 级别的 Qwen2.5-Math-RM 建议按 GPU 显存设置如tp8配合在线服务的--tp参数使用。dtype权重与激活的数据类型可选auto/float16/bfloat16auto会对 FP32/FP16 模型使用 FP16对 BF16 模型使用 BF16。session_len最大会话长度奖励打分是单次前向通常保持默认即可。cache_max_entry_countKV 缓存占空闲显存的比例默认 0.8奖励打分不生成新 token缓存占用很小。enable_prefix_caching前缀缓存开关由于打分是全量前向通常无需开启。2. 为什么取最后一个 token奖励模型把整条对话编码为固定维度的表征后通过得分头输出逐位置标量训练时通常只用最后一个位置的标量监督整条对话的好坏。因此 async_engine.py 中x[-1]的取值逻辑与训练约定一致——最后一个 token 位置的 logit 就是整条对话的奖励分数。这也是离线接口要求输入必须以assistant回复结尾的原因分数反映的是这条完整问答的质量。3. 常见问题tp未定义原文档示例代码中的tp是外部变量直接复制运行时需先赋值如tp 1否则会NameError。add_generation_prompt必须为False若设为True聊天模板会在对话末尾追加生成提示符相当于把待续写的 token 也纳入打分序列导致最后一个 token 位置不再是回复的收尾分数含义发生偏移。架构不在白名单若加载的模型架构不在[InternLM2ForRewardModel, Qwen2ForRewardModel]中get_reward_score与/pooling都会抛出ValueError: xxx is not in reward model list属于预期行为。不要用 Turbomind 后端奖励模型仅支持 PyTorch 引擎使用--backend turbomind或TurbomindEngineConfig无法正确加载得分头。六、小结LMDeploy 为奖励模型提供了一套完整的推理方案离线侧通过pipeline.get_reward_score一次前向完成打分在线侧通过lmdeploy serve api_server --backend pytorch暴露 OpenAI 兼容的/pooling接口二者底层共享同一条async_get_reward_score链路取序列末位 token 的得分头输出。当前支持 Qwen2.5-Math-RM72B、InternLM2-Reward1.8B/7B/20B与 POLAR1.8B/7B全部限定 PyTorch 引擎。无论是 RLHF 数据筛选、离线批量评分还是在线打分服务都可以直接基于上述方案落地。深入阅读 internlm2_reward.py、qwen2_reward.py 与 auxiliary.py 可获得更多实现细节。赞分享人工智能大模型模型推理服务推理引擎本地部署模型量化【免费下载链接】lmdeployLMDeploy is a toolkit for compressing, deploying, and serving LLMs.项目地址https://gitcode.com/gh_mirrors/lm/lmdeploy点击查看免费下载相关推荐在 vLLM-Omni 中部署与运行 ByteDance-Seed/BAGEL-7B-MoT全模态离线推理与在线服务实战指南在 vLLM Omni 中部署与运行 ByteDance Seed/BAGEL 7B MoT全模态离线推理与在线服务实战指南 本文基于 vLLM Omni 仓人工智能大模型模型推理服务多模态语音音频媒体生成本地部署PaddleHub LeViT-128S 图像分类模型实战指南从推理 API 到 Serving 在线服务部署PaddleHub LeViT 128S 图像分类模型实战指南从推理 API 到 Serving 在线服务部署 本文围绕 PaddleHub 中 levit_人工智能大模型微调模型推理服务PaddleHub PPLCNet_x0_25 图像分类模型实战从安装推理到 Serving 在线服务部署PaddleHub PPLCNet_x0_25 图像分类模型实战从安装推理到 Serving 在线服务部署 PPLCNet_x0_25 是百度基于 Intel人工智能大模型微调模型推理服务上一篇Kafka-UI终极Apache Kafka集群管理解决方案下一篇快速上手js-mindmap零基础创建思维导图的完整指南创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
02
RELATED NEWS

相关资讯

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

03
WHY YAOTU

想打造同款高转化官网?

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

◈

场景化定制

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

◐

营销型架构

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

▲

全周期服务

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

免费获取你的建站方案

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