Prhub

#48463 [Feat] Add Support for BertForMaskedLM to vLLM

原始 PR 作者 atalhens 合并时间 2026-07-14 04:56 文件变更 4 提交数 5 评论 3 代码增减 +158 / -2

执行摘要

添加 BertForMaskedLM 模型支持

PR body 指出:'vLLM currently supports BERT encoder models but does not support BertForMaskedLM, preventing Hugging Face masked language modeling checkpoints from being loaded and executed. This PR closes that gap so users can run MLM checkpoints directly on vLLM.'

该 PR 实现清晰,适合作为新模型集成的模板。权重映射和命名处理的细节值得关注。建议阅读 bert.py 中的 BertForMaskedLM 类实现和对应的测试。

讨论亮点

DarkLight1337 建议将新增的测试文件 test_mlm.py 合并到现有的 test_token_classification.py 中,以避免增加新文件。作者 atalhens 同意并执行。该讨论体现了对测试目录结构简洁性的关注。

实现拆解

  1. 定义模型类:在 vllm/model_executor/models/bert.py 中新增 BertForMaskedLM 类,使用 @attn_type('encoder_only')@default_pooling_type(tok_pooling_type='ALL') 装饰。类内部实例化 BertModel 骨干、BertMLMHead 和 token 分类池化器。hf_to_vllm_mapper 处理权重名称映射,包括丢弃 NSP head、处理 legacy LayerNorm 命名和 tied decoder 权重。
  2. 注册模型:在 registry.py_EMBEDDING_MODELS 字典中添加 'BertForMaskedLM': ('bert', 'BertForMaskedLM')
  3. 测试验证:在 test_token_classification.py 中添加 test_bert_for_masked_lm,比较 vLLM 与 Hugging Face 输出。
  4. 测试注册:在 tests/models/registry.py 中添加示例模型条目。
文件 模块 状态 重要度
vllm/model_executor/models/bert.py 模型层 modified 8.8
tests/models/language/pooling/test_token_classification.py 测试 modified 6.36
vllm/model_executor/models/registry.py 模型注册 modified 4.93
tests/models/registry.py 测试注册 modified 3.81

关键符号

BertForMaskedLM.__init__ BertForMaskedLM.forward BertForMaskedLM.load_weights BertForMaskedLM.embed_input_ids test_bert_for_masked_lm

分析完成后,这里会展示 LLM 生成的相对完整源码片段和详细注释。

评论区精华

测试文件位置调整 测试

DarkLight1337 建议将新增的 test_mlm.py 合并到现有的 test_token_classification.py 中,以避免增加新文件。

结论:作者同意,将测试移至 test_token_classification.py。 · 已解决

风险与影响

权重映射的正确性依赖于检查点命名规范,当前仅测试了 google-bert/bert-base-uncased,对于其他变体可能需要调整。MLM head 的 tied embedding 处理可能在某些检查点上不适用。新增代码仅影响 BertForMaskedLM 模型路径,不影响现有模型。

用户现在可以使用 vLLM 执行 MLM 任务,扩展了模型支持范围。影响范围局限于新增模型,现有功能不受影响。

新模型集成 检查点兼容性 单检查点测试 权重映射复杂性

关联 Issue

未识别关联 Issue

当前没有检测到明确关联的 Issue 链接,后续同步到相关引用后会出现在这里。

完整报告

参与讨论