Skip to content

feat(xing_4): 复用 Hugging Face Xing4 与公共训练组件 - #1439

Closed
xingleixu123 wants to merge 8 commits into
mindspore-ai:masterfrom
xingleixu123:codex/xing40-official-hf-20261103
Closed

xingleixu123 wants to merge 8 commits into
mindspore-ai:masterfrom
xingleixu123:codex/xing40-official-hf-20261103

Conversation

@xingleixu123

@xingleixu123 xingleixu123 commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

/kind feature

What does this PR do / why do we need it:

为官方 Xing4 增加训练与并行接入。三个官方 Python 文件保留原名和原始内容,位于 xing_4/transformer;HP 在 adapter 中继承官方模型,只补训练目标、精度策略和公共高性能组件所需的接口,通过现有 builder、provider 和 plan_overrides 接入。

本次逐条重新核对全部 29 个检视线程及 Conversation 意见,追加第 7 个 commit fdce1a9,保留此前 6 个提交和原检视记录。增量 8 个文件,+258/−343:

  • 配置解析并入 builder,MoE/Router/MLP 训练接线并入 training.py,删除两个只承载这些接线的文件。
  • 直接保留官方 mHC 对象和参数身份,在 decoder 设置训练 norm epsilon;删除随后必被融合替换的中间包装及其重复初始化。融合 pre/post 仍由 plan_overrides 和公共算子执行,保留第四项 residual 的反向链。
  • 删除重复的模型类型检查;保留构建后全部 mHC 必须命中融合计划的检查。训练入口不支持绕过 builder 执行未替换 decoder。
  • EP 复用公共 expert-major 接口,检查接口能力而非绑定具体 GroupedExperts 类。当前配置继续使用 grouped GEMM;未新增不完整的逐专家 EP 开关。
  • 撤回公共 _precision.py 的纯文档差异,继续直接复用已有函数。官方 HF 文件、Muon 更新数学、MTP/CP 语义和并行计划均保持。

保留必要的专家打包及可逆 checkpoint 映射:公共 GroupedExperts 目前接收打包参数,不能直接消费官方 ModuleList;转换必须检查布局、激活、参数别名及不可迁移的状态。尺寸已经从实际 weight.shape 推导。#1407 的 Experts 接入仍在途,不把它当成当前已验证的替代方案。

保持公共 MTP、MLA/CP runtime、GroupedExperts、SwiGLU、RecomputePolicy、MoE monitor 和框架 Muon 的复用。原 #1425 的公共 MLA CP 改动已在本 PR 内,不再单独合入;QKClip 使用 Muon 叶优化器原生 post hook,不依赖 #1455。

Which issue(s) this PR fixes:

关联 #1466、#1464、#1456、#1395、#1397、#1459。

总跟踪为 hf1s#353,依赖与无需单独合入的 PR 已在置顶表中按优先级和依赖列出。#304 保持不变。

Test Plan and Test result:

正式模型 head fdce1a9a;统一复合运行源码 manifest 7dd9613c60843e646e15f6bb9879f477c201d63824793859e5386bd8059d8f4f,不是裸master。包含 #1470、#1410 + dz-ssk#7 及已记录冻结依赖;完整归属与条件项见总issue置顶表。

  • 单卡MF→HP完整1000步通过:从MF1500完整训练状态恢复,独立训练1501–2500。LOSS / raw MTPLOSS signed mean为 −0.0001479853 / −0.0000119462,abs(mean)均≤0.005;正负步数为470/530、490/510。恢复张量、优化器槽、61个FP32别名和8000个实际样本字段通过;HP2500最终checkpoint独立读回通过。
  • 四卡完整1000步通过:FSDP replay、EP2、CP2DP2、TP2CP2和仅主干重计算均独立恢复同一连续FSDP1500,训练1501–2500;每项LOSS/MTPLOSS均满足均值阈值并出现正负。各rank样本、CP分片/TP副本、全局重分片或同布局恢复、学习率和有限梯度核对通过。
  • 四卡主要参照是冻结e401组合的连续0–2500 FSDP;当前fdce FSDP为独立1501–2500 replay,不声称新fdce连续基线。另有当前各配置相对当前FSDP replay的同版本对照,统计单列。
  • CPU真实provider/replacement、HF部分加载、Muon hook、公共MLA callback及共享实际state的decoder前后向检查完成。CPU mHC桩仅验证接线,完整NPU训练验证实际算子。独立4进程Gloo目标/梯度参考含空CP分片,不代替真实NPU FSDP。
  • 去掉重复初始化会改变同seed冷启动随机消费;正式回归共享实际checkpoint,没有复刻旧随机或累加轨迹。官方三文件不变,未新增库内UT/ST或固定YAML。
  • 当前head CLA通过,review/外部CI仍待完成;精度通过不等同CI绿色。带采样且并发的运行不作为新性能结论。

完整统计、代码处置、实际配置边界及12张网站图 · 合入顺序与不需合入项。

Code review checklist [illustration]:

  • whether to verify the function's return value (It is forbidden to use void to mask the return values of security functions and self-developed functions. C++ STL functions can be masked if there is no problem)
  • Whether to comply with SOLID principle / Demeter's law
  • Whether there is UT test case && the test case is a valid (if there is no test case, please explain the reason)
  • Whether the API change is involved
  • Whether official document modification is involved

按用户要求,本轮 PR 仅保留逻辑代码;已执行的测试证据单独归档。

@xingleixu123
xingleixu123 force-pushed the codex/xing40-official-hf-20261103 branch from da06b7f to d6fe53a Compare November 3, 2026 12:02
@xingleixu123
xingleixu123 force-pushed the codex/xing40-official-hf-20261103 branch from d6fe53a to a92f507 Compare November 3, 2026 23:35
@xingleixu123 xingleixu123 changed the title feat(xing40): 复用官方 Xing4.0 并保留 MF 训练语义 feat(xing40): 复用官方模型并适配训练语义 Nov 3, 2026
@xingleixu123
xingleixu123 force-pushed the codex/xing40-official-hf-20261103 branch from a92f507 to 284f79b Compare November 4, 2026 00:07
@xingleixu123 xingleixu123 changed the title feat(xing40): 复用官方模型并适配训练语义 feat(xing4): 复用官方模型并适配训练语义 Nov 4, 2026
@@ -0,0 +1,286 @@
# Copyright 2026 Huawei Technologies Co., Ltd

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

为什么需要这个文件,没有已有的实现吗?或者已有的实现能少量修改吗

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

已删除独立 grouped_experts.py,将 MLA/GMM 替换与权重转换集中在 adapter/conversion/module_replacement.py。专家执行继续复用公共 GroupedExperts;仅保留官方 ModuleList 到共享打包参数的转换、可逆 checkpoint 映射及必要接口签名适配。真实配置命中主干和 MTP 两处专家,恢复回归通过。

对应本轮 14d9ccce。保留原线程供继续检视。

# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

你重计算为什么需要一个文件。你看下库上dsv41咋做的相关的,是不是少量修改,尽可能复用库上能力

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

已删除独立重计算适配文件,使用库上的 RecomputePolicy(region_patterns) 声明 model.layers.* / mtp.layers.*,由共享调度实现重计算。

对应本轮 14d9ccce。保留原线程供继续检视。

from torch import nn
from transformers import PreTrainedModel
from transformers.models.deepseek_v4.modeling_deepseek_v4 import (
DeepseekV4HyperConnection,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

类似这样的 为什么没有导入trans的xing,然后一些embedding类似继承的是xing4XXX

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

底座使用本地保留的官方 Xing4_0Config、Xing4_0Model、Xing4_0ForCausalLM 及官方注意力、MLP、路由模块,HP 训练实现继续继承这些 Xing4 类,没有改用 DSV3 底座。按此前原源码不改的要求,官方文件保持原名原始字节;训练接线集中到模型目录 modeling_xing_4.py。

对应本轮 14d9ccce。保留原线程供继续检视。

"""Create subclasses once per official module, without changing its globals."""

class Xing4RotaryEmbedding(reference.Xing4_0RotaryEmbedding):
"""Official rotary execution with the recipe's derived FP32 frequency buffer."""

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

类似不应该有reference的前缀? 然后你看下是不是有比较多的能继承

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

已移除 reference 前缀和空构造包装,直接继承官方 Xing4 类;配置构建沿用共享 HyperAutoModelForCausalLM,不再增加下载/固定 revision 入参。

对应本轮 14d9ccce。保留原线程供继续检视。

@xingleixu123 xingleixu123 changed the title feat(xing4): 复用官方模型并适配训练语义 feat(xing_4): 复用官方 Xing4 与公共训练组件 Nov 4, 2026
@xingleixu123
xingleixu123 force-pushed the codex/xing40-official-hf-20261103 branch 4 times, most recently from 1c81d02 to bdef8fa Compare November 4, 2026 04:19
@xingleixu123
xingleixu123 force-pushed the codex/xing40-official-hf-20261103 branch from bdef8fa to 6617529 Compare November 4, 2026 06:05
@xingleixu123
xingleixu123 force-pushed the codex/xing40-official-hf-20261103 branch 2 times, most recently from 39b0425 to de53874 Compare November 4, 2026 07:45
@xingleixu123 xingleixu123 changed the title feat(xing_4): 复用官方 Xing4 与公共训练组件 feat(xing_4): 复用 Hugging Face Xing4 与公共训练组件 Nov 4, 2026
@xingleixu123
xingleixu123 force-pushed the codex/xing40-official-hf-20261103 branch from de53874 to 3d013f2 Compare November 4, 2026 09:23
# Copyright 2026 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

我们也有啊 为啥要写这么多呢 到底改什么了。为啥不能用我们的 或者提供的modeling 4那个文件,为啥要修改,修改也应该很少啊

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

已移除 adapter/moe 和 adapter/runtime 目录,将 router/MoE/MLP/MTP 的训练接线集中到模型目录;删除额外专家容器及未使用的 hash/固定路由支线。learned Top-K 直接调用官方实现,执行复用公共 MLA、GroupedExperts、SwiGLU、MTPLayer。剩余差异是训练辅助目标与状态、精度策略、mHC/MTP 训练接线及 EP/CP 接口。

对应本轮 14d9ccce。保留原线程供继续检视。

"""
# The shared kernel contracts the source axis first. Convert the
# Megatron destination-first matrix at this layout boundary.
if self.megatron_compatibility:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

为啥还有这种写法,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

已删除 MF 专用兼容开关。官方 Xing4 定义 H_res @ streams;共享 post 算子使用 source-first 布局,因此仅在接口边界转置。非对称矩阵的独立数学参考验证了输出和四项输入梯度,不再依赖 MF 特制算术。

对应本轮 14d9ccce。保留原线程供继续检视。

@@ -0,0 +1,5 @@
# Preserve upstream bytes for the four bundled Xing4 source artifacts.
config.json -text whitespace=cr-at-eol,-blank-at-eol,-blank-at-eof

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

没必要的删掉啊

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

已删除 .gitattributes。官方三个 Python 文件的 Git blob 与构建产物均核验原始 SHA256,未修改源码内容或文件名。

对应本轮 14d9ccce。保留原线程供继续检视。

Comment thread setup.py Outdated
],
'hyper_parallel.auto_parallel': ['op_profiles/*.yaml', 'op_records.yaml'],
'hyper_parallel.models.deepseek_v3': ['recipes/*.yaml'],
'hyper_parallel.models.xing_4': ['config.json'],

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

没必要的删掉啊

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

已移除 setup.py 增量,使用库上现有打包规则。三个官方 Python 文件已实际构建并逐一核验 SHA256;固定 config.json 也已按新意见移到仓库外。

对应本轮 14d9ccce。保留原线程供继续检视。

@Cui-yshoho

Copy link
Copy Markdown
Contributor

可以把GroupedExperts权重转换统一放到module_replacement.py

h_res: torch.Tensor,
num_stream: int,
*,
use_fused: bool = True,

@Cui-yshoho Cui-yshoho Nov 4, 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.

这里不需要修改,后续非融合计划删除

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

已撤回本 PR 对共享 mhc_post.py 的修改,该文件与目标 master 完全一致。模型直接调用现有接口,NPU 使用融合路径;本轮不新增非融合开关。

对应本轮 14d9ccce。保留原线程供继续检视。

@Cui-yshoho

Cui-yshoho commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor
  • 看了一下,感觉可以以modeling_xing4_0.py为主体完成训练接入,将router、moe、mlp等训练逻辑放在模型实现中,减少 adapter中的子类包装。高性能模块替换及权重转换集中在module_replacement.py,ep等继续放在distributed里。
  • 基本顺序就是我们以 https://huggingface.co/XingChen-AGI/Xing4.0-29B-A4B/blob/main/modeling_xing4_0.py 为基础,然后把这个改为能够训练接入,作为hyper models下的modeling_xing4_0.py ,这样可以减少adapter适配;然后我们再做一些权重转换、并行适配之类的。
  • 另外我们其实和deepseekv4很像的。https://mp.weixin.qq.com/s/tSUxd6ia2fqwMRNXKkQJDw , 所以类似config.json、tokenizer.json和tokenizer_config.json,可以让用户提前下好模型资产 不需要放到hyper上

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.

这个别加进代码仓里,这是具体的模型规格,应该是类似ckpt那样放在外面供hyper-parallel去读取的

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

已从代码 PR 移除固定 config.json,原文件作为外部模型资产独立归档。HP 训练配方传入等价模型字段,不要求配置 key/value 与 MF 字面一致。

对应本轮 14d9ccce。保留原线程供继续检视。

@xingleixu123
xingleixu123 force-pushed the codex/xing40-official-hf-20261103 branch from 3d013f2 to 14d9ccc Compare November 4, 2026 10:54
@xingleixu123

Copy link
Copy Markdown
Contributor Author

已按这两条建议合并结构:GroupedExperts 权重转换和 MLA 高性能替换统一到 adapter/conversion/module_replacement.py;router/MoE/MLP/MTP 的训练接线移到模型目录,EP 继续在 adapter/distributed。删除共享 mHC 修改、固定 config.json、setup.py 增量与 .gitattributes,文件数 26→17,净删 264 行。

按任务此前明确的“官方源码原名原样保留”要求,官方 modeling_xing4_0.py 保持字节不变,HP 训练入口位于相邻的 modeling_xing_4.py,继续继承官方构造和模块;没有把整套模型重写在 adapter 内。

CPU 两组前后向 364 项张量逐位一致,复用 18 tests / 20 subtests 通过;125 卡 5 的真实 MF5→HP6–10 恢复短跑通过。完整 1000 步报告保留原冻结版本归属,本轮不把短跑当成新的完整验收。原有评论与 review 均保留,未自动解决线程。

@xingleixu123

Copy link
Copy Markdown
Contributor Author

已复核1105 README新增第零章,追加e4013cfb(4文件+11/−14),原五个提交及检视保留。

确认并修复了实际部分加载缺陷:直接Tensor.zero_/fill_会绕过HF初始化保护,覆盖同模块已加载router bias和mHC状态;改用现有nn.init,见#1466。同seed随机初始化逐项一致,已提供非零计数仍保留。FP32 helper直接复用原名,去掉额外别名。

计数持久性继续保留。正常成功步保存常为零,但非持久化会改变旧DCP schema并丢弃非零计数;已有MF1500和FSDP step5恢复不能当作官方HF冷启动证据。进一步定位到公共loader会把ignore-missing同时当成免初始化,独立草稿#1468(#1467)修复此共性问题,未混入本模型PR。

SwiGLU非空策略继续依赖并复用#356,#1420仅为导出调整。当前partial检查是固定实现的过渡保护,不是通用能力协议;不重复增加一套激活实现。透明forward保留并补充必要签名说明。

逐项判断、原始输出与源码绑定。本模型CPU24项/14子测试、受控卡5专项22项完成;公共loader有单独CPU及NPU before/after。新HF部分加载测试先CPU加载后转NPU,公共loader补测才在NPU张量上初始化,范围已区分。

本轮不重跑完整训练、四卡100步或吞吐测量,旧数值曲线保留原提交归属;官方HF完整冷启动仍有MTP权重边界,未宣称全部打通。未新增库内UT/ST,外部证据不等同CI绿色。总跟踪hf1s#353已更新优先级和条件依赖。

@xingleixu123

Copy link
Copy Markdown
Contributor Author

/check-pr

module.ep_executor = build_ep_compute(
module, ep_mesh, router_fn=type(module).route, archetype_key="xing4",
expected_attrs=["gate", "experts", "shared_experts"], combine=SHARED_MERGE_MODES["none"],
use_grouped_gemm=True, fix_router=fix_router)

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.

这里isinstance(module.experts, GroupedExperts)和写死use_grouped_gemm=True会导致moe部分强制走grouped_gemm分支。
如果期望仅保留该分支,则直接在modeling里面实现grouped-gemm版本,并删除这里的配置;如果希望保留for-loop专家计算版本做精度比对基线,则删除这里的校验,use_grouped_gemm改为可配置参数

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

非 EP 路径继续保留 HF ModuleList 循环。EP 当前只承诺已验 grouped 路径,检查改为公共 forward_expert_major 能力而非具体类名;公共非 grouped loop 要求另一套 stacked 权重布局与加载契约,本次不新增未经完整验证的开关。

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.

如果不看护非grouped loop分支,在modeling_xing4_0.py中的MoE部分请直接按照grouped-GEMM实现

return query, key, value


def _expert_weights(module: nn.Module) -> tuple[Any, list[tuple[nn.Parameter, nn.Parameter, nn.Parameter]]]:

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.

这里是否有必要添加一个大函数做校验和weight打包?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

目前这部分除打包外还验证来源专家、共享权重、hooks/buffer、shape 和激活策略,并提供可逆 checkpoint 映射;矩阵执行仍复用公共 GroupedExperts。现有公共 EP 能力尚不覆盖全部 ModuleList 转换契约,后续可随公共能力成熟再收敛。

return config, weights


def _validate_expert_weights(

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.

这里为什么不是直接从weight的shape里面读取hidden_size, intermediate_size

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

目前 _validate_expert_weights 已从第一组 gate weight 的 shape 读取 intermediate_size 和 hidden_size,再对配置及其他专家权重做一致性检查,避免不一致时静默打包。


from collections.abc import Callable, Iterable

import torch

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

这个文件不应该改

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

已在 fdce1a9 回退 _precision.py 的文档差异,该公共文件相对本 PR 原基线不再有改动;训练侧继续复用既有 helper。

#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

这个文件应该放在training.py

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

已在 fdce1a9 将 Router、MLP 和 MoE 训练适配合并到 training.py,旧 moe.py 已删除;其余 import 与 provider 已同步调整。

合并配置入口与 MoE 训练接线,直接复用官方 mHC 对象,移除重复初始化包装。
保留融合替换、专家转换、MTP/CP 归一化及原生 Muon hook 的必要契约。
撤回公共精度 helper 的纯文档差异,不改官方 HF 源码。
@xingleixu123

Copy link
Copy Markdown
Contributor Author

/check-pr

@xingleixu123

Copy link
Copy Markdown
Contributor Author

本轮追加commit fdce1a9(8文件 +258/−343),原6个提交及全部检视意见保留,29个thread逐项复核,14条补充回复已发布,未自动resolve检视。

单卡MF1500→HP1501–2500完整1000步、四卡FSDP/EP2/CP2DP2/TP2CP2/仅主干重计算各1000步已完成并独立复算通过;LOSS与raw MTPLOSS各自abs(mean signed delta)≤0.005,正负自然出现。恢复、实际样本、日程、全窗口和最终单卡checkpoint读回证据已核验。详情包含MAE/最大差/正负数及可复算CSV。

完整证据与网站图片;总跟踪 hf1s#353 已按优先级和依赖区分待合入、已吸收、已合入及条件PR。正式运行是manifest 7dd9613c…的复合源码,不是裸master;当前FSDP是从连续基线1500恢复的replay。PR仍Draft,CI/检视批准单独等待。

@xingleixu123

Copy link
Copy Markdown
Contributor Author

/check-pr

__all__ = ["Xing4MLAAttention", "Xing4GroupedExperts", "Xing4FusedHyperConnection"]


def fusion_attention_with_logit_maxima(module: nn.Module, query: torch.Tensor, key: torch.Tensor,

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.

开源的代码推理Xing4_0Attention 是不需要max-logits的
所以这似乎是训练的必须语义?

or not math.isfinite(value):
raise ValueError(f"{name} must be finite")
elif value < 0 and name != "mhc_init_gating_factor":
raise ValueError(f"{name} must be nonnegative")

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.

这校验是不是有点非必要

]


def _load_replacements():

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.

但是代码里面没有地方引用到

counts.zero_()


class Xing4MLP(Xing4_0MLP):

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.

这个写法似乎有点问题:
expert里面,因为mlp.expert本来就要被grouped GEMM 替换
剩下dense层和shared_experts里面要用swiglu的 可以靠plan overrides做
这也导致了module replacements里面 _expert_weights进行了额外的奇怪校验

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.

特别是要合并training和module_replacement之后



@register_module_replacement
class Xing4GroupedExperts(GroupedExperts):

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.

因为框架的 GroupedExperts.init 收的是"已经打包好"的源,而这里的源是 64个独立专家的 nn.ModuleList
所以需要这一套

self.gate_proj, self.up_proj, self.down_proj = source.gate_proj, source.up_proj, source.down_proj
# Only the optional clipped/compute-dtype policy needs the extended SwiGLU API.
from hyper_parallel.components.functional.activation_swiglu import ( # pylint: disable=import-outside-toplevel
swiglu_from_projections,

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.

放开头

counts.zero_()


class Xing4MLP(Xing4_0MLP):

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.

特别是要合并training和module_replacement之后



@torch.no_grad()
def initialize(owner: Any, module: nn.Module) -> None:

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.

源代码写法 我们重写了这两个module

将 MLA、融合 mHC 和分组专家的替换并入 adapter/training.py,移除 conversion 目录和冗余注册。Dense 和共享专家复用计划中的 SwiGLUMLP,路由专家直接打包官方 ModuleList,保留 checkpoint 双向映射。

精简固定配方的配置和权重检查,保留标签对齐、CP 归约组、Muon 逻辑矩阵布局及 QK 投影归属约束。

将 torch_npu 导入移至模块顶部,CP RoPE 复用公共 functional 接口。仅在训练启用 Muon QK clipping 时累计逐头最大值,由 Muon 的 step 后钩子消费并清空。
else:
normalized = (scores / (scores.sum(dim=-1, keepdim=True) + 1e-20)).reshape(
batch_size, -1, self.num_experts)
group = self.aux_loss_cp_group

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.

开了TP 和 EP的场景下会漏掉TP域的同步,即获取的不是完整序列

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

拿到完整序列计算

return getattr(config, "swiglu_limit", None), getattr(torch, dtype) if isinstance(dtype, str) else dtype


@module_replacement

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.

还需要molude replacement吗
似乎训练就应该直接确定使用/or not

carrier.train(module.training)
super().__init__(module=carrier, module_fqn=module_fqn, context=context)

def forward(self, *args: torch.Tensor, **kwargs: torch.Tensor) -> torch.Tensor:

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.

这个写法有点奇怪?

def __init__(self, optimizer: Any, config: Any, adapter_factory: AdapterFactory) -> None:
"""Wrap a leaf with its family adapter and independent transfer runtime."""
# The pipeline calls adapter updates directly, bypassing the leaf's step hooks.
if optimizer._optimizer_step_pre_hooks or optimizer._optimizer_step_post_hooks:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

祥宇&佳琪后续考虑正式方案

for name, buffer in module.named_buffers(recurse=False, remove_duplicate=False)
if name in getattr(module, "fp32_buffer_names", ())
}
mismatched.extend(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

尝试给这个回退,model inint dtype 用 fp 32。优化器有个配置 main_param == fp32;model inint dtype直接删掉

"""
target_dtype = _resolve_model_init_dtype(model_init_dtype)
if target_dtype is None:
return

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

直接干掉



@method_replacement
def xing4_cp_mean_loss(*, module: nn.Module, method_fqn: str,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@townwish4git 下来确认下

if not callable(getattr(module.experts, "forward_expert_major", None)):
raise ValueError("Xing4 EP requires an expert-major module replacement before binding the executor")
module.ep_executor = build_ep_compute(
module, ep_mesh, router_fn=type(module).route, archetype_key="xing4",

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

既然是特定模型,直接这个文件不要。改在modeling中

else:
normalized = (scores / (scores.sum(dim=-1, keepdim=True) + 1e-20)).reshape(
batch_size, -1, self.num_experts)
group = self.aux_loss_cp_group

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

拿到完整序列计算

return output.view(batch, sequence, heads, -1), None


@module_replacement

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

这个不应该走模块替换

return getattr(config, "swiglu_limit", None), getattr(torch, dtype) if isinstance(dtype, str) else dtype


@module_replacement

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

这个尝试不走模块替换 但是如果因为和hf权重行为不一致 走不通,再看看是不是这样



@inner_wrapper
def xing4_moe_cp_wrapper(target_module: Xing4MoE, mesh: Any, tp_mesh: Any,

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.

aux-loss使用的通信与不应该放在这里,删除

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants