Skip to content

[Bug Fix] Use astor instead of ast to unparse source code of paddle model, to avoid unstable result between different python versions.#272

Merged
lixinqi merged 2 commits into
PaddlePaddle:developfrom
Xreki:fix_hash
Sep 12, 2025
Merged

[Bug Fix] Use astor instead of ast to unparse source code of paddle model, to avoid unstable result between different python versions.#272
lixinqi merged 2 commits into
PaddlePaddle:developfrom
Xreki:fix_hash

Conversation

@Xreki

@Xreki Xreki commented Sep 10, 2025

Copy link
Copy Markdown
Collaborator

PR Category

Bug Fix

Description

Paddle样本在执行validate时,通过从model.pyforward函数中移除注释、解析模型结构,并依据模型结构的源码字符串生成样本的sha哈希值,写入graph_hash.txt

#266 改成用ast从model.py中解析python类型,并使用ast.unparse将AST转成源码。ast.unparse在不同Python版本下,针对多输出场景的源码格式化风格不一样,比如:
81ebdb28336d12e75ff2c98b57cdf252

这是Python内置AST打印器的“非稳定行为”,会导致在不同Python版本下得到的模型字符串不一样,从而会得到不同的哈希值。

本PR改成使用第三方库astor代替ast.unparse来生成源码,并修复CI上的依赖。
astor.to_sourceast.unparse转换得到的源码的对比:

astor.to_source ast.unparse
稳定性 第三方库(跨版本行为稳定,Python 3.6~3.12 基本一致)。适合做“跨版本、可预测”的源码还原。 Python 3.9+ 标准库自带。行为可能随 Python 版本更新而变化(例如 tuple 结尾逗号、换行位置等)。
注释 不会保留注释(因为 ast 树里本身没有注释) 不会保留注释(因为 ast 树里本身没有注释)
格式化风格 始终使用 4 空格缩进;二元运算符两边强制加空格;一行多个语句会被拆分成多行;括号规则相对保守(只在需要时加)。 格式更接近 Python 官方代码风格(PEP 8-ish),但在不同版本里会变动;有时会多加括号,或把表达式拆得更细;输出可能比 astor 更“冗余”。

总结:

  • astor.to_source,更稳定、更简洁、跨版本统一
  • ast.unparse,官方实现、格式更严格,但跨版本差异大

…void unstable result between different python versions.
@lixinqi lixinqi merged commit 2e977e3 into PaddlePaddle:develop Sep 12, 2025
3 checks passed
@Xreki Xreki deleted the fix_hash branch September 12, 2025 01:59
JewelRoam pushed a commit to JewelRoam/GraphNet that referenced this pull request Oct 29, 2025
…odel, to avoid unstable result between different python versions. (PaddlePaddle#272)

* Use astor instead of ast to unparse source code of paddle model, to avoid unstable result between different python versions.

* Remove the install of astor for torch.
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.

2 participants