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_en.md 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. # MindSpore API Comment Specifications
  2. <!-- TOC -->
  3. - [MindSpore API Comment Specifications](#mindspore-api-comment-specifications)
  4. - [Overview](#overview)
  5. - [Python API Comment Specifications](#python-api-comment-specifications)
  6. - [Comment Format](#comment-format)
  7. - [Precautions](#precautions)
  8. - [Python Example](#python-example)
  9. - [Class](#class)
  10. - [Method](#method)
  11. - [Formula](#formula)
  12. - [Link](#link)
  13. - [C++ API Comment Specifications](#c-api-comment-specifications)
  14. <!-- /TOC -->
  15. ## Overview
  16. - MindSpore Python code comments comply with [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html). An API document is automatically generated by the Sphinx tool. For comment examples and support details, see [Example Google Style Python Docstrings](https://www.sphinx-doc.org/en/master/usage/extensions/example_google.html) and [Support for NumPy and Google style docstrings](https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html).
  17. - MindSpore C++ code needs to be compiled in Markdown files based on the namespace design.
  18. ## Python API Comment Specifications
  19. ### Comment Format
  20. The comments of classes and methods are in the following format:
  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. The format items are described as follows:
  39. - `Summary`: briefly describes the API function.
  40. - `More elaborate description`: describes the function and usage of an API in detail.
  41. - `Note`: describes precautions for using an API. Do not use `Notes`.
  42. - `Args`: API parameter information, including the parameter name, type, value range, and default value.
  43. - `Returns`: return value information, including the return value type.
  44. - `Raises`: exception information, including the exception type and meaning.
  45. - `Examples`: sample code
  46. For comments of operators and cells, add `Inputs`, `Outputs` and `Supported Platforms` before `Examples`.
  47. - `Inputs` and `Outputs`: describes the input and output types and shapes of the operators after instantiation. The input name can be the same as that in the example. It is recommended to provide the corresponding mathematical formula in the comment.
  48. - `Supported Platforms`: describes the hardware platforms supported by the operator. Add `` before and after the platform name, and use space to separate them when there are more than one.
  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. ### Precautions
  59. - Overall Requirements
  60. - The comment items required for a class or method are as follows: `Summary`, `Args`, `Returns`, and `Raises`. If a function does not contain related information (such as `Args`, `Returns`, and `Raises`), do not write None (for example, `Raises: None`), but directly omit the comment item.
  61. - When an API is generated by directory, the comments in the \_\_init\_\_ file header are displayed at the beginning of the web page. When an API is generated by file, the comments at the beginning of the file are displayed at the beginning of the web page. The comments must contain the overall description of the corresponding modules.
  62. - If a comment contains a backslash (\\), change `"""` in the header to `r"""`.
  63. - Colon requirements: Keywords (such as `Args` and `Returns`) and parameter names (such as `Arg1` or `Arg2`) are followed by colons (:). A colon must be followed by a space. The content of `Summary` and `Returns` cannot contain colons.
  64. - Blank line requirements: A blank line is required between contents of different types (such as `Args` and `Returns`). A blank line is not required between contents of the same type (for example, `Arg1` and `Arg2`). If the content is described in an unordered or ordered list, a blank line must be added between the content in the list and the content above the list.
  65. - Space requirements: The newline characters of `Args` and `Raises` must be indented by four spaces. The sub-parameters or values of `Args` and line breaks for disordered or ordered content of `Inputs`, `Outputs` and `Returns` do not need indents and are aligned with the start position of the previous line. In `Args`, there must be a space between the parameter name and the `(` of the type.
  66. - `Args` Comment
  67. - Common parameter types are as follows:
  68. - Basic data types: `int`, `float`, `bool`, `str`, `list`, `dict`, `set`, `tuple` and `numpy.ndarray`.
  69. - dtype: For the value of mindspore.dtype, set this parameter to `mindspore.dtype`. For the value of the numpy type, set this parameter to `numpy.dtype`. Set other parameters based on the actual requirements.
  70. - One parameter with multiple optional types: Union [type 1, type 2], for example, `Union[Tensor, Number]`.
  71. - List type: list[Specific type], for example, `list[str]`.
  72. - The format of optional types is as follows: (Type, optional).
  73. - Other types: Tensor, other specific types, or method names.
  74. - `Returns` Comment
  75. - If the return value type or dimension changes, describe the relationship between the return value and the input.
  76. - If there are multiple return values, write them in different lines. The line difference is not displayed on the web page. The unordered list supports return values in different lines.
  77. - `Examples` Comment
  78. - For the content in `Examples`, ```>>>``` should be added at the beginning of each line of code. For multiple lines (including classes, function definitions or manual switch line) and blank lines, ```...``` is needed at the beginning of these lines. There is no need to add any symbols at the beginning of the output result line.
  79. - Actual code needs to be provided in `Examples`. If you need to refer to other Examples, use Note.
  80. - The comments of the ops operator are written in PyNative mode. If the operator can be executed, the execution result must be provided.
  81. - Import can be omitted in the case of industry consensus, such as np and nn.
  82. - If the import path is long or a user-defined alias is required, add `from xxx import xxx as something` or `import xxx`. If the import path is short, place it in the code.
  83. - `Inputs` and `Outputs` Comment
  84. - If the data type is Tensor, describe the shape in the format of :math:`(N, C, X)`.
  85. - Formula
  86. - Line formula (in the middle of the singly occupied line)
  87. ```rst
  88. .. math::
  89. formula
  90. ```
  91. - Line-embedded formula (displayed together with other peer text, not in the middle)
  92. ```rst
  93. xxx :math:`formula` xxx
  94. ```
  95. - If the formula contains an underscored variable and the underscore is followed by multiple letters (for example, xxx_yyy) , select one of the following methods based on the site requirements:
  96. 1. Multiple letters are enclosed in braces ({}), for example, xxx_{yyy}. The content following the underscore can be used as the subscript, which is displayed as $xxx_{yyy}$.
  97. 2. If a backslash (\\) is added before an underscore (_), for example, xxx\\_yyy, the complete variable name is displayed as xxx_yyy.
  98. - Parent Class Method Display
  99. - By default, the parent class method is not displayed.
  100. - You can add `:inherited-members:` to the module of the RST file in the Sphinx project to specify the parent class method to be displayed. For details, see <https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html>.
  101. - Link
  102. - Only the title (such as the name in the following example) is displayed. The detailed address is not displayed.
  103. Write a quotation in the following format:
  104. ```rst
  105. `name`_
  106. ```
  107. Provide a link in the following format:
  108. ```rst
  109. .. _`name`: https://xxx
  110. ```
  111. Note:
  112. - If there is a newline character, indent it. For details, see the following table.
  113. - There must be a space before https.
  114. Alternatively, you can use the following simplified format, that is, write only in the place where the reference is made.
  115. ```rst
  116. `name <https://xxx>`_
  117. ```
  118. - Display the detailed address:
  119. ```rst
  120. https://xxx
  121. ```
  122. - Table (For details, see section <https://sublime-and-sphinx-guide.readthedocs.io/en/latest/tables.html#list-table-directive>.)
  123. ```rst
  124. .. list-table:: Title # Table title
  125. :widths: 25 25 25 # Table column width
  126. :header-rows: 1
  127. * - Heading row 1, column 1 # Table header
  128. - Heading row 1, column 2
  129. - Heading row 1, column 3
  130. * - Row 1, column 1
  131. - #The table is empty.
  132. - Row 1, column 3
  133. * - Row 2, column 1
  134. - Row 2, column 2
  135. - Row 2,
  136. # If a newline is required for the table content, add a blank line in the middle.
  137. column 3
  138. ```
  139. Display effect:
  140. ![image](./resource/list_table.png)
  141. - By default, the detailed description is displayed in one line. If you need to display it in another line, write it in the form of a list or code-block.
  142. - List mode:
  143. ```rst
  144. - Content1
  145. - Content2
  146. - Content3
  147. ```
  148. - Code-Block mode:
  149. ```rst
  150. .. code-block::
  151. Content1
  152. Content2
  153. Content3
  154. ```
  155. ### Python Example
  156. #### Class
  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. For details about the display effect, click [here](https://www.mindspore.cn/doc/api_python/en/master/mindspore/mindspore.html#mindspore.Tensor).
  186. #### Method
  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. For details about the display effect, click [here](https://www.mindspore.cn/doc/api_python/en/master/mindspore/mindspore.html#mindspore.ms_function).
  232. #### Formula
  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. For details about the display effect, click [here](https://www.mindspore.cn/doc/api_python/en/master/mindspore/mindspore.nn.html#mindspore.nn.Conv2d).
  246. #### Link
  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. For details about the display effect, click [here](https://www.mindspore.cn/doc/api_python/en/master/mindspore/mindspore.ops.html#mindspore.ops.BatchNorm).
  261. ## C++ API Comment Specifications
  262. - The name of the Markdown file must be the same as that of the namespace.
  263. - The internal format of the Markdown file is as follows. For details, see [Sample](https://www.mindspore.cn/doc/api_cpp/en/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. ```