Skip to content

Align Kimi BF16 column linear under accuracy gate - #1411

Open
zrr1999 wants to merge 1 commit into
developfrom
kimi-k2-accuracy-compatible
Open

Align Kimi BF16 column linear under accuracy gate#1411
zrr1999 wants to merge 1 commit into
developfrom
kimi-k2-accuracy-compatible

Conversation

@zrr1999

@zrr1999 zrr1999 commented Jul 7, 2026

Copy link
Copy Markdown
Member

PR Category

Operator Mechanism

PR Types

Bug fixes

Description

This PR narrows the Kimi accuracy-compatible BF16 column-linear alignment change to the experimental ColumnParallelLinear path only.

  • Add an explicit use_accuracy_compatible argument to column_sequence_parallel_linear.
  • In TP=1 BF16 only, route through paddle.nn.functional.linear to match the Megatron-Core no-TE behavior observed for Kimi shared-expert fc1.
  • Keep the default fused_linear path unchanged unless use_accuracy_compatible=True.
  • Add a single-card regression test for the accuracy gate, default fused path, dtype guard, and ColumnParallelLinear.forward config propagation.

Validation:

  • python -m py_compile src/paddlefleet/tensor_parallel/layers.py tests/single_card_tests/tensor_parallel/test_column_sequence_parallel_accuracy.py
  • pre-commit run --files tests/single_card_tests/tensor_parallel/test_column_sequence_parallel_accuracy.py src/paddlefleet/tensor_parallel/layers.py --show-diff-on-failure
  • Kimi 2-layer no-TE forward-loss comparisons reached 20-step and 100-step BITWISE_PASS in the repro workspace.

Copilot AI review requested due to automatic review settings July 7, 2026 06:51

Copilot AI 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.

Pull request overview

该 PR 旨在为 Kimi 的跨框架精度对齐引入一个显式的 use_accuracy_compatible 开关:在不影响默认高性能路径(如 fused / fusion 相关路径)的前提下,为特定 BF16/TP=1/MLA/MoE 形状选择更贴近 Megatron-Core(no-TE)数值行为的实现,以便进行 bitwise/严格精度对齐验证。

Changes:

  • TransformerConfig 中新增 use_accuracy_compatible 开关,并在开启时统一调整一批 fused/rope/softmax 等相关开关与 env flag。
  • 为 RMSNorm、attention(QK/softmax/mask)、MoE router/单卡 MoE combine、MLP SwiGLU、Embedding dtype 等关键算子引入 accuracy gate 下的数值对齐路径。
  • 为 TP 线性层相关实现补充 accuracy gate 下的特定 BF16 路径(包含 TP=1 ColumnParallelLinear 的 F.linear 路由与 Kimi routed expert fc1 的 split GEMM PyLayer)。

PR 标题/描述检查:

  • 标题未符合约定格式(需要形如 [CLASS]Title)。建议改为例如:[Feature] Align Kimi BF16 column linear under accuracy gate(或按团队分类用 [BugFix]/[Refactor] 等)。
  • 描述信息较完整(包含 Summary/Validation/Scope),满足最低要求。

Reviewed changes

Copilot reviewed 14 out of 14 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
src/paddlefleet/transformer/transformer_config.py 新增 use_accuracy_compatible 并在开启时统一设置对齐用的配置与 env flag。
src/paddlefleet/transformer/paddle_norm.py accuracy gate 下引入显式 FP32 岛与 BF16 边界行为的 RMSNorm PyLayer。
src/paddlefleet/transformer/multi_latent_attention.py 在实验路径下对 accuracy gate 做 RoPE 分流,确保 Kimi 对齐走标准 MLA YaRN 路径。
src/paddlefleet/transformer/moe/moe_utils.py 将 env flag 读取改为动态读取,支持 config 构造阶段设置。
src/paddlefleet/transformer/moe/moe_router.py accuracy gate 下修正 unfused router matmul 权重布局、topk gather 以匹配 Torch scatter backward 等。
src/paddlefleet/transformer/moe/moe_layer.py accuracy gate 下调整单卡 MoE 的 per-token scale 位置与 combine 的 BF16 累加行为。
src/paddlefleet/transformer/mlp.py accuracy gate 下对 SwiGLU 使用 FP32 岛并支持 per_token_scale 的对齐位置。
src/paddlefleet/transformer/hyper_connection.py 动态读取 env flag,避免 import-time 固化。
src/paddlefleet/transformer/dot_product_attention.py accuracy/eager 下引入显式 QK PyLayer backward、softmax/mask dtype 处理以贴近对齐目标。
src/paddlefleet/tensor_parallel/layers.py accuracy gate 下为线性层引入 F.linear 分流与 Kimi expert fc1 split GEMM PyLayer 等。
src/paddlefleet/models/gpt/gpt_layer_specs.py accuracy gate 下调整 MLA 子层 spec(q_a/kv_a 投影选择)。
src/paddlefleet/models/gpt/gpt_embedding.py accuracy gate 下将 embedding 输出 cast 回表 dtype(对齐 Megatron 输入 RMSNorm 的 BF16 行为)。
src/paddlefleet/fusions/fused_softmax.py accuracy gate 下提供 FP32 softmax + BF16 输出且显式 backward 的 PyLayer。
packages/paddlefleet_ops/src/paddlefleet_ops/init.py 改善 ecosystem ops 动态加载失败时的封装与可用性 flag 处理。

Comment on lines +368 to +372
if bias is not None:
output = output + bias
output = paddle.nn.functional.linear(input, weight, bias)
elif use_accuracy_compatible:
output = paddle.nn.functional.linear(input, weight)
else:
Comment on lines +269 to +278
mla_q_a_proj = (
backend.linear()
if use_accuracy_compatible
else backend.column_parallel_linear()
)
mla_kv_a_proj = (
backend.linear()
if use_accuracy_compatible
else backend.column_parallel_linear()
)
Comment on lines +355 to +362
def forward(
ctx,
input,
weight,
bias,
allreduce_dgrad,
tp_group,
use_accuracy_compatible=False,

@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.

已完成首轮审查。发现需要先修复的 P1 问题,细节已放在行内评论,主要涉及 accuracy gate 的进程级状态泄漏,以及 frozen-weight 线性层默认路径和反向 dtype 处理的回归风险。CI 当前通过。

P1 优先级:P1

  • 非行级:GitHub mergeability 当前仍显示存在 merge conflicts;请同步 develop 并解决冲突后再请求复查。
Powered by Nyanpasu with gpt-5.5 xhigh, please check the suggestions carefully.

self.moe_topk_fusion = False
self.routing_map_fusion = False
self.fused_linear_ce_loss_chunk = 0
os.environ["FLAGS_use_accuracy_compatible_kernel"] = "1"

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

这里在构造一个 use_accuracy_compatible=True 的 config 时会永久写入进程级环境变量。这个 flag 现在被多个运行时路径动态读取(例如 fused softmax、language loss、MoE dispatcher/hyper_connection),因此同一 Python 进程里只要先创建过 accuracy config,之后创建的普通 config 即使 use_accuracy_compatible=False 也会被这些 env-gated 路径污染,默认训练/推理路径不再可恢复。请不要在 TransformerConfig.__post_init__ 里修改 os.environ,而是把 config gate 显式传到需要的模块;如果还要兼容外部手动设置 env,可以把 env 只作为用户显式开关读取。

可以按这个方向收敛:

def accuracy_compatible_enabled(config=None):
    return bool(getattr(config, "use_accuracy_compatible", False)) or (
        os.environ.get("FLAGS_use_accuracy_compatible_kernel", "0") == "1"
    )

然后由持有 config 的调用点使用该 helper,而不是从 config 构造阶段反向写全局环境变量。

Comment on lines +368 to +373
if bias is not None:
output = output + bias
output = paddle.nn.functional.linear(input, weight, bias)
elif use_accuracy_compatible:
output = paddle.nn.functional.linear(input, weight)
else:
output = paddle.matmul(input, weight)

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

这里把 frozen-weight 的 bias 分支无条件切到 F.linear,即使 use_accuracy_compatible=False 也会改变默认路径的 GEMM/融合选择;这和 PR 描述的“default fused_linear path unchanged unless use_accuracy_compatible is enabled”不一致,也会让普通 BF16/FP16 冻结权重层出现数值或性能回归。请只在 accuracy gate 下使用 F.linear,默认路径保持原来的 matmul + bias

Suggested change
if bias is not None:
output = output + bias
output = paddle.nn.functional.linear(input, weight, bias)
elif use_accuracy_compatible:
output = paddle.nn.functional.linear(input, weight)
else:
output = paddle.matmul(input, weight)
if use_accuracy_compatible:
output = paddle.nn.functional.linear(input, weight, bias)
else:
output = paddle.matmul(input, weight)
if bias is not None:
output = output + bias

bias,
allreduce_dgrad,
tp_group,
use_accuracy_compatible=False,

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

这个新参数让 frozen-weight 前向也能走 accuracy F.linear,但同一个类的 backward 仍直接使用保存的 weight.t() 做 dgrad。PR 在 trainable linear backward 已经处理了同类问题:BF16 前向接 CE/上游 FP32 梯度时,grad_output 可能是 float32 而冻结权重仍是 bfloat16,Paddle matmul 需要同 dtype,会在 LoRA/冻结 base weight 路径反向时报 dtype mismatch。请同步修正 frozen-weight backward:

dgrad_weight = (
    weight.cast(grad_output.dtype)
    if weight.dtype != grad_output.dtype
    else weight
)
grad_input = grad_output.matmul(dgrad_weight.t())

PaddlePaddle-bot

This comment was marked as outdated.

@Paddle-CI-Bot

Paddle-CI-Bot commented Jul 7, 2026

Copy link
Copy Markdown

PaddleFleet Log Analysis

Run #28922014450 · Attempt 1

日志分析报告

流水线名称 问题标签 修复建议 日志片段
Unit test (single card) MoE router matmul shape 不匹配 + flash_attn float32 不支持 + GPTEmbedding 缺少 embedding 属性 修复 MoE gate detach matmul 的 weight 转置逻辑;attention accuracy_compatible 路径下强制转 bf16/fp16;在 gpt_embedding.py:619 判断 self.embedding 是否存在再取 dtype 报错代码
Integration test (H20, multi-card) — Qwen pre-train/sft/lora NCCL unhandled cuda error,exit_code=241 Qwen multi-card 训练在 broadcast_mp_parameters 阶段 rank 7 触发 NCCL CUDA 错误,导致 3 个 Qwen 子任务全部失败;检查 gpt_embedding.py 的 accuracy_compatible 逻辑是否引入 dtype 不一致触发 CUDA 异常 报错代码
Integration test (A100) — Qwen VL sft/lora/moe Loss Diff 精度回归 + 精度审批缺失 Qwen3VL sft/lora/moe step 10 Loss 与 GT 存在 1e-6 ~ 3e-6 绝对误差(atol=0 零容忍),需要精度审批人(XieYunshen/From00/risemeup1/tianlef 之一)APPROVE 后 CI 才能通过 报错代码
Coverage Upload And Check 增量覆盖率不达标(exit 9,覆盖率 55%) 针对 paddle_norm.py(16%)、tensor_parallel/layers.py(44%)、transformer/mlp.py(27%)补充单测覆盖 报错代码

失败的测试 case:

# Unit test (single card)
tests/single_card_tests/ai_edited_test/pipeline_parallel/test_ai_moe_router.py::TestGateDetachMatmul::test_fuse_false_path
tests/single_card_tests/ai_edited_test/moe/test_ai_moe_router.py::TestMoERouter::test_gate_detach_matmul_no_fuse
tests/single_card_tests/ai_edited_test/transformer/test_ai_dot_product_attention_use_accuracy_compatible.py::TestDotProductAttentionUseAccuracyCompatible::test_compatible_matches_default_baddbmm
tests/single_card_tests/ai_edited_test/transformer/test_ai_dot_product_attention_use_accuracy_compatible.py::TestDotProductAttentionUseAccuracyCompatible::test_float32_mask_is_converted
tests/single_card_tests/ai_edited_test/transformer/test_ai_dot_product_attention_use_accuracy_compatible.py::TestDotProductAttentionUseAccuracyCompatible::test_forces_softmax_in_fp32
tests/single_card_tests/ai_edited_test/transformer/test_ai_dot_product_attention_use_accuracy_compatible.py::TestDotProductAttentionUseAccuracyCompatible::test_forward_backward_grads
tests/single_card_tests/ai_edited_test/transformer/test_ai_dot_product_attention_use_accuracy_compatible.py::TestDotProductAttentionUseAccuracyCompatible::test_forward_runs_eager_qk_branch
tests/single_card_tests/ai_edited_test/models/test_ai_gpt_embedding.py::TestGPTEmbeddingForwardPaths::test_forward_mtp_assertion
tests/single_card_tests/ai_edited_test/models/test_ai_gpt_embedding.py::TestGPTEmbeddingForwardPaths::test_forward_removes_none_values
tests/single_card_tests/ai_edited_test/models/test_ai_gpt_embedding.py::TestGPTEmbeddingForwardPaths::test_forward_with_decoder_input
tests/single_card_tests/ai_edited_test/models/test_ai_gpt_embedding.py::TestGPTEmbeddingSWARotaryPosEmb::test_swa_apply_rope_fusion
tests/single_card_tests/ai_edited_test/models/test_ai_gpt_embedding.py::TestGPTEmbeddingSWARotaryPosEmb::test_swa_mrope_path
tests/single_card_tests/ai_edited_test/models/test_ai_gpt_embedding.py::TestGPTEmbeddingSWARotaryPosEmb::test_swa_rope_path
tests/single_card_tests/ai_edited_test/models/test_ai_gpt_embedding.py::TestGPTEmbeddingSWARotaryPosEmb::test_swa_sequence_parallel_mrope
tests/single_card_tests/ai_edited_test/models/test_ai_gpt_embedding.py::TestGPTEmbeddingSWARotaryPosEmb::test_swa_sequence_parallel_rope
tests/single_card_tests/ai_edited_test/models/test_ai_gpt_embedding.py::TestGPTEmbeddingCPScatterSPAssert::test_no_sp_with_cp_scatter_plain_path_passes
tests/single_card_tests/model/test_base_embedding.py::TestGPTEmbeddingFillFeatureBranch::test_forward_handles_none_pad_token_id
tests/single_card_tests/model/test_base_embedding.py::TestGPTEmbeddingFillFeatureBranch::test_forward_uses_custom_pad_token_id
tests/single_card_tests/model/test_base_embedding.py::TestGPTEmbeddingFillFeatureBranch::test_forward_zeros_padding_and_sets_moe_mask

# Integration test (H20) — Qwen
Qwen pre-train (multi-card, H20): NCCL unhandled cuda error, exit_code=241
Qwen sft (multi-card, H20): exit_code=241
Qwen lora (multi-card, H20): exit_code=1

# Integration test (A100) — Qwen VL
Qwen vl sft (A100, tp8): Log Loss=11.93260002 vs GT=11.93260193, abs_diff=1.91e-06
Qwen vl lora (A100): Log Loss=11.93219948 vs GT=11.93220043, abs_diff=9.5e-07
Qwen vl moe (A100): Log Loss=12.33152866 vs GT=12.3315258, abs_diff=2.86e-06

根本原因分析:

本 PR(kimi-k2-accuracy-compatible,PR #1411)为 Kimi BF16 数值对齐引入了 use_accuracy_compatible 路径,改动涉及 gpt_embedding.pytensor_parallel/layers.pytransformer/dot_product_attention.pymoe_router.py 等多处,导致以下问题:

  1. MoE router matmul shape 不匹配:accuracy_compatible 路径下 gate weight 未做转置,matmul(x[B,8], W[4,N]) 维度不对齐(X[1]=8 ≠ W[0]=4)。
  2. flash_attn float32 不支持:accuracy_compatible attention 路径构造了 float32 输入送入 flash_attn,但 Paddle flash_attn kernel 仅支持 fp16/bf16。
  3. GPTEmbedding 缺少 embedding 属性gpt_embedding.py:619 新增的 self.embedding.embed_tokens.weight.dtype 访问在测试用 mock 对象中无 embedding 子层,属性不存在导致 AttributeError;同样影响 test_base_embedding.py 中通过 embed_tokens.weight.dtype 取 dtype 的逻辑。
  4. H20 Qwen multi-card NCCL 错误broadcast_mp_parameters 阶段 rank 7 触发 NCCL unhandled cuda error,可能与 accuracy_compatible 路径修改的 dtype 处理引入了参数 tensor 异常有关。
  5. A100 Qwen VL Loss Diff:VL sft/lora/moe 在 A100 上 step 10 loss 与 GT 存在 1e-6~3e-6 绝对误差,超出零容忍阈值(atol=0),需精度审批人 approve。
  6. 覆盖率不达标:新增代码中 paddle_norm.py(16%)、tensor_parallel/layers.py(44%)、mlp.py(27%)未被单测覆盖,导致增量覆盖率仅 55%,低于 CC_FAIL_ON_ERROR 阈值触发 exit 9。

修复建议:

  1. MoE gate matmul:在 moe_router.py accuracy_compatible 路径的 gate detach matmul 中,对 weight 做转置(weight.T)或调整 matmul 参数 transpose_y=True,使 [B, hidden] × [hidden, num_experts] 维度对齐。

  2. flash_attn dtypedot_product_attention.py accuracy_compatible 分支中,在调用 flash_attn 前将 query/key/value 强制转换为 bf16 或 fp16,不可直接传入 float32。

  3. GPTEmbedding embedding 属性gpt_embedding.py:619 访问 self.embedding 前加守卫:

    if hasattr(self, 'embedding') and self.embedding is not None:
        target_dtype = self.embedding.embed_tokens.weight.dtype
    else:
        target_dtype = ...  # fallback dtype

    同步修复 test_base_embedding.py 对应 mock 对象需注册 embedding 子层。

  4. H20 Qwen NCCL:上述 dtype 修复后重跑观察是否复现;若仍失败,在 Qwen multi-card 配置 yaml 中确认 accuracy_compatible 相关 flag 未意外激活导致参数 dtype 混乱。

  5. A100 Qwen VL Loss Diff:需精度审批人(XieYunshen、From00、risemeup1、tianlef 之一)在 PR Align Kimi BF16 column linear under accuracy gate #1411 上 APPROVE review 后 CI 才会放行;若认为误差在可接受范围需更新 GT loss 基准文件,走精度变更流程。

  6. 覆盖率:重点补充以下文件的单测:

    • src/paddlefleet/transformer/paddle_norm.py lines 51-59, 63-73, 81-85, 91, 97, 103-105, 148
    • src/paddlefleet/tensor_parallel/layers.py lines 371, 488-490, 496, 506-521, 663, 1193, 1523-1526, 1531
    • src/paddlefleet/transformer/mlp.py lines 218, 222-223, 226-230
    • src/paddlefleet/models/gpt/gpt_embedding.py lines 622-623

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

🔄 每次 Re-run 后自动更新

@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.

已复查最新提交。合并冲突已经解除;上一轮 3 个 P1 代码问题在当前代码中仍未修复,继续以原行内线程为准。另发现当前 codestyle 失败中有两个可直接定位的格式/ruff 问题,已补充为新的行内评论。

P3 优先级:P3

  • 非行级:PR 标题/描述不在 diff 行中,无法行内附着。当前 Check PR Description 仍因模板字段缺失失败;建议把标题改成类似 [Bug fixes] Align Kimi BF16 column linear under accuracy gate,并在描述里补齐 PR Category: Distributed StrategyPR Types: Bug fixes(或更准确的类型)以及现有 Summary/Validation 内容。
Powered by Nyanpasu with gpt-5.5 xhigh, please check the suggestions carefully.

Comment thread src/paddlefleet/transformer/mlp.py Outdated
if per_token_scale is not None:
scale = per_token_scale.unsqueeze(-1).cast("float32")
intermediate_parallel = intermediate_parallel * scale
intermediate_parallel = intermediate_parallel.cast(original_dtype)

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

Codestyle Check 里的 ruff format 仍在失败,本地 ruff format --diff src/paddlefleet/transformer/mlp.py 定位到这一行需要拆行。当前格式会让必需的样式检查继续失败;请按 formatter 输出调整。

Suggested change
intermediate_parallel = intermediate_parallel.cast(original_dtype)
intermediate_parallel = intermediate_parallel.cast(
original_dtype
)

Comment on lines +56 to +57
def _use_accuracy_compatible_config(config: "TransformerConfig") -> bool:
return bool(getattr(config, "use_accuracy_compatible", False))

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

Codestyle Checkruff check 失败,本地 ruff check --fix --diff src/paddlefleet/transformer/dot_product_attention.py 定位到这里的 UP037。该文件已经启用 from __future__ import annotations,带引号的类型注解会让样式检查持续失败;请移除注解里的字符串引号。

Suggested change
def _use_accuracy_compatible_config(config: "TransformerConfig") -> bool:
return bool(getattr(config, "use_accuracy_compatible", False))
def _use_accuracy_compatible_config(config: TransformerConfig) -> bool:
return bool(getattr(config, "use_accuracy_compatible", False))

PaddlePaddle-bot

This comment was marked as outdated.

PaddlePaddle-bot

This comment was marked as outdated.

@zrr1999
zrr1999 force-pushed the kimi-k2-accuracy-compatible branch from a07ffb4 to 20a36d5 Compare July 8, 2026 07:10
@zrr1999

zrr1999 commented Jul 8, 2026

Copy link
Copy Markdown
Member Author

Update pushed in 20a36d5:

  • Reset the branch onto latest develop and removed the stale broad accuracy/debug diff. The old comments about env mutation, attention, frozen-weight, router/norm/softmax changes, and formatting are now on outdated code that is no longer in this PR.
  • Current PR diff is intentionally minimal: src/paddlefleet/tensor_parallel/layers.py plus a single-card regression test covering the new gate and default path.
  • Updated the PR body to satisfy ci/checkPRTemplate.py (### PR Category, ### PR Types, ### Description).

@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.

已复查最新提交。当前 PR 已重置为最小范围,只保留 ColumnParallelLinear experimental 路径下的 BF16 TP=1 accuracy gate 和对应单卡回归测试;上一轮 Nyanpasu 提出的 P1/P3 问题都已随旧的大范围 diff 移除或由当前模板检查通过而关闭。当前代码未发现需要阻塞合入的问题。

本地已验证 py_compileruff check 通过;新增测试在本地因环境缺少 paddle 无法收集运行,仍以仓库 CI 结果为准。

Powered by Nyanpasu with gpt-5.5 xhigh, please check the suggestions carefully.

@PaddlePaddle-bot PaddlePaddle-bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 Paddle-CI-Agent | pr_review | 2026-07-08 15:24:44

📋 Review 摘要

PR 概述:将 Kimi BF16 column-linear 的 accuracy-compatible 分支收敛到 experimental ColumnParallelLinear 的 TP=1 路径,并补充单卡门禁测试。
变更范围src/paddlefleet/tensor_parallel/layers.pytests/single_card_tests/tensor_parallel/test_column_sequence_parallel_accuracy.py
影响面 TagTensor Parallel Tests

问题

未发现阻塞性问题。PR 规范问题在下面章节报,不在这里重复。

历史 Findings 修复情况

Finding 问题 状态
F1 use_accuracy_compatible 会把进程级 FLAGS_use_accuracy_compatible_kernel 永久置为 1 ✅ 已修复
F2 use_accuracy_compatible 只把 bf16 置为 True,但不会同步 params_dtype/autocast_dtype ✅ 已修复
F3 use_accuracy_compatible=True 的默认配置会在这里提前走 EC flash attention,绕过后面的 accuracy-compatible QK/softmax 路径。 ⚠️ 仍存在
F4 BF16 accuracy attention backward 会把 FP32 softmax 梯度和 BF16 key/query 直接做 matmul ⚠️ 仍存在

📝 PR 规范检查

标题仍缺少官方 Tag;描述已按 checklist §D2 补齐 PR Category / PR Types / Description 结构。

标题建议(可直接复制):

  • [Bug fixes] Align Kimi BF16 column linear under accuracy gate

总体评价

本次 diff 的默认 fused path 保持 use_accuracy_compatible=False,accuracy gate 也限制在 TP=1 且 input/weight 均为 BF16 的 experimental column-linear 分支,整体范围符合 PR 描述。新增测试覆盖了 gate、默认路径、dtype guard 和 ColumnParallelLinear.forward 的配置透传。

本地验证:python -m py_compile src/paddlefleet/tensor_parallel/layers.py tests/single_card_tests/tensor_parallel/test_column_sequence_parallel_accuracy.pygit diff HEAD^ HEAD --check 通过;python -m unittest tests.single_card_tests.tensor_parallel.test_column_sequence_parallel_accuracy 因当前环境缺少 paddle 包未能执行。

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (develop@3c25856). Learn more about missing BASE report.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##             develop     #1411   +/-   ##
===========================================
  Coverage           ?   100.00%           
===========================================
  Files              ?         1           
  Lines              ?         2           
  Branches           ?         1           
===========================================
  Hits               ?         2           
  Misses             ?         0           
  Partials           ?         0           
Flag Coverage Δ
coverage_combine 100.00% <100.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/paddlefleet/tensor_parallel/layers.py 100.00% <100.00%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@zrr1999

zrr1999 commented Jul 15, 2026

Copy link
Copy Markdown
Member Author

Kimi-K2 numerical-alignment scope update

This PR should remain narrow: it contributes one measured BF16 column-linear mechanism and keeps the default path unchanged. The results below come from the complete gated Kimi stack, not from this PR alone.

Validated on the real Kimi-K2 2-layer BF16 SFT checkpoint with native ms-swift/Megatron-Core and PaddleFormers/PaddleFleet runners:

  • EP1 forward loss: 100/100 steps bitwise exact.
  • EP8 all-to-all forward loss: 100/100 steps bitwise exact.
  • EP1 step-1 canonical parameter gradients: 794/794 BITWISE_PASS, revalidated after updating PFCCLab/Megatron-LM to a10a87c5b.
  • EP8 bounded canonical gradients: 64/64 BITWISE_PASS.
  • Bounded optimizer state for two real decay/no-decay parameters: 8/8 exact across FP32 master parameter, FP32 moment1/moment2, and BF16 copyback.

This is not yet a complete-training alignment claim. The following native contracts remain to be closed end to end: global gradient norm/clipping, scheduler and warmup authority, all parameter groups/tied weights, distributed optimizer reduction/update order, and multi-step native training updates.

A related authority distinction is important for review. PFCCLab/Megatron-LM PR #2 targets the MiniMax/PyTorch-AdamW stack and cannot be applied wholesale to this Kimi contract:

  • Kimi's native optimizer authority is TransformerEngine 2.16.1 FusedAdam; forcing torch.optim.AdamW(fused=True) changed FP32 master/moment hashes, while the TE-compatible Paddle path is currently 8/8 exact.
  • The MiniMax diagnosis in PFCCLab/ms-swift add spec utils #2 assumes BF16 Megatron main grads versus Paddle amp_master_grad; the current Kimi EP8 config already uses FP32 main grads and FP32 grad reduction.
  • Replacing native Torch MoE index_select backward with FP32 scatter changes the reference semantics. Kimi instead makes Paddle reproduce native deterministic Torch index-add behavior, which is part of the 794/794 result.
  • Alternate per-token loss normalization still needs distributed, variable-length, accumulation-aware training evidence before use in Kimi.

Therefore this PR's explicit TP1/BF16/accuracy-gated scope is intentional. It should not absorb model-specific optimizer, MoE-backward, or training-normalization changes.

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.

6 participants