公司动态
Intern-S2-Mobius开发者手册:从源码解析到自定义推理流程
Intern-S2-Mobius开发者手册从源码解析到自定义推理流程【免费下载链接】Intern-S2-Mobius-FP8项目地址: https://ai.gitcode.com/InternLM/Intern-S2-Mobius-FP8Intern-S2-Mobius是一款基于Mobius-v0架构构建的35B基础模型由Xtuner和LMDeploy实现。它创新性地将知识存储与推理计算分离通过全局共享的Memory和多Reasoner迭代查询机制实现了更高的推理效率和更强的任务性能。本手册将带您深入了解模型架构、核心功能及自定义推理流程帮助开发者快速上手并充分利用这一强大工具。模型架构解析知识与推理的分离革命核心创新Mobius架构的工作原理传统Transformer模型将知识存储和推理计算逐层绑定而Mobius架构通过以下设计实现了知识-推理分离全局共享Memory替代层绑定的FFN知识存储使所有Reasoner可访问统一知识空间多Reasoner机制多个推理单元迭代查询Memory并优化隐藏状态双向残差连接推理阶段可跨层访问知识突破传统前向传播限制这种架构带来两大原生能力反向残差连接Backward Residual Connection和动态潜在推理Dynamic Latent Reasoning使模型能在更少推理步骤中合成有用信息同时将部分 deliberation 过程内化减少对长可见思维链的依赖。图1推理效率对比 - Intern-S2-Mobius在保持强推理性能的同时提升请求吞吐量主要得益于更简洁的推理轨迹源码结构概览模型核心实现位于以下文件模型配置configuration_interns2_mobius.py核心架构modeling_interns2_mobius.py预处理processing_interns2_mobius.py关键类结构包括InternS2MobiusModel整合视觉和语言模型的主类InternS2MobiusDecoderLayer包含注意力和MLP的解码层InternS2MobiusGatedDeltaNet实现线性注意力的核心模块InternS2MobiusAttention多头注意力机制实现核心功能详解效率与性能的双重突破知识-推理解耦架构Mobius架构通过分离知识向量与推理算子使每个Reasoner能访问更广泛的知识空间。在modeling_interns2_mobius.py中InternS2MobiusGatedDeltaNet类实现了这一核心逻辑通过卷积和门控机制处理序列转换# 核心代码片段示意 class InternS2MobiusGatedDeltaNet(nn.Module): def forward(self, hidden_states, cache_paramsNone, cache_positionNone, attention_maskNone): # 卷积序列转换 mixed_qkv self.causal_conv1d_fn( xmixed_qkv, weightself.conv1d.weight.squeeze(1), biasself.conv1d.bias, activationself.activation ) # 门控delta规则处理 core_attn_out, last_recurrent_state self.chunk_gated_delta_rule( query, key, value, gg, betabeta, initial_stateNone )动态潜在推理Mobius通过循环潜在迭代在解码前优化连续隐藏状态这一过程在rot_pos_emb方法中实现def rot_pos_emb(self, grid_thw: torch.Tensor) - torch.Tensor: # 计算旋转位置嵌入 freq_table self.rotary_pos_emb(max_hw) # 获取频率表 # 生成位置坐标 row_idx block_rows[:, None, None, None] * merge_size intra_row[None, None, :, None] col_idx block_cols[None, :, None, None] * merge_size intra_col[None, None, None, :] # 计算嵌入 embeddings freq_table[pos_ids] # 查找旋转嵌入 return embeddings.flatten(1)这种机制使模型能动态分配计算资源对不同令牌进行差异化处理显著提升推理效率。图2Mobius与基线模型的平均输出长度对比 - Mobius能以更短的推理链完成相同任务卓越性能表现在各类基准测试中Intern-S2-Mobius表现出优异性能尤其在科学任务上有显著提升通用推理在MMLU Pro、SimpleQA等基准上超越Qwen3.5-35B科学任务在Biology-Instructions、Mol-Instructions等科学数据集上取得大幅提升推理效率实现近4倍的端到端推理加速同时减少输出长度图3通用和科学基准测试性能对比 - 每行中分数更高者以粗体显示快速上手环境搭建与基础部署环境准备首先克隆项目仓库git clone https://gitcode.com/InternLM/Intern-S2-Mobius-FP8 cd Intern-S2-Mobius-FP8推荐使用Python 3.8环境并安装必要依赖pip install -r requirements.txt模型加载与基础推理使用Transformers库加载模型进行基础推理import torch from transformers import AutoModelForImageTextToText, AutoTokenizer model_path internlm/Intern-S2-Mobius tokenizer AutoTokenizer.from_pretrained(model_path, trust_remote_codeTrue) model AutoModelForImageTextToText.from_pretrained( model_path, trust_remote_codeTrue, torch_dtypetorch.bfloat16, device_mapauto, ).eval() # 准备输入 messages [ {role: user, content: Give me a short introduction to Intern-S2-Mobius.} ] text tokenizer.apply_chat_template( messages, tokenizeFalse, add_generation_promptTrue, ) inputs tokenizer(text, return_tensorspt).to(model.device) # 生成输出 with torch.no_grad(): output_ids model.generate( **inputs, max_new_tokens512, do_sampleTrue, temperature0.8, top_p1, ) response_ids output_ids[0][inputs[input_ids].shape[-1]:] print(tokenizer.decode(response_ids, skip_special_tokensTrue))推荐采样参数为获得最佳结果建议使用以下采样参数top_p 1 top_k 50 min_p 0.0 temperature 0.8高级部署提升推理效率的关键策略使用LMDeploy部署推荐LMDeploy提供高效部署支持推荐使用MTPMulti-token Prediction推测解码# MTP推测解码部署推荐 lmdeploy serve api_server \ internlm/Intern-S2-Mobius \ --trust-remote-code \ --backend pytorch \ --tp 1 \ --speculative-algorithm qwen3_5_mtp \ --speculative-num-draft-tokens 4 \ --dtype bfloat16 \ --max-batch-size 64基础部署无MTPlmdeploy serve api_server \ internlm/Intern-S2-Mobius \ --trust-remote-code \ --backend pytorch \ --dtype bfloat16 \ --tp 1使用vLLM部署vLLM同样支持Intern-S2-Mobius的高效部署# MTP推测解码部署推荐 vllm serve \ internlm/Intern-S2-Mobius \ --trust-remote-code \ --tensor-parallel-size 2 \ --reasoning-parser qwen3 \ --enable-auto-tool-choice \ --tool-call-parser qwen3_coder \ --spec-method mtp \ --spec-tokens 4自定义推理流程深入模型内部理解推理过程Intern-S2-Mobius的推理流程主要包含以下步骤输入处理文本和图像输入分别通过语言模型和视觉模型处理位置嵌入计算3D位置嵌入以支持视觉-语言融合解码层处理交替使用全注意力和线性注意力层输出生成通过LM Head生成最终文本输出关键流程在InternS2MobiusForConditionalGeneration类的forward方法中实现def forward(self, input_idsNone, pixel_valuesNone, labelsNone, **kwargs): # 模型前向传播 outputs self.model( input_idsinput_ids, pixel_valuespixel_values, **kwargs ) # 计算logits hidden_states outputs[0] logits self.lm_head(hidden_states[:, slice_indices, :]) # 计算损失如有标签 loss self.loss_function(logitslogits, labelslabels) if labels is not None else None return InternS2MobiusCausalLMOutputWithPast( lossloss, logitslogits, past_key_valuesoutputs.past_key_values )实现自定义推理要实现自定义推理流程可继承InternS2MobiusPreTrainedModel并覆盖相关方法class CustomInternS2Mobius(InternS2MobiusPreTrainedModel): def __init__(self, config): super().__init__(config) self.model InternS2MobiusModel(config) # 添加自定义层或修改现有结构 def custom_forward(self, inputs): # 实现自定义前向逻辑 outputs self.model(** inputs) # 添加自定义处理 return outputs推理案例分析以下是一个线性代数选择题的推理对比案例展示了Mobius如何以更少的令牌完成相同推理图4Intern-S2-Mobius-35B与Qwen3.5-35B在线性代数选择题上的对比 - 两模型均选择正确答案选项C但Mobius使用更少令牌主要得益于消除重复推导和检查总结与展望Intern-S2-Mobius通过知识-推理分离架构在保持强大性能的同时实现了显著的推理效率提升。其核心优势包括知识-推理解耦全局共享Memory与多Reasoner机制高效推理近4倍端到端加速更短推理链强科学性能在生物、化学等科学任务上表现突出灵活部署支持LMDeploy、vLLM等多种高效部署方案随着模型的不断优化Intern-S2-Mobius有望在更多领域展现其潜力为开发者提供更强大、更高效的AI工具。通过本手册您已了解Intern-S2-Mobius的核心架构、部署方法和自定义推理流程。如需进一步深入建议查阅项目源码及技术报告探索更多高级特性和优化策略。【免费下载链接】Intern-S2-Mobius-FP8项目地址: https://ai.gitcode.com/InternLM/Intern-S2-Mobius-FP8创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考