You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sphinx autosummary生成torch.nn.Module文档时遇'Training'属性不存在错误

问题原因

training是torch.nn.Module的实例属性,并非类属性。Sphinx autosummary生成文档时,默认会遍历类的所有属性,但当mock导入torch相关模块时,mock出的类无法正确复现Module的动态属性逻辑(Module的很多属性是通过元类或__getattr__动态生成的),导致Sphinx在类层面找不到training属性,从而抛出错误。另外你之前的mock配置有误,autodoc_mock_imports需要指定顶级模块而非子模块/类,mock是按模块层级生效的。

解决方法

1. 修正mock配置

在docs/conf.py中修改mock设置,直接mock整个torch模块:

autodoc_mock_imports = ['torch']

2. 过滤实例属性(二选一即可)

方法A:修改自定义类模板

打开docs/templates/custom-class-template.rst,修改属性生成的循环逻辑,跳过training等实例属性:

{% block attributes %}
{% if attributes %}
.. rubric:: Attributes

.. autosummary::
{% for item in attributes if item not in ['training', '_parameters', '_buffers', '_modules'] %}
    ~{{ fullname }}.{{ item }}
{% endfor %}
{% endif %}
{% endblock %}

方法B:通过Sphinx事件跳过成员

在docs/conf.py中添加事件钩子,自动跳过指定的实例属性:

def skip_instance_attributes(app, what, name, obj, skip, options):
    # 跳过Module子类的实例属性
    if what == 'class' and name in ['training', '_parameters', '_buffers', '_modules']:
        return True
    return skip

def setup(app):
    app.connect('autodoc-skip-member', skip_instance_attributes)

3. 重新生成文档

在docs目录下重新执行:

make html

内容的提问来源于stack exchange,提问作者Yuxi L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 00:15:29