Repository navigation
feat(xing_4): 复用 Hugging Face Xing4 与公共训练组件 - #1439
xingleixu123 wants to merge 8 commits into
Conversation
da06b7f to
d6fe53a
Compare
d6fe53a to
a92f507
Compare
a92f507 to
284f79b
Compare
| @@ -0,0 +1,286 @@ | |||
| # Copyright 2026 Huawei Technologies Co., Ltd | |||
There was a problem hiding this comment.
为什么需要这个文件,没有已有的实现吗?或者已有的实现能少量修改吗
There was a problem hiding this comment.
已删除独立 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. |
There was a problem hiding this comment.
你重计算为什么需要一个文件。你看下库上dsv41咋做的相关的,是不是少量修改,尽可能复用库上能力
There was a problem hiding this comment.
已删除独立重计算适配文件,使用库上的 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, |
There was a problem hiding this comment.
类似这样的 为什么没有导入trans的xing,然后一些embedding类似继承的是xing4XXX
There was a problem hiding this comment.
底座使用本地保留的官方 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.""" |
There was a problem hiding this comment.
类似不应该有reference的前缀? 然后你看下是不是有比较多的能继承
There was a problem hiding this comment.
已移除 reference 前缀和空构造包装,直接继承官方 Xing4 类;配置构建沿用共享 HyperAutoModelForCausalLM,不再增加下载/固定 revision 入参。
对应本轮 14d9ccce。保留原线程供继续检视。
1c81d02 to
bdef8fa
Compare
bdef8fa to
6617529
Compare
39b0425 to
de53874
Compare
de53874 to
3d013f2
Compare
| # 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. |
There was a problem hiding this comment.
我们也有啊 为啥要写这么多呢 到底改什么了。为啥不能用我们的 或者提供的modeling 4那个文件,为啥要修改,修改也应该很少啊
There was a problem hiding this comment.
已移除 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: |
There was a problem hiding this comment.
已删除 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 | |||
There was a problem hiding this comment.
已删除 .gitattributes。官方三个 Python 文件的 Git blob 与构建产物均核验原始 SHA256,未修改源码内容或文件名。
对应本轮 14d9ccce。保留原线程供继续检视。
| ], | ||
| 'hyper_parallel.auto_parallel': ['op_profiles/*.yaml', 'op_records.yaml'], | ||
| 'hyper_parallel.models.deepseek_v3': ['recipes/*.yaml'], | ||
| 'hyper_parallel.models.xing_4': ['config.json'], |
There was a problem hiding this comment.
已移除 setup.py 增量,使用库上现有打包规则。三个官方 Python 文件已实际构建并逐一核验 SHA256;固定 config.json 也已按新意见移到仓库外。
对应本轮 14d9ccce。保留原线程供继续检视。
|
可以把GroupedExperts权重转换统一放到module_replacement.py |
| h_res: torch.Tensor, | ||
| num_stream: int, | ||
| *, | ||
| use_fused: bool = True, |
There was a problem hiding this comment.
已撤回本 PR 对共享 mhc_post.py 的修改,该文件与目标 master 完全一致。模型直接调用现有接口,NPU 使用融合路径;本轮不新增非融合开关。
对应本轮 14d9ccce。保留原线程供继续检视。
|
There was a problem hiding this comment.
这个别加进代码仓里,这是具体的模型规格,应该是类似ckpt那样放在外面供hyper-parallel去读取的
There was a problem hiding this comment.
已从代码 PR 移除固定 config.json,原文件作为外部模型资产独立归档。HP 训练配方传入等价模型字段,不要求配置 key/value 与 MF 字面一致。
对应本轮 14d9ccce。保留原线程供继续检视。
3d013f2 to
14d9ccc
Compare
|
已按这两条建议合并结构:GroupedExperts 权重转换和 MLA 高性能替换统一到 按任务此前明确的“官方源码原名原样保留”要求,官方 CPU 两组前后向 364 项张量逐位一致,复用 18 tests / 20 subtests 通过;125 卡 5 的真实 MF5→HP6–10 恢复短跑通过。完整 1000 步报告保留原冻结版本归属,本轮不把短跑当成新的完整验收。原有评论与 review 均保留,未自动解决线程。 |
|
已复核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已更新优先级和条件依赖。 |
|
/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) |
There was a problem hiding this comment.
这里isinstance(module.experts, GroupedExperts)和写死use_grouped_gemm=True会导致moe部分强制走grouped_gemm分支。
如果期望仅保留该分支,则直接在modeling里面实现grouped-gemm版本,并删除这里的配置;如果希望保留for-loop专家计算版本做精度比对基线,则删除这里的校验,use_grouped_gemm改为可配置参数
There was a problem hiding this comment.
非 EP 路径继续保留 HF ModuleList 循环。EP 当前只承诺已验 grouped 路径,检查改为公共 forward_expert_major 能力而非具体类名;公共非 grouped loop 要求另一套 stacked 权重布局与加载契约,本次不新增未经完整验证的开关。
There was a problem hiding this comment.
如果不看护非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]]]: |
There was a problem hiding this comment.
这里是否有必要添加一个大函数做校验和weight打包?
There was a problem hiding this comment.
目前这部分除打包外还验证来源专家、共享权重、hooks/buffer、shape 和激活策略,并提供可逆 checkpoint 映射;矩阵执行仍复用公共 GroupedExperts。现有公共 EP 能力尚不覆盖全部 ModuleList 转换契约,后续可随公共能力成熟再收敛。
| return config, weights | ||
|
|
||
|
|
||
| def _validate_expert_weights( |
There was a problem hiding this comment.
这里为什么不是直接从weight的shape里面读取hidden_size, intermediate_size
There was a problem hiding this comment.
目前 _validate_expert_weights 已从第一组 gate weight 的 shape 读取 intermediate_size 和 hidden_size,再对配置及其他专家权重做一致性检查,避免不一致时静默打包。
|
|
||
| from collections.abc import Callable, Iterable | ||
|
|
||
| import torch |
There was a problem hiding this comment.
已在 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 |
There was a problem hiding this comment.
这个文件应该放在training.py
There was a problem hiding this comment.
已在 fdce1a9 将 Router、MLP 和 MoE 训练适配合并到 training.py,旧 moe.py 已删除;其余 import 与 provider 已同步调整。
合并配置入口与 MoE 训练接线,直接复用官方 mHC 对象,移除重复初始化包装。 保留融合替换、专家转换、MTP/CP 归一化及原生 Muon hook 的必要契约。 撤回公共精度 helper 的纯文档差异,不改官方 HF 源码。
|
/check-pr |
|
本轮追加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/检视批准单独等待。 |
|
/check-pr |
| __all__ = ["Xing4MLAAttention", "Xing4GroupedExperts", "Xing4FusedHyperConnection"] | ||
|
|
||
|
|
||
| def fusion_attention_with_logit_maxima(module: nn.Module, query: torch.Tensor, key: torch.Tensor, |
There was a problem hiding this comment.
开源的代码推理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") |
| ] | ||
|
|
||
|
|
||
| def _load_replacements(): |
| counts.zero_() | ||
|
|
||
|
|
||
| class Xing4MLP(Xing4_0MLP): |
There was a problem hiding this comment.
这个写法似乎有点问题:
expert里面,因为mlp.expert本来就要被grouped GEMM 替换
剩下dense层和shared_experts里面要用swiglu的 可以靠plan overrides做
这也导致了module replacements里面 _expert_weights进行了额外的奇怪校验
There was a problem hiding this comment.
特别是要合并training和module_replacement之后
|
|
||
|
|
||
| @register_module_replacement | ||
| class Xing4GroupedExperts(GroupedExperts): |
There was a problem hiding this comment.
因为框架的 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, |
| counts.zero_() | ||
|
|
||
|
|
||
| class Xing4MLP(Xing4_0MLP): |
There was a problem hiding this comment.
特别是要合并training和module_replacement之后
|
|
||
|
|
||
| @torch.no_grad() | ||
| def initialize(owner: Any, module: nn.Module) -> None: |
将 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 |
There was a problem hiding this comment.
开了TP 和 EP的场景下会漏掉TP域的同步,即获取的不是完整序列
| return getattr(config, "swiglu_limit", None), getattr(torch, dtype) if isinstance(dtype, str) else dtype | ||
|
|
||
|
|
||
| @module_replacement |
There was a problem hiding this comment.
还需要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: |
| 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: |
| for name, buffer in module.named_buffers(recurse=False, remove_duplicate=False) | ||
| if name in getattr(module, "fp32_buffer_names", ()) | ||
| } | ||
| mismatched.extend( |
There was a problem hiding this comment.
尝试给这个回退,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 |
|
|
||
|
|
||
| @method_replacement | ||
| def xing4_cp_mean_loss(*, module: nn.Module, method_fqn: str, |
| 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", |
There was a problem hiding this comment.
既然是特定模型,直接这个文件不要。改在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 |
| return output.view(batch, sequence, heads, -1), None | ||
|
|
||
|
|
||
| @module_replacement |
| return getattr(config, "swiglu_limit", None), getattr(torch, dtype) if isinstance(dtype, str) else dtype | ||
|
|
||
|
|
||
| @module_replacement |
There was a problem hiding this comment.
这个尝试不走模块替换 但是如果因为和hf权重行为不一致 走不通,再看看是不是这样
|
|
||
|
|
||
| @inner_wrapper | ||
| def xing4_moe_cp_wrapper(target_module: Xing4MoE, mesh: Any, tp_mesh: Any, |
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:
保留必要的专家打包及可逆 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;统一复合运行源码 manifest7dd9613c60843e646e15f6bb9879f477c201d63824793859e5386bd8059d8f4f,不是裸master。包含 #1470、#1410 + dz-ssk#7 及已记录冻结依赖;完整归属与条件项见总issue置顶表。完整统计、代码处置、实际配置边界及12张网站图 · 合入顺序与不需合入项。
Code review checklist [illustration]:
按用户要求,本轮 PR 仅保留逻辑代码;已执行的测试证据单独归档。