docstring について
PyTorch のコントリビューター向けに、関数やメソッドの docstring 作成規約を説明するスキルです。reST の構成、引数、例、相互参照の書式を扱います。
主な機能
- 01docstring の構成を定義
- 02引数と戻り値の記述方法
- 03reST の相互参照を解説
- 04関数種別ごとの例を掲載
- 05スタイルチェックリスト
活用シーン
- 01PyTorch 関数の docstring 作成
- 02C バインド関数の文書化
- 03例と API 参照の追加
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ pytorch/ pytorch --skill docstringインストール後、Claude Code で/docstringを入力して読み込まれたか確認します。
詳細
PyTorch Docstring 作成ガイド
このスキルでは、torch/_tensor_docs.py と torch/nn/functional.py の規約に従って、PyTorch プロジェクトの関数やメソッドの Docstring を作成する方法について説明します。
一般原則
- LaTeX や数式のバックスラッシュに関する問題を避けるため、すべての Docstring にraw 文字列(
r"""...""")を使用します - ドキュメントには Sphinx/reStructuredText(reST)形式を使用します
- 簡潔かつ完全に記述し、重要な情報をすべて含めます
- 可能な場合は、必ず例を含めます
- 関連する関数やクラスへの相互参照を使用します
Docstring の構成
1. 関数シグネチャ(1 行目)
すべてのパラメーターを示す関数シグネチャから始めます。
r"""function_name(param1, param2, *, kwarg1=default1, kwarg2=default2) -> ReturnType
注意:
- 関数名を含めます
- 位置引数とキーワード専用引数を示します(区切りには
*を使用します) - デフォルト値を含めます
- 戻り値の型注釈を示します
- この行の末尾にピリオドを付けないでください
2. 簡潔な説明
関数の動作を 1 行で説明します。
r"""conv2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1) -> 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``
4. 相互参照
Sphinx ロールを使用して、関連するクラスや関数へのリンクを作成します。
:class:\~torch.nn.ModuleName`` - クラスへのリンク:func:\torch.function_name`` - 関数へのリンク:meth:\~Tensor.method_name`` - メソッドへのリンク:attr:\attribute_name`` - 属性への参照~プレフィックスを付けると、最後の要素のみが表示されます(例:torch.nn.Conv2dではなくConv2d)
例:
See :class:`~torch.nn.Conv2d` for details and output shape.
5. 注記と警告
重要な情報にはアドモニションを使用します。
.. note::
This function doesn't work directly with NLLLoss,
which expects the Log to be computed between the Softmax and itself.
Use log_softmax instead (it's 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`.
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 スペース字下げします
7. Keyword 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 ``hard=True``, the returned samples will be one-hot, otherwise they will
be probability distributions that sum to 1 across `dim`.
または、文脈から明らかな場合は、関数シグネチャの行に含めるだけでもかまいません。
9. Examples セクション
可能な場合は、必ず例を含めます。
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, padding=1)
書式ルール:
- 二重コロンを付けた
Examples::を使用します - Python コードには
>>>プロンプトを使用します - 必要に応じて
#を使ったコメントを含めます - 理解の助けになる場合は、実際の出力も示します(
>>>を付けずに字下げします)
10. 外部参照
論文や外部ドキュメントへのリンクを作成します。
.. _Link Name:
https://arxiv.org/abs/1611.00712
本文から参照します:See `Link Name`_
メソッドの種類
ネイティブ Python 関数
通常の Python 関数には標準的な Docstring を使用します。
def relu(input: Tensor, inplace: bool = False) -> Tensor:
r"""relu(input, inplace=False) -> Tensor
Applies the rectified linear unit function element-wise. See
:class:`~torch.nn.ReLU` for more details.
"""
# implementation
C バインド関数(add_docstr を使用)
C バインド関数には _add_docstr を使用します。
conv1d = _add_docstr(
torch.conv1d,
r"""
conv1d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1) -> 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)`
...
""",
)
インプレース版
インプレース操作(末尾が _ のもの)では、元の関数を参照します。
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`
""",
)
よく使うパターン
Shape の記述
テンソルの Shape には LaTeX 数式表記を使用します。
:math:`(\text{minibatch} , \text{in\_channels} , iH , iW)`
再利用可能な引数の定義
よく使う引数は一度定義して再利用します。
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)
テンプレートの挿入
再現性に関する注記や、その他の共通テキストを挿入します。
r"""
{tf32_note}
{cudnn_reproducibility_note}
""".format(**reproducibility_notes, **tf32_notes)
完全な例
すべての要素を含む完全な例を示します。
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 ``hard=True``, 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, tau=1, hard=False)
>>> # Sample hard categorical using "Straight-through" trick:
>>> F.gumbel_softmax(logits, tau=1, hard=True)
.. _Link 1:
https://arxiv.org/abs/1611.00712
"""
# implementation
クイックチェックリスト
PyTorch の docstring を書く際は、次の点を確認してください。
- 生文字列を使用する(
r""") - 1 行目に関数シグネチャを記載する
- 簡潔な説明を記載する
- Args セクションにすべてのパラメーターと型を記載する
- 省略可能なパラメーターにはデフォルト値を記載する
- Sphinx の相互参照(
:func:、:class:、:meth:)を使用する - 必要に応じて数式を追加する
- Examples セクションに少なくとも 1 つの例を含める
- 重要な注意点について警告や注記を追加する
- 関連するモジュールクラスへのリンクに
:class:を使用する - テンソルの形状には適切な数式表記を使用する
- 一貫した書式とインデントに従う
よく使う Sphinx ロールの一覧
:class:\~torch.nn.Module`` - クラスへの参照:func:\torch.function`` - 関数への参照:meth:\~Tensor.method`` - メソッドへの参照:attr:\attribute`` - 属性への参照:math:\equation`` - インライン数式:ref:\label`` - 内部参照``code``- インラインコード(バッククォートを 2 つ使用)
補足事項
- インデント:コードには 4 つのスペースを使用し、パラメーターの説明を継続する行には 2 つのスペースを使用します
- 行の長さ:可能な場合は、行を 100 文字未満にするようにしてください
- ピリオド:文末にはピリオドを付けますが、シグネチャ行には付けません
- バッククォート:コードにはバッククォートを 2 つ使用します:
``True`` ``None`` ``False`` - 型:一般的な型には
Tensor、int、float、bool、str、tuple、listなどがあります