Prhub

#31769 [Bugfix] Fix Cohere2MoeConfig import crash from huggingface_hub @strict

原始 PR 作者 arathi-hlab 合并时间 2026-07-22 08:56 文件变更 2 提交数 5 评论 5 代码增减 +149 / -57

执行摘要

修复 Cohere2MoeConfig 因 @strict 导致的导入崩溃

修复 issue #28233:当 transformers==5.3.0 配合 huggingface_hub==1.9.0 时,@strict 装饰器要求类必须是标准库 @dataclass,但 Cohere2MoeConfig 继承自 PreTrainedConfig 并非 dataclass,导致 import 时抛出 StrictDataclassDefinitionError,进而使 sglang.srt.configs 整体无法导入,阻塞 bench_one_batch 等工具启动。

值得精读。展示了如何将自定义配置从 dataclass+@strict 迁移至标准 PreTrainedConfig 模式,并揭示了子类 init 中赋值可能被父类 init 静默覆盖的常见陷阱。review 流程中的自动化工具和人工审核有效避免了隐患合并。

讨论亮点

在 review 中,gemini-code-assist 指出 use_cache 参数在 init 中被赋值但未传递给 super().init,导致父类覆盖为默认 True。mingfeima 确认该问题并引用 #28861。作者随后在 commit 099219f 中修复:在 super().init() 中显式传入 use_cache=use_cache,并新增 test_use_cache_false_preserved 测试。

实现拆解

  1. 移除 @strict 装饰器和相应的 try/except 导入逻辑,删除 post_init 方法。所有字段从类级改为 init 参数并显式赋值。
  2. init 中保留派生默认值:num_key_value_heads 默认为 num_attention_heads;layer_types 根据滑动窗口模式自动推导。
  3. 字段赋值后调用 super().init(),显式传递 pad_token_id、bos_token_id、eos_token_id、tie_word_embeddings 和关键的 use_cache(此前缺失)。
  4. 在 super().init() 后执行 RoPE 标准化(如存在),与原行为一致。
  5. 新增测试文件 test_cohere2_moe_config.py,包含 4 个测试用例,注册 CPU CI。
文件 模块 状态 重要度
python/sglang/srt/configs/cohere2_moe.py 配置层 modified 8.24
test/registered/unit/configs/test_cohere2_moe_config.py 测试 added 6.98

关键符号

Cohere2MoeConfig.__init__ Cohere2MoeConfig.__post_init__ TestCohere2MoeConfig.test_configs_package_imports TestCohere2MoeConfig.test_derived_defaults_num_key_value_heads TestCohere2MoeConfig.test_derived_defaults_layer_types TestCohere2MoeConfig.test_pretrained_config_kwargs_forwarded TestCohere2MoeConfig.test_use_cache_false_preserved

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

评论区精华

use_cache 参数未转发到 PreTrainedConfig.__init__ 正确性

gemini-code-assist review 指出 use_cache 参数在 __init__ 中被赋值但未传递给 super().__init__,导致父类将 self.use_cache 重置为默认值 True。mingfeima 确认该问题并引用 #28861。作者随后在 commit 099219f 中修复并添加了对应的测试。

结论:已修复:在 super().__init__ 中显式传入 use_cache=use_cache,并新增 test_use_cache_false_preserved 测试。 · 已解决

风险与影响

风险较低。主要考虑:执行顺序变化(super() 在字段赋值后、RoPE 标准化前),但字段已显式赋值,行为等效。若外部代码依赖 @strict 装饰器(极不可能),则本变更破坏兼容性,但仓库内无此用法。测试覆盖了主要路径。总体安全。

直接影响所有使用 Cohere2MoeConfig 的模型加载路径,修复导入崩溃 bug,bench_one_batch 等工具可正常启动。use_cache 参数从静默覆盖变为正确生效。重构后代码更符合 Transformers 标准,降低维护成本。无性能影响。影响程度:中度。

核心路径变更 配置解析变更

关联 Issue

#28233 [Bug] `StrictDataclassDefinitionError` when importing Cohere2MoeConfig

完整报告

参与讨论