Skip to content

[FSDP] Supp FSDP save HF ckpt - #79946

Merged
Xing-lil merged 2 commits into
PaddlePaddle:developfrom
Xing-lil:fsdp_supp_save_hf_ckpt
Nov 13, 2026
Merged

Xing-lil merged 2 commits into
PaddlePaddle:developfrom
Xing-lil:fsdp_supp_save_hf_ckpt

Conversation

@Xing-lil

@Xing-lil Xing-lil commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

PR Category

Distributed Strategy

PR Types

New features

Description

FSDP 训练下 save_hf_steps 导出 HF 权重时报 Tensor not initialized:参数存储已被 FSDP 释放,model.full() 无法读取数据。

本 PR 由 FSDP 模块接管 model.full:

  • 按 buffer group 将已释放参数 all_gather 后拷至 CPU 并绑定回参数,逐组释放显存中的临时 buffer;fp8 参数先转为主精度;
  • 临时换回模型原有的 sharded_state_dict,对描述为 replicated 的专家参数按 EP 折叠到第 0 维(与 FSDP sharded_state_dict 一致),再调用模型原有的 full,复用原有的 HV 组装与写盘流程;
  • 导出结束或中途出错时,重新释放参数并恢复 sharded_state_dict。
  • 同时,full_param 的 HV 路径支持 CPU tensor 参与。

是否引起精度变化

否

@Paddle-Review-Bot

Paddle-Review-Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Paddle-Bot Review Board (review完成)

序号 位置 优先级 规则来源 状态
1 导出时绕过 EP 专家描述折叠 P1 仓库规则:Paddle 基础评审规则 ✅
2 参数收集阶段缺少异常回滚 P2 仓库规则:Paddle 基础评审规则 ✅
3 分片与 fp8 导出路径缺少多卡测试 P2 仓库规则:Paddle 基础评审规则 ✅

可维护性建议(总分 87.9 / 100,只给建议,不影响评审结论)

序号 位置 维度 状态
1 局部变量 full 命名 命名质量 ✅
2 full 改为生成器后的调用契约 契约一致性 ✅
3 HV 路径 CPU 张量设备语义 逻辑清晰度 ✅
4 参数释放样板重复 底层优雅度 💡
5 EP 折叠逻辑重复 中层优雅度 💡
各维度得分(仅评本 PR 改动,点击展开)
83 中层优雅度
5
84 底层优雅度
4
85 抽象适配度
85 高层优雅度
85 设计一致性
85 跨模块架构
86 AI 生成债务
86 契约一致性
2
87 API 表面一致性
87 逻辑清晰度
3
87 测试策略
90 约定偏离
90 错误处理一致性
90 初始化耦合
90 命名质量
1
90 类型安全
93 未完成迁移
93 包组织结构
95 依赖健康度
— 鉴权一致性

Powered by Nyanpasu claude with Opus 5.5 默认推理级别, please check the suggestions carefully.

released.append((param, param.shape))
value._share_buffer_to(param)
del full
self.model.sharded_state_dict = self._model_sharded_state_dict

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

这里把 model.sharded_state_dict 切回模型原始实现,导致 full_param 拿到的是没有经过 FSDP 修正的描述。FullyShardFusion.sharded_state_dict 第 1626-1639 行专门处理了一种情况:EP>1 时,模型把专家参数描述为 replicated(global_shape == local_shape),这时要把 EP 折叠到第 0 维,"to keep keys distinct"。full() 绕过了这段折叠,各 EP rank 的专家分片会带着相同的 key、global_offset 和 slice_shape 进入 full_param。dedup_read_items(full_param.py 第 250-259 行)按 (tensor_name, src_global_offset, slice_shape) 去重后只保留 rank 最小的那份,导出的 HF 权重会静默丢掉其余 EP rank 的专家,并且不会报错。

建议导出时同样应用 EP 折叠,例如在原始描述上复用第 1626-1639 行的 global_shape/global_offset 修正。如果确认这种场景不支持,请在 full() 里对 is_expert_param 且 EP>1 的组显式报错,并补充 EP>1 的多卡导出测试。

value._share_buffer_to(param)
del full
self.model.sharded_state_dict = self._model_sharded_state_dict
try:

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

try/finally 从第 1704 行才开始,第 1676-1702 行的收集循环不在保护范围内。循环里已经对前面若干 group 执行了 value._share_buffer_to(param),如果后面某个 group 的 paddle.empty([total_buffer_size]) 申请显存失败(大 buffer 时可能 OOM),或者 all_gather、build_ckpt_weight 抛错,前面这些参数会一直绑在 CPU 数据上(_is_initialized() 为 True),后续 forward 的 all_gather_params 会在这份 CPU 存储上做 _share_data_with,状态不一致。_base_sharded_state_dict 同样是"先绑定、再还原",但它的回滚覆盖了完整流程。

另外 full() 现在是生成器:调用方如果中途 break,或者没迭代完就丢弃,finally 要等到 GC 才会执行,在此之前参数保持 CPU 绑定,model.sharded_state_dict 也还停在原始实现上。

建议把 released = [] 之后的收集循环和第 1703 行的替换一起放进 try,finally 只还原 released 里已经绑定的参数;同时在 docstring 中说明调用方必须迭代完或显式 close()。

full = params_buffer.data_buffer
if params_buffer.fp8 is not None:
full = build_ckpt_weight(params_buffer, group.dtype)
if params_buffer.is_sharded:

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

新增测试 TestFullToCpu 只用 SimpleNamespace 覆盖了 is_sharded=False、fp8=None 的单进程路径。导出正确性的关键分支都没有覆盖:本行开始的分片 all_gather 后按 param_offsets 切片、第 1682-1683 行 fp8 build_ckpt_weight 的 dtype 转换、full_param.py 中 HV 路径新增的 CPU→CUDA 搬运(现有 test_model_full_param.py 的 HV 用例源张量都在 GPU 上),以及导出后再次 forward/step 时参数状态是否正常。按仓库规则,分布式行为需要有代表性的多进程覆盖。

建议在 test/collective/fleet/dygraph_group_fsdp.py 中增加一个多卡用例:训练一步后调用 model.full()(同时覆盖 HV 分组),将导出结果和 unshard_params 下的参数做逐项比较,然后再跑一步 forward/backward,确认参数已重新释放、训练能继续。

if not params:
continue
params_buffer = group.params_buffer
full = params_buffer.data_buffer

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.

💡 可维护性建议(命名质量,不阻塞合入):局部变量 full 与方法名同名,并且在循环里先后表示本 rank 的分片 data_buffer、fp8 拷贝和 all_gather 之后的完整 buffer,到第 1686 行才真正是"full"。紧邻的 sharded_state_dict 对同一对象使用 weight。建议沿用 weight,all_gather 的结果另起名(如 gathered),后续切片改用 gathered._slice(...)。

self._shard_descs[params_buffer.data_buffer.name] = param_slice_info
return result

def full(self, aoa_config=None, **kwargs):

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.

💡 可维护性建议(契约一致性,不阻塞合入):Layer.full 是普通函数,调用时会立即校验 h_group/v_group、解析 kwargs,并返回 __iter__ 可重复调用的 assembler。这里替换成生成器函数之后,参数错误要等到第一次 next() 才抛出,返回值也只能迭代一次。建议改为先完成参数绑定,再 return 一个负责收尾的迭代器;如果保留生成器写法,请在 docstring 中写明返回只能迭代一次,并说明 model.sharded_state_dict 会被临时替换,同时补上与 Layer.full 一致的类型标注。

else:
buffer = paddle.empty(read_item.slice_shape, dtype=read_item.dtype)
if buffer.place.is_cpu_place():
buffer = buffer.cuda()

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.

💡 可维护性建议(逻辑清晰度,不阻塞合入):同文件 _run_distributed(第 525-531 行)对 CPU 源张量是 cuda() 通信后再 .cpu() 搬回;这里只做了搬上 GPU,结果会以 GPU 张量的形式缓存进 sharded_desc_to_tensor。两条路径的设备语义不一致,读者无法判断这是有意为之还是遗漏。建议对齐 on_cpu 的写法,或者加一行注释说明 HV 路径的输出固定在 GPU 上,由 memory_growth_threshold 控制峰值。

finally:
self.model.sharded_state_dict = self.sharded_state_dict
for param, shape in released:
stop_gradient = param.stop_gradient

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.

💡 可维护性建议(底层优雅度,不阻塞合入):第 1708-1712 行"保存 stop_gradient → _clear_data() → 恢复 stop_gradient → _set_dims(shape)"与本类 _base_sharded_state_dict 的 finally(第 1568-1573 行)、shard_params、_release_params_after_unit 逐行相同,测试里又新增了一个 _release() 副本。建议抽一个模块级小函数(如 _release_param(param, shape)),这次新增的代码和测试先复用,以后释放语义有调整时只需改一处。

or tuple(sharded_weight.global_shape) != local_shape
):
continue
# Expert described as replicated: fold EP into axis 0 to keep keys distinct.

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.

💡 可维护性建议(中层优雅度,不阻塞合入):这里的 EP 折叠公式和注释与 sharded_state_dict 第 1632-1641 行逐行相同。两处必须保持一致,full() 导出的 key 才能和 checkpoint 描述对齐,以后只改一处就会让导出与保存悄悄分叉。建议抽一个小函数,如 _fold_expert_desc(local_shape, ep_nranks, ep_rank) -> (global_shape, global_offset),两处共用;ep_nranks/ep_rank 的获取也可以一并复用。

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.15686% with 4 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (develop@77bc015). Learn more about missing BASE report.

Files with missing lines Patch % Lines
...thon/paddle/distributed/fsdp/fully_shard_fusion.py 91.83% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             develop   #79946   +/-   ##
==========================================
  Coverage           ?   92.15%           
==========================================
  Files              ?        2           
  Lines              ?       51           
  Branches           ?        0           
==========================================
  Hits               ?       47           
  Misses             ?        4           
  Partials           ?        0           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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

LGTM

@Xing-lil
Xing-lil merged commit 7303b89 into PaddlePaddle:develop Nov 13, 2026
101 of 103 checks passed
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.

4 participants