You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

comments_specification.md 14 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. # MindSpore API注释规范
  2. <!-- TOC -->
  3. - [MindSpore API注释规范](#mindspore-api注释规范)
  4. - [总体说明](#总体说明)
  5. - [Python API注释规范](#python-api注释规范)
  6. - [注释格式](#注释格式)
  7. - [注意事项](#注意事项)
  8. - [Python示例](#python示例)
  9. - [类](#类)
  10. - [方法](#方法)
  11. - [公式](#公式)
  12. - [链接](#链接)
  13. - [C++ API注释规范](#c-api注释规范)
  14. <!-- /TOC -->
  15. ## 总体说明
  16. - MindSpore Python代码注释遵循[Google Python Style Guide](https://google.github.io/styleguide/pyguide.html),由Sphinx工具自动生成API文档,注释样例和支持情况可参考[Example Google Style Python Docstrings](https://www.sphinx-doc.org/en/master/usage/extensions/example_google.html)和[Support for NumPy and Google style docstrings](https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html)。
  17. - MindSpore C++代码需按照命名空间的设计,分别编写Markdown文件。
  18. ## Python API注释规范
  19. ### 注释格式
  20. 类和方法的注释都采用如下格式:
  21. ```rst
  22. Summary.
  23. More elaborate description.
  24. Note:
  25. Description.
  26. Args:
  27. Arg1 (Type): Description. Default: xxx.
  28. Arg2 (Type): Description.
  29. - Sub-argument1 or Value1 of Arg2: Description.
  30. - Sub-argument2 or Value2 of Arg2: Description.
  31. Returns:
  32. Type, description.
  33. Raises:
  34. Type: Description.
  35. Examples:
  36. >>> Sample Code
  37. ```
  38. 其中,
  39. - `Summary`:简单描述该接口的功能。
  40. - `More elaborate description`:详细描述该接口的功能和如何使用等信息。
  41. - `Note`:描述使用该接口时需要注意的事项。特别注意不能写成`Notes`。
  42. - `Args`:接口参数信息,包含参数名、参数类型、取值范围、默认值等。
  43. - `Returns`:返回值信息,包含返回值类型等。
  44. - `Raises`:异常信息,包含异常类型、含义等。
  45. - `Examples`:样例代码。
  46. 针对算子和Cell的注释,需要在`Examples`前添加`Inputs`、`Outputs`和`Supported Platforms`三项内容。
  47. - `Inputs`和`Outputs`:用于描述实例化后,算子的输入和输出的类型和shape,输入名可以和样例相同。建议在注释中给出对应的数学公式。
  48. - `Supported Platforms`:用于描述算子支持的硬件平台,名称前后需添加``,存在多个时使用空格隔开。
  49. ```rst
  50. Inputs:
  51. - **input_name1** (Type) - Description.
  52. - **input_name2** (Type) - Description.
  53. Outputs:
  54. Type and shape, description.
  55. Supported Platforms:
  56. ``Ascend`` ``GPU`` ``CPU``
  57. ```
  58. ### 注意事项
  59. - 整体要求
  60. - 类或方法必须书写的注释项有:`Summary`、`Args`、`Returns`和`Raises`。如果函数中没有相关信息(如`Args`、`Returns`和`Raises`等),不需要写None(如`Raises:None`),直接省略注释项即可。
  61. - 以目录为粒度生成API时,__init__文件头部的注释内容会呈现在网页开头;以文件为粒度生成API时,该文件头部的注释内容会呈现在网页开头。这些注释内容需包含相应模块的整体说明。
  62. - 注释中包含反斜杠时,需要将头部的`"""`改成`r"""`。
  63. - 冒号要求:关键字(如`Args`、`Returns`等)后面有冒号":";参数名(如`Arg1`、`Arg2`等)后面有冒号":",冒号后需有空格。`Summary`和`Returns`的内容中不能包含冒号。
  64. - 空行要求:不同类型(如`Args`、`Returns`等)的内容之间需有空行,同种类型(如`Arg1`、`Arg2`等)的内容之间不需要空行。采用无序或有序列表描述内容时,整个列表内容与上方内容之间需增加一个空行。
  65. - 空格要求:`Args`和`Raises`内容的换行需要缩进4个空格,`Args`的子参数或取值、`Inputs`、`Outputs`和`Returns`等无序或有序列表内容的换行不需要缩进,与上一行的正文起始位置对齐。`Args`中参数名和类型的`(`之间需要有空格。
  66. - `Args`注释说明
  67. - 常见参数类型有:
  68. - 基本数据类型:`int`、`float`、`bool`、`str`、`list`、`dict`、`set`、`tuple`、`numpy.ndarray`。
  69. - dtype:如果是mindspore.dtype里的值,写成`mindspore.dtype`,如果是numpy类型,写成`numpy.dtype`。其他按实际情况写。
  70. - 一个参数有多个可选类型:Union[类型1, 类型2],如`Union[Tensor, Number]`。
  71. - list类型:list[具体类型],如`list[str]`。
  72. - 可选类型统一格式:(类型, optional)。
  73. - 其他类型:Tensor或其他具体类型或方法名。
  74. - `Returns`注释说明
  75. - 如果返回值类型或维度发生变化,需要说明返回值与输入的关系。
  76. - 多个返回值时,分行写,网页显示时不分行,无序列表的方式可支持分行。
  77. - `Examples`注释说明
  78. - `Examples`中的内容需在每行代码开头加上```>>>```,多行代码(含类或函数定义、人为换行等)或空行的开头需加上```...```,输出结果行开头不需要加任何符号。
  79. - `Examples`中需提供实际的代码,如果需提示参考其他Examples,请使用Note。
  80. - ops算子注释采用PyNative模式写作,可运行的需给出运行结果。
  81. - 业界共识的情况可省略import,如np、nn等。
  82. - 导入路径较长和必须自定义别名的导入需要加`from xxx import xxx as something`或`import xxx`,导入路径短的尽量放到代码中。
  83. - `Inputs`和`Outputs`注释说明
  84. - 类型是Tensor时,需描述shape,并按:math:`(N, C, X)`格式写作。
  85. - 公式
  86. - 行公式(单独占一行,居中)
  87. ```rst
  88. .. math::
  89. formula
  90. ```
  91. - 行内嵌公式(与其他同行文字显示在一起,不居中)
  92. ```rst
  93. xxx :math:`formula` xxx
  94. ```
  95. - 公式中带有含下划线的变量,且下划线后存在多个字母(如xxx_yyy),请根据实际需要选择以下其中一种方式。
  96. 1. 多个字母用{}括起来(如xxx_{yyy}),可将下划线后的内容作为下标,显示为$xxx_{yyy}$。
  97. 2. 在下划线前增加反斜杠(如xxx\\_yyy),可将完整显示变量名称,显示为xxx_yyy。
  98. - 父类方法的显示
  99. - 默认不显示父类方法。
  100. - 可通过在Sphinx工程rst文件的模块下添加`:inherited-members:`,指定需要显示父类方法,详细可参考<https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html>。
  101. - 链接
  102. - 只显示标题(如例子中的name),不显示详细地址。
  103. 引用的地方需这样写:
  104. ```rst
  105. `name`_
  106. ```
  107. 提供链接的地方需这样写:
  108. ```rst
  109. .. _`name`: https://xxx
  110. ```
  111. 注意:
  112. - 如有换行请注意缩进,参考下方具体示例。
  113. - https前需有空格。
  114. 或者可以采用以下简化写法,只在引用的地方写即可。
  115. ```rst
  116. `name <https://xxx>`_
  117. ```
  118. - 直接显示详细地址。
  119. ```rst
  120. https://xxx
  121. ```
  122. - 表格(详细可参考<https://sublime-and-sphinx-guide.readthedocs.io/en/latest/tables.html#list-table-directive>)
  123. ```rst
  124. .. list-table:: Title # 表格标题
  125. :widths: 25 25 25 # 表格列宽
  126. :header-rows: 1
  127. * - Heading row 1, column 1 # 表头
  128. - Heading row 1, column 2
  129. - Heading row 1, column 3
  130. * - Row 1, column 1
  131. - # 表格内容为空
  132. - Row 1, column 3
  133. * - Row 2, column 1
  134. - Row 2, column 2
  135. - Row 2,
  136. # 表格内容如需换行,在中间增加一个空行
  137. column 3
  138. ```
  139. 显示效果:
  140. ![image](./resource/list_table.png)
  141. - 详细说明默认不换行,如需换行,需以列表或code-block的方式写作。
  142. - 列表方式:
  143. ```rst
  144. - Content1
  145. - Content2
  146. - Content3
  147. ```
  148. - code-block方式:
  149. ```rst
  150. .. code-block::
  151. Content1
  152. Content2
  153. Content3
  154. ```
  155. ### Python示例
  156. #### 类
  157. ```python
  158. class Tensor(Tensor_):
  159. """
  160. Tensor is used for data storage.
  161. Tensor inherits tensor object in C++.
  162. Some functions are implemented in C++ and some functions are implemented in Python.
  163. Args:
  164. input_data (Tensor, float, int, bool, tuple, list, numpy.ndarray): Input data of the tensor.
  165. dtype (:class:`mindspore.dtype`): Input data should be None, bool or numeric type defined in `mindspore.dtype`.
  166. The argument is used to define the data type of the output tensor. If it is None, the data type of the
  167. output tensor will be as same as the `input_data`. Default: None.
  168. Outputs:
  169. Tensor, with the same shape as `input_data`.
  170. Examples:
  171. >>> # initialize a tensor with input data
  172. >>> t1 = Tensor(np.zeros([1, 2, 3]), mindspore.float32)
  173. >>> assert isinstance(t1, Tensor)
  174. >>> assert t1.shape == (1, 2, 3)
  175. >>> assert t1.dtype == mindspore.float32
  176. ...
  177. >>> # initialize a tensor with a float scalar
  178. >>> t2 = Tensor(0.1)
  179. >>> assert isinstance(t2, Tensor)
  180. >>> assert t2.dtype == mindspore.float64
  181. """
  182. def __init__(self, input_data, dtype=None):
  183. ...
  184. ```
  185. 显示效果可访问[这里](https://www.mindspore.cn/doc/api_python/zh-CN/master/mindspore/mindspore.html#mindspore.Tensor)。
  186. #### 方法
  187. ```python
  188. def ms_function(fn=None, obj=None, input_signature=None):
  189. """
  190. Create a callable MindSpore graph from a python function.
  191. This allows the MindSpore runtime to apply optimizations based on graph.
  192. Args:
  193. fn (Function): The Python function that will be run as a graph. Default: None.
  194. obj (Object): The Python Object that provides the information for identifying the compiled function. Default:
  195. None.
  196. input_signature (MetaTensor): The MetaTensor which describes the input arguments. The MetaTensor specifies
  197. the shape and dtype of the Tensor and they will be supplied to this function. If input_signature
  198. is specified, each input to `fn` must be a `Tensor`. And the input parameters of `fn` cannot accept
  199. `**kwargs`. The shape and dtype of actual inputs should keep the same as input_signature. Otherwise,
  200. TypeError will be raised. Default: None.
  201. Returns:
  202. Function, if `fn` is not None, returns a callable function that will execute the compiled function; If `fn` is
  203. None, returns a decorator and when this decorator invokes with a single `fn` argument, the callable function is
  204. equal to the case when `fn` is not None.
  205. Examples:
  206. >>> def tensor_add(x, y):
  207. ... z = F.tensor_add(x, y)
  208. ... return z
  209. ...
  210. >>> @ms_function
  211. ... def tensor_add_with_dec(x, y):
  212. ... z = F.tensor_add(x, y)
  213. ... return z
  214. ...
  215. >>> @ms_function(input_signature=(MetaTensor(mindspore.float32, (1, 1, 3, 3)),
  216. ... MetaTensor(mindspore.float32, (1, 1, 3, 3))))
  217. ... def tensor_add_with_sig(x, y):
  218. ... z = F.tensor_add(x, y)
  219. ... return z
  220. ...
  221. >>> x = Tensor(np.ones([1, 1, 3, 3]).astype(np.float32))
  222. >>> y = Tensor(np.ones([1, 1, 3, 3]).astype(np.float32))
  223. ...
  224. >>> tensor_add_graph = ms_function(fn=tensor_add)
  225. >>> out = tensor_add_graph(x, y)
  226. >>> out = tensor_add_with_dec(x, y)
  227. >>> out = tensor_add_with_sig(x, y)
  228. """
  229. ...
  230. ```
  231. 显示效果可访问[这里](https://www.mindspore.cn/doc/api_python/zh-CN/master/mindspore/mindspore.html#mindspore.ms_function)。
  232. #### 公式
  233. ```python
  234. class Conv2d(_Conv):
  235. r"""
  236. 2D convolution layer.
  237. Applies a 2D convolution over an input tensor which is typically of shape :math:`(N, C_{in}, H_{in}, W_{in})`,
  238. where :math:`N` is batch size, :math:`C_{in}` is channel number, and :math:`H_{in}, W_{in})` are height and width.
  239. For each batch of shape :math:`(C_{in}, H_{in}, W_{in})`, the formula is defined as:
  240. .. math::
  241. out_j = \sum_{i=0}^{C_{in} - 1} ccor(W_{ij}, X_i) + b_j,
  242. ...
  243. """
  244. ```
  245. 显示效果可访问[这里](https://www.mindspore.cn/doc/api_python/zh-CN/master/mindspore/mindspore.nn.html#mindspore.nn.Conv2d)。
  246. #### 链接
  247. ```python
  248. class BatchNorm(PrimitiveWithInfer):
  249. r"""
  250. Batch Normalization for input data and updated parameters.
  251. Batch Normalization is widely used in convolutional neural networks. This operation
  252. applies Batch Normalization over input to avoid internal covariate shift as described
  253. in the paper `Batch Normalization: Accelerating Deep Network Training by Reducing Internal
  254. Covariate Shift <https://arxiv.org/abs/1502.03167>`_. It rescales and recenters the
  255. features using a mini-batch of data and the learned parameters which can be described
  256. in the following formula,
  257. ...
  258. """
  259. ```
  260. 显示效果可访问[这里](https://www.mindspore.cn/doc/api_python/zh-CN/master/mindspore/mindspore.ops.html#mindspore.ops.BatchNorm)。
  261. ## C++ API注释规范
  262. - Markdown文件命名需与命名空间相同。
  263. - Markdown文件内部格式如下,可参考[样例](https://www.mindspore.cn/doc/api_cpp/zh-CN/master/lite.html)。
  264. ```markdown
  265. # The name of namespace
  266. The link of header file.
  267. ## The name of class
  268. The description of class.
  269. The name of attribute or function.
  270. The description of attribute or function.
  271. ```