Skip to content

[Hunyuan]: add Hunyuan Dense V1 causal language model support - #4767

Open
KissrainKlein wants to merge 12 commits into
PaddlePaddle:developfrom
KissrainKlein:feat/hunyuan-model
Open

[Hunyuan]: add Hunyuan Dense V1 causal language model support#4767
KissrainKlein wants to merge 12 commits into
PaddlePaddle:developfrom
KissrainKlein:feat/hunyuan-model

Conversation

@KissrainKlein

Copy link
Copy Markdown

本 PR 完成 Hunyuan Dense V1 从 Transformers 到 PaddleFormers 的迁移,包含组网、前向精度、前 10 token 生成对齐、GSM8K 训练 loss 曲线对比和模型单测验证。

1. 模型实现与注册

  • 新增 Hunyuan Dense V1 模型、配置和 tokenizer:
    • paddleformers/transformers/hunyuan/configuration.py
    • paddleformers/transformers/hunyuan/modeling.py
    • paddleformers/transformers/hunyuan/tokenizer.py
    • paddleformers/transformers/hunyuan/tokenizer_fast.py
  • 支持 hunyuan_v1_dense 配置识别,并完成 AutoConfigAutoModelAutoModelForCausalLM 注册。
  • 实现 Hunyuan GQA、DynamicNTK RoPE、KV cache、CausalLM、序列分类与 token 分类路径。

2. 前向精度对齐

  • 模型:Hunyuan-0.5B-Instruct
  • 使用 5 个中英文 prompt 对比 Transformers 与 PaddleFormers 的前向 logits。
  • 5/5 个样例 logits 均满足 rtol=1e-3, atol=1e-2allclose
  • 最大 logits 绝对误差:2.6464462e-05
  • 各样例 mean absolute difference 的平均值:1.9950181e-06

3. 生成前向进度对齐

相同权重、greedy decoding(do_sample=False)和 max_new_tokens=32 下,使用 5 个中英文 prompt 验证生成前向进度:

  • 前 10 个生成 token IDs 完全一致。
    case1:
    HF first 10 new token ids: [120029, 185, 3125, 270, 3890, 558, 14746, 507, 17687, 2842]
    Paddle first 10 new token ids: [120029, 185, 3125, 270, 3890, 558, 14746, 507, 17687, 2842]
    case2:
    HF first 10 new token ids: [120029, 185, 3125, 270, 3890, 14116, 58131, 1668, 292, 2733]
    Paddle first 10 new token ids: [120029, 185, 3125, 270, 3890, 14116, 58131, 1668, 292, 2733]
    case3:
    HF first 10 new token ids: [120029, 185, 56520, 11, 252, 2388, 316, 14053, 356, 252]
    Paddle first 10 new token ids: [120029, 185, 56520, 11, 252, 2388, 316, 14053, 356, 252]
    case4:
    HF first 10 new token ids: [120029, 185, 3890, 3030, 1115, 2150, 507, 16, 10, 16]
    Paddle first 10 new token ids: [120029, 185, 3890, 3030, 1115, 2150, 507, 16, 10, 16]
    case5:
    HF first 10 new token ids: [120029, 185, 3125, 270, 3890, 14116, 1824, 507, 7331, 12523]
    Paddle first 10 new token ids: [120029, 185, 3125, 270, 3890, 14116, 1824, 507, 7331, 12523]

4. 训练 loss 曲线对比

  • 数据:固定顺序 GSM8K canonical JSONL。
  • 训练:SFT、full finetuning、每卡 batch size=1、gradient accumulation=4、300 optimizer steps。
  • 对比对象:PaddleFormers 与 ms-swift;两端学习率合同已逐 step 核验。
  • 两端均拥有连续的 300 个 step 记录,所有 loss、学习率和差值均为有限数,无 NaN/Inf。
  • 最大学习率绝对差:4.2857143e-10
指标 PaddleFormers ms-swift / 对比结果
第 1 步 loss 2.3506793126 2.3583018780
第 300 步 loss 0.7751995468 0.9477578998
300-step 平均绝对 loss 差 - 0.1626918178

5. 模型单测

新增 tests/transformers/hunyuan/test_modeling.py,覆盖:

  • 基础前向和 attention mask;
  • CausalLM logits 与带 labels 的 loss;
  • 显式/隐式 position IDs;
  • KV cache 增量解码与完整前向最后一个 token logits;
  • GQA;
  • input_ids / inputs_embeds 等价前向;
  • 序列分类和 token 分类;
  • 通用 mixin 的配置序列化、forward signature、save/load、determinism、embedding resize 和 generation。

@CLAassistant

CLAassistant commented Jul 14, 2026

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@paddle-bot

paddle-bot Bot commented Jul 14, 2026

Copy link
Copy Markdown

Thanks for your contribution!

@Paddle-CI-Bot

Copy link
Copy Markdown

PaddleFormers Log Analysis

Run #29401755775 · Attempt 1

日志分析报告

流水线名称 问题标签 修复建议 日志片段
Unittest GPU CI HunyuanModel state_dict 形状不匹配 HunyuanModelTest 的 tiny config 中 num_attention_heads/num_key_value_heads/hidden_size 参数与 GQA 实现中 qkv_proj 合并维度计算不一致,需修正 HunyuanModelTester 的 tiny 参数(head_dim=hidden_size//num_attention_heads 保持整除),使 save/load 时权重 shape 吻合 报错代码
Unittest GPU CI torchcodec teardown KeyError video_utils.py:368 在 teardown 中 del sys.modules["torchcodec"],但该模块在环境中未实际加载过(torchcodec 未安装),应改为 sys.modules.pop("torchcodec", None) 报错代码
Unittest GPU CI SwanlabCallback get_run() 异常 SWANLAB_MODE=disabledswanlab.get_run() 会直接抛出异常而非返回 Noneintegrations.py:482 需先判断 disabled 模式跳过 get_run() 调用,或 catch RuntimeError 报错代码

失败的测试 case:

ERROR tests/trainer/test_trainer_visualization.py::TestSwanlabCallback::test_swanlabcallback
ERROR tests/transformers/hunyuan/test_modeling.py::HunyuanModelTest::test_save_load
ERROR tests/transformers/kimi_k25/test_processor.py::KimiK25ProcessorTest::test_video_frame_sampling
ERROR tests/transformers/qwen2_5_vl/test_modeling.py::Qwen2_5_VLIntegrationTest::test_model_tiny_logits_with_video
ERROR tests/transformers/qwen2_5_vl/test_processor.py::Qwen2_5_VLProcessorTest::test_apply_chat_template_video_frame_sampling
ERROR tests/transformers/qwen2_vl/test_vision_process.py::TestQwenVisionProcessing::test_fetch_video_with_paddlecodec
ERROR tests/transformers/qwen3_vl/test_modeling.py::Qwen3VLIntegrationTest::test_model_tiny_logits_with_video
ERROR tests/transformers/qwen3_vl/test_processor.py::Qwen3VLProcessorTest::test_apply_chat_template_video_frame_sampling
ERROR tests/transformers/qwen3_vl_moe/test_modeling.py::Qwen3VLMoeIntegrationTest::test_model_tiny_logits_with_video

= 1184 passed, 181 skipped, 13 warnings, 9 errors, 9 retried in 1163.21s =

根本原因分析:

PR 新增 Hunyuan Dense V1 模型,引入了三类问题:

  1. HunyuanModel test_save_loadHunyuanModelTester 的 tiny config 中 GQA 参数组合(num_key_value_heads=8,实际 GQA 合并后 qkv_proj.weight shape [hidden, num_kv_heads*3*head_dim])与模型实际运行时的 hidden_size 对不上,导致 save 出来的权重 shape 和重新实例化的模型期望 shape 不一致。
  2. torchcodec KeyError(7 个 case)video_utils.py teardown 逻辑中使用了 del sys.modules["torchcodec"] 硬删除,但 CI 环境未安装 torchcodec,模块从未被 import 进 sys.modules,故 teardown 必然 KeyError;这是此 PR 新增/修改 video_utils.py 引入的 bug。
  3. SwanlabCallback test_swanlabcallback:swanlab 新版本 API 中 get_run()disabled 模式下不返回 None 而直接抛 RuntimeErrorintegrations.pyif self._swanlab.get_run() is None: 未做异常兜底;此 case 重试后通过(flaky),优先级较低。

修复建议:

  1. video_utils.py teardown(必须修):

    # 修改 video_utils.py:368 附近
    # 原代码:
    del sys.modules["torchcodec"]
    # 改为:
    sys.modules.pop("torchcodec", None)
  2. HunyuanModelTester tiny config(必须修):检查 tests/transformers/hunyuan/test_modeling.pyHunyuanModelTester.__init__hidden_sizenum_attention_headsnum_key_value_headsintermediate_size 参数,确保满足:

    • hidden_size % num_attention_heads == 0
    • GQA 场景下 qkv_proj 合并权重 shape == [hidden_size, (num_key_value_heads * 2 + num_attention_heads) * head_dim],保证 save/load round-trip shape 一致。
  3. SwanlabCallback get_run() 兜底(建议修):

    # paddleformers/trainer/integrations.py:482
    try:
        run = self._swanlab.get_run()
    except RuntimeError:
        run = None
    if run is None:
        ...

🔍 准确性记录:请点击评论底部 😊 图标,选择 👍(准确)或 👎(有误),将自动记录到 CI 监控系统

🔄 每次 Re-run 后自动更新

@a31413510

Copy link
Copy Markdown
Collaborator

检查ci单侧报错
image

@a31413510

Copy link
Copy Markdown
Collaborator

建议在PaddleFormers/paddleformers/datasets/template/template.py中增加hunyuan模版,可参考:
register_template(
name="hunyuan",
format_user=StringFormatter(slots=["<|hy_User|>{{content}}<|hy_Assistant|>"]),
format_assistant=StringFormatter(slots=["{{content}}", {"eos_token"}]),
format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
)

@a31413510

Copy link
Copy Markdown
Collaborator

paddleformers/transformers/glm4/modeling.py和tests/transformers/glm4/test_glm4.py中的所有中文注释都需要改成英文或者直接删除

@risemeup1111 risemeup1111 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已复查,当前还有需要修正的阻塞点,细节都在行内评论里。另有一条非行级的范围建议:

  • P3 优先级:P3 非行级:glm4 目录也被带进了这次 diff,但 auto/configuration.py / auto/modeling.py / 顶层导出还没接上,和当前标题/描述的 Hunyuan 范围也不一致。请确认这部分是否要一起合入;如果要合入,请补齐注册和说明,否则建议拆到独立 PR。处理要求:请针对该评论进行回复(同意并已修改请回复 Done,不同意请说明理由)。
Powered by Nyanpasu with gpt-5.5 xhigh, please check the suggestions carefully.



# Exact Hugging Face architecture name used by Hunyuan Dense V1 checkpoints.
HunYuanDenseV1ForCausalLM = HunyuanForCausalLM

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 优先级:P1
这里目前只补了 HunYuanDenseV1ForCausalLM,但 auto/modeling.py 会按最长前缀把 HunYuanDenseV1ForCausalLM 解析成 HunYuanDenseV1Model。现在这个别名不存在,所以 AutoModel.from_pretrained() 遇到 Hunyuan Dense V1 checkpoint 时会直接找不到类。处理要求:请针对该评论修复并提交新的 commit。

建议至少补一个:

HunYuanDenseV1Model = HunyuanModel

如果还要支持 pipe / 任务头,再在对应类定义后补同名 alias。

Comment on lines +184 to +190
"hunyuan.modeling": [
"HunyuanModel",
"HunyuanPretrainedModel",
"HunyuanForCausalLM",
"HunYuanDenseV1ForCausalLM",
"HunyuanForCausalLMPipe",
],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 优先级:P2
这里的顶层 lazy import 还是只暴露了基础模型和 CausalLM,HunyuanForSequenceClassification / HunyuanForTokenClassification / HunyuanSentenceEmbedding 仍然无法从 paddleformers.transformers 直接导入。既然这次 PR 已经新增了这些类,建议把它们也加进顶层导出;paddleformers/transformers/hunyuan/__init__.py 里最好同步一份。处理要求:请针对该评论进行回复(同意并已修改请回复 Done,不同意请说明理由)。

Suggested change
"hunyuan.modeling": [
"HunyuanModel",
"HunyuanPretrainedModel",
"HunyuanForCausalLM",
"HunYuanDenseV1ForCausalLM",
"HunyuanForCausalLMPipe",
],
"hunyuan.modeling": [
"HunyuanModel",
"HunyuanPretrainedModel",
"HunyuanForCausalLM",
"HunYuanDenseV1ForCausalLM",
"HunyuanForCausalLMPipe",
"HunyuanForSequenceClassification",
"HunyuanForTokenClassification",
"HunyuanSentenceEmbedding",
"HunyuanForCausalLMFleet",
"HunyuanForCausalLMPipeFleet",
],

@a31413510

Copy link
Copy Markdown
Collaborator

需要解决代码冲突
image

@a31413510

Copy link
Copy Markdown
Collaborator

需要解决代码冲突

class HunyuanForCausalLMPipe(HunyuanForCausalLM):
config_class = HunyuanConfig
_decoder_layer_cls = HunyuanDecoderLayer
_get_tensor_parallel_mappings = HunyuanModel._get_tensor_parallel_mappings

@risemeup1111 risemeup1111 Aug 19, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P0 优先级:P0

这里在模块导入阶段读取 HunyuanModel._get_tensor_parallel_mappings,但该方法既没有在 Hunyuan 模型中定义,也不在 PretrainedModel 基类中提供。因此加载 paddleformers.transformers.hunyuan.modeling(包括顶层 lazy import 首次访问 Hunyuan)会在类定义时直接抛出 AttributeError,整个 Hunyuan 实现无法导入。请为 HunyuanModel 实现实际的 tensor-parallel mapping(并覆盖所需权重布局),或移除该引用并提供正确的 pipe 映射。

@risemeup1111 risemeup1111 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

序号 位置 优先级 状态
1 hunyuan/modeling.py:1236 P0 🚧
2 hunyuan/modeling.py:1230 P1 🚧
3 transformers/init.py:211 P2 🚧
Powered by Nyanpasu with gpt-5.5 xhigh, please check the suggestions carefully.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants