PyTorch Docstring 编写规范详解从签名行到 Sphinx 交叉引用的完整指南【免费下载链接】pytorchTensors and Dynamic neural networks in Python with strong GPU acceleration项目地址: https://gitcode.com/GitHub_Trending/py/pytorch本文基于 PyTorch 仓库中的文档字符串写作技能指南.claude/skills/docstring/SKILL.md系统讲解在 PyTorch 项目中为函数与方法编写 docstring 的完整规范签名行格式、Sphinx/reStructuredText 结构、参数文档化规则、Examples 写法以及 C 绑定函数、in-place 变体、别名函数三类特殊场景的处理方式。读完本文你可以按照 PyTorch 的既有约定为任意torch函数撰写可被 Sphinx 文档系统正确渲染、可被 doctest 校验的标准 docstring。Docstring 在 PyTorch 中的位置PyTorch 的 API 大体来自三个方向纯 Python 函数如torch/nn/functional.py中的gumbel_softmax见 torch/nn/functional.py、由 C 实现绑定到torch._C的算子、以及由 TorchScript 生成的 Tensor 方法。后两者的 docstring 并不写在 C 源码里而是统一通过torch._C._add_docstr在导入时挂载到对应对象上。这一机制在 torch/_C/init.pyi.in 中有类型声明def _add_docstr(obj: T, doc_obj: str) - T: ... # THPModule_addDocStr围绕这个机制仓库沉淀了两类核心文档挂载文件torch/_torch_docs.py为torch._C模块级函数挂载 docstring并提供parse_kwargs等复用工具torch/_tensor_docs.py为Tensor方法挂载 docstring其入口函数add_docstr_all只做了极薄的一层封装torch/_tensor_docs.py#L9-L10def add_docstr_all(method: str, docstr: str) - None: add_docstr(getattr(torch._C.TensorBase, method), docstr)正因为所有 docstring 最终都进入同一套 Sphinx 文档管线格式约定必须高度统一这就是该技能指南存在的意义。通用原则指南给出的五条总原则是一律使用 raw stringr...docstring 中大量出现 LaTeX 反斜杠如:math:\\exp(x_i)普通字符串会被 Python 先行转义raw string 才能原样交给 Sphinx遵循 Sphinx/reStructuredTextreST格式docstring 会被 Sphinx 直接当作 reST 片段渲染简洁但完整只写必要信息但每个必要信息都不能缺尽可能包含 Examples示例是读者验证 API 行为的最快路径同时 PyTorch 的文档流水线会对代码做 doctest 校验示例本身就是回归测试使用交叉引用指向相关的函数、类与方法避免重复描述。Docstring 的标准结构十要素一个完整的 PyTorch docstring 由以下要素按固定顺序组成以下逐一给出规则与规范示例。1. 函数签名首行首行必须是函数签名展示全部参数rfunction_name(param1, param2, *, kwarg1default1, kwarg2default2) - ReturnType要求写出函数名位置参数与仅关键字参数之间用*分隔写出所有默认值结尾标注返回类型这一行末尾不能加句号。2. 简要描述签名后空一行用一句话说明函数做什么rconv2d(input, weight, biasNone, stride1, padding0, dilation1, groups1) - Tensor Applies a 2D convolution over an input image composed of several input planes.3. 数学公式如适用块级公式使用 Sphinx 的.. math::指令.. math:: \text{Softmax}(x_{i}) \frac{\exp(x_i)}{\sum_j \exp(x_j)}行内公式使用:math:\x^2 形式。这正是通用原则中必须用 raw string 的直接原因。4. 交叉引用用 Sphinx role 链接到相关的类、函数、方法、属性:class:\~torch.nn.ModuleName —— 引用类:func:\torch.function_name —— 引用函数:meth:\~Tensor.method_name —— 引用方法:attr:\attribute_name —— 引用属性前缀~表示只渲染最后一段例如显示Conv2d而非torch.nn.Conv2d示例See :class:~torch.nn.Conv2d for details and output shape.5. Notes 与 Warnings用 admonition 承载重要提示。note适合说明与配套 API 的关系、数值性质warning适合说明容易踩坑的语义如是否拷贝.. note:: This function doesnt work directly with NLLLoss, which expects the Log to be computed between the Softmax and itself. Use log_softmax instead (its faster and has better numerical properties). .. warning:: :func:new_tensor always copies :attr:data. If you have a Tensor data and want to avoid a copy, use :func:torch.Tensor.requires_grad_ or :func:torch.Tensor.detach.其中new_tensor的 warning 并非杜撰torch/_tensor_docs.py 中挂载的new_tensordocstring 正是这类警告的实际用例。6. Args 段为所有参数提供类型注解与描述Args: input (Tensor): input tensor of shape :math:(\text{minibatch} , \text{in\_channels} , iH , iW) weight (Tensor): filters of shape :math:(\text{out\_channels} , kH , kW) bias (Tensor, optional): optional bias tensor of shape :math:(\text{out\_channels}). Default: None stride (int or tuple): the stride of the convolving kernel. Can be a single number or a tuple (sH, sW). Default: 1格式规则参数名用小写与形参一致类型放括号里(Type)可选参数写作(Type, optional)描述紧跟类型之后可选参数在末尾给出 Default: value行内代码用双反引号None续行缩进 2 个空格见上例stride的第二行。7. Keyword Args 段如适用仅关键字参数可单独成段。torch/_tensor_docs.py 中的new_common_args就是标准写法Keyword args: dtype (:class:torch.dtype, optional): the desired type of returned tensor. Default: if None, same :class:torch.dtype as this tensor. device (:class:torch.device, optional): the desired device of returned tensor. Default: if None, same :class:torch.device as this tensor. requires_grad (bool, optional): If autograd should record operations on the returned tensor. Default: False.8. Returns 段如需要返回值的文档写法Returns: Tensor: Sampled tensor of same shape as logits from the Gumbel-Softmax distribution. If hardTrue, the returned samples will be one-hot, otherwise they will be probability distributions that sum to 1 across dim.如果返回类型在签名行已经表达清楚可以省略该段。9. Examples 段尽可能都写示例格式规则标题用双冒号Examples::Python 代码用提示符必要时用#注释展示实际输出时输出行缩进且不加。Examples:: inputs torch.randn(33, 16, 30) filters torch.randn(20, 16, 5) F.conv1d(inputs, filters) # With square kernels and equal stride filters torch.randn(8, 4, 3, 3) inputs torch.randn(1, 4, 5, 5) F.conv2d(inputs, filters, padding1)10. 外部引用论文等外部文档使用 reST 的目标标签target声明再在正文中以标签_引用。按指南的写法标签定义与引用形如.. _Link 1: https://论文或文档地址See Link 1_正文引用时只需写Link Name_链接解析交给 Sphinx这也是 PyTorch 文档中大量论文引用的统一方式。四类函数的 docstring 写法差异纯 Python 函数直接写标准 docstring 即可def relu(input: Tensor, inplace: bool False) - Tensor: rrelu(input, inplaceFalse) - Tensor Applies the rectified linear unit function element-wise. See :class:~torch.nn.ReLU for more details. # implementationC 绑定函数_add_docstrC 绑定函数没有 Python 源码可挂 docstring需要用torch._C._add_docstr在文档挂载模块中绑定。指南以conv1d为例展示结构签名行、一句话描述、交叉引用、Args 段conv1d _add_docstr( torch.conv1d, r conv1d(input, weight, biasNone, stride1, padding0, dilation1, groups1) - Tensor Applies a 1D convolution over an input signal composed of several input planes. See :class:~torch.nn.Conv1d for details and output shape. Args: input: input tensor of shape :math:(\text{minibatch} , \text{in\_channels} , iW) weight: filters of shape :math:(\text{out\_channels} , kW) ... , )实际仓库中这类挂载集中出现在 torch/_torch_docs.py模块级函数与 torch/_tensor_docs.pyTensor 方法经由add_docstr_all间接调用_add_docstr。In-place 变体以_结尾的原地操作docstring 只需引用对应非原地版本。torch/_tensor_docs.py 中的abs_是最典型的现成例子add_docstr_all( abs_, r abs_() - Tensor In-place version of :meth:~Tensor.abs , )别名函数别名同样只做引用避免重复维护两份说明add_docstr_all( absolute, r absolute() - Tensor Alias for :func:abs , )常见复用模式张量形状用 LaTeX 记法形状一律写成:math:\(...)形式例如:math:(\text{minibatch} , \text{in_channels} , iH , iW)保证渲染后是统一的数学排版。参数定义一次、多处复用parse_kwargsdtype、device、generator等参数在几百个函数的 docstring 中反复出现。PyTorch 的做法是把这段文本解析成字典再格式化回填。解析工具是 torch/_torch_docs.py#L10-L25 中的parse_kwargsdef parse_kwargs(desc): rMap a description of args to a dictionary of {argname: description}. # Split on exactly 4 spaces after a newline regx re.compile(r\n\s{4}(?!\s)) kwargs [section.strip() for section in regx.split(desc)] kwargs [section for section in kwargs if len(section) 0] return {desc.split( )[0]: desc for desc in kwargs}从源码结构看它按“换行后恰好 4 个空格”切分段落即每个参数条目以 4 空格缩进起始再以条目第一个词参数名作为字典键——这解释了为什么 Args 段的续行只允许缩进 2 空格、新参数必须缩进 4 空格缩进层级本身就是解析边界。torch/_torch_docs.py 中的common_args即为按此规则定义的公共参数集。复用时的写法common_args parse_kwargs( dtype (:class:torch.dtype, optional): the desired type of returned tensor. Default: if None, same as this tensor. ) # Then use with .format(): r ... Keyword args: {dtype} {device} .format(**common_args)模板插入TF32 说明、cuDNN 可复现性说明等公共文案以模板变量注入r {tf32_note} {cudnn_reproducibility_note} .format(**reproducibility_notes, **tf32_notes)torch/_tensor_docs.py 顶部即从torch._torch_docs导入了reproducibility_notes用于此类注入。完整示例gumbel_softmax指南给出的完整示例与 torch/nn/functional.py 中gumbel_softmax的实际签名一致展示了签名行、Args含 optional 标记与 Default、Returns、note 与 Examples 的组合def gumbel_softmax( logits: Tensor, tau: float 1, hard: bool False, eps: float 1e-10, dim: int -1, ) - Tensor: r Sample from the Gumbel-Softmax distribution and optionally discretize. Args: logits (Tensor): [..., num_features] unnormalized log probabilities tau (float): non-negative scalar temperature hard (bool): if True, the returned samples will be discretized as one-hot vectors, but will be differentiated as if it is the soft sample in autograd. Default: False dim (int): A dimension along which softmax will be computed. Default: -1 Returns: Tensor: Sampled tensor of same shape as logits from the Gumbel-Softmax distribution. If hardTrue, the returned samples will be one-hot, otherwise they will be probability distributions that sum to 1 across dim. .. note:: This function is here for legacy reasons, may be removed from nn.Functional in the future. Examples:: logits torch.randn(20, 32) # Sample soft categorical using reparametrization trick: F.gumbel_softmax(logits, tau1, hardFalse) # Sample hard categorical using Straight-through trick: F.gumbel_softmax(logits, tau1, hardTrue) .. _Link 1: https://论文地址 # implementation对照源码可以看到几个值得注意的细节hardTrue的 straight-through 语义、dim的默认值-1、以及“可能在未来移除”的 note——这些正是 docstring 承担 API 契约说明职责的体现。快速自检清单写完一个 PyTorch docstring 后按指南的清单逐项核对使用了 raw stringr首行包含完整函数签名含默认值与返回类型无句号有一句话的简要描述Args 段覆盖所有参数并标注类型可选参数都写了Default:使用了 Sphinx 交叉引用:func:、:class:、:meth:数学表达用:math:/.. math::书写Examples 段至少一个可运行示例提示符重要注意点用 note/warning admonition 表达与torch.nn中对应的模块类建立了:class:引用张量形状使用统一的 LaTeX 记法缩进与格式符合前述约定Sphinx Role 速查与排版约定常用 role 一览Role用途示例:class:\~torch.nn.Module| 类引用 |:class:~torch.nn.Conv2d:func:\torch.function| 函数引用 |:func:torch.softmax:meth:\~Tensor.method| 方法引用 |:meth:~Tensor.abs:attr:\attribute| 属性引用 |:attr:data:math:\equation| 行内公式 |:math:x^2:ref:\label| 文档内引用 |:ref:tensor-attributescode行内代码双反引号TrueNoneFalse其余排版约定缩进代码块 4 空格参数描述的续行 2 空格注意新参数条目必须是 4 空格否则parse_kwargs无法正确切分见上文解析实现行宽尽量控制在 100 字符以内句号句子以句号结尾但签名行除外反引号代码一律用双反引号常见类型Tensor、int、float、bool、str、tuple、list等。小结PyTorch 的 docstring 规范本质上是一套“面向 Sphinx 渲染 面向 doctest 校验 面向文档代码复用”的三合一约定raw string 保证 LaTeX 原样传递固定的十段式结构保证 API 文档信息密度一致_add_docstr/add_docstr_all机制让 C 绑定 API 与纯 Python API 拥有同等质量的文档parse_kwargs与模板注入则让公共参数说明只维护一份。掌握了签名行、交叉引用、Args 缩进规则与四类函数的差异写法后即可在任何 PyTorch 函数上产出与 torch/_tensor_docs.py、torch/_torch_docs.py 既有风格完全一致的 docstring。【免费下载链接】pytorchTensors and Dynamic neural networks in Python with strong GPU acceleration项目地址: https://gitcode.com/GitHub_Trending/py/pytorch创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考