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 29 kB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  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. - [Comment Format](#comment-format)
  15. - [Precautions](#precautions)
  16. - [C++ Example](#c-example)
  17. <!-- /TOC -->
  18. ## Overview
  19. - 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).
  20. - MindSpore C++ code needs to be compiled in Markdown files based on the namespace design.
  21. ## Python API Comment Specifications
  22. ### Comment Format
  23. The comments of classes and methods are in the following format:
  24. ```text
  25. Summary.
  26. More elaborate description.
  27. .. warning::
  28. Warning description.
  29. Note:
  30. Note description.
  31. Args:
  32. Arg1 (Type): Description. Default: xxx.
  33. Arg2 (Type): Description.
  34. - Sub-argument1 or Value1 of Arg2: Description.
  35. - Sub-argument2 or Value2 of Arg2: Description.
  36. Returns:
  37. Type, description.
  38. Raises:
  39. Type: Description.
  40. Examples:
  41. >>> Sample Code
  42. ```
  43. The format items are described as follows:
  44. - `Summary`: briefly describes the API function. If the description begins with a verb, the module must use the same verb form, the first person (the original form of the verb) or the third person (add an "s" after the verb), and the first person is recommended.
  45. - `More elaborate description`: describes the function and usage of an API in detail.
  46. - `warning`: describes warnings for using an API to avoid negative consequences.
  47. - `Note`: describes precautions for using an API. Do not use `Notes`.
  48. - `Args`: API parameter information, including the parameter name, type, value range, and default value.
  49. - `Returns`: return value information, including the return value type.
  50. - `Raises`: exception information, including the exception type and meaning.
  51. - `Examples`: sample code
  52. For comments of operators and cells, add `Inputs`, `Outputs` and `Supported Platforms` before `Examples`.
  53. - `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.
  54. - `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.
  55. ```text
  56. Inputs:
  57. - **input_name1** (Type) - Description.
  58. - **input_name2** (Type) - Description.
  59. Outputs:
  60. Type and shape, description.
  61. Supported Platforms:
  62. ``Ascend`` ``GPU`` ``CPU``
  63. ```
  64. ### Precautions
  65. - Overall Requirements
  66. - 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.
  67. - 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.
  68. - If a comment contains a backslash (\\), change `"""` in the header to `r"""`.
  69. - If the comment begins with a verb, the module must use the same verb form, the first person (the original form of the verb) or the third person (add an "s" after the verb), and the first person is recommended.
  70. - 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.
  71. - Blank line requirements:
  72. 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`).
  73. ```text
  74. High-Level API for Training or Testing.
  75. Args:
  76. network (Cell): A training or testing network.
  77. loss_fn (Cell): Objective function, if `loss_fn` is None, the
  78. network should contain the logic of loss and grads calculation, and the logic
  79. of parallel if needed. Default: None.
  80. Returns:
  81. function, original function.
  82. ```
  83. 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.
  84. ```text
  85. Args:
  86. amp_level (str): Option for argument `level` in `mindspore.amp.build_train_network`, level for mixed
  87. precision training. Supports ["O0", "O2", "O3", "auto"]. Default: "O0".
  88. - O0: Do not change.
  89. - O2: Cast network to float16, keep batchnorm run in float32, using dynamic loss scale.
  90. - O3: Cast network to float16, with additional property 'keep_batchnorm_fp32=False'.
  91. - auto: Set to level to recommended level in different devices. Set level to "O2" on GPU, set
  92. level to "O3" Ascend. The recommended level is choose by the export experience, cannot
  93. always generalize. User should specify the level for special network.
  94. "O2" is recommended on GPU, "O3" is recommended on Ascend.
  95. ```
  96. - Space requirements:
  97. The newline characters of `Args` and `Raises` must be indented by four spaces.
  98. ```text
  99. Args:
  100. lr_power (float): Learning rate power controls how the learning rate decreases during training,
  101. must be less than or equal to zero. Use fixed learning rate if `lr_power` is zero.
  102. use_locking (bool): If True, the var and accumulation tensors will be protected from being updated.
  103. Default: False.
  104. Raises:
  105. TypeError: If `lr`, `l1`, `l2`, `lr_power` or `use_locking` is not a float.
  106. If `use_locking` is not a bool.
  107. If dtype of `var`, `accum`, `linear` or `grad` is neither float16 nor float32.
  108. If dtype of `indices` is not int32.
  109. ```
  110. The following contents do not need indents and are aligned with the start position of the previous line.
  111. 1. The sub-parameters or values of `Args`
  112. ```text
  113. Args:
  114. parallel_mode (str): There are five kinds of parallel modes, "stand_alone", "data_parallel",
  115. "hybrid_parallel", "semi_auto_parallel" and "auto_parallel". Default: "stand_alone".
  116. - stand_alone: Only one processor is working.
  117. - data_parallel: Distributes the data across different processors.
  118. - hybrid_parallel: Achieves data parallelism and model parallelism
  119. manually.
  120. - semi_auto_parallel: Achieves data parallelism and model parallelism by
  121. setting parallel strategies.
  122. ```
  123. 2. The line breaks for disordered or ordered content of `Inputs`, `Outputs` and `Returns`
  124. ```text
  125. Inputs:
  126. - **var** (Parameter) - The variable to be updated. The data type must be float16 or float32.
  127. - **accum** (Parameter) - The accumulation to be updated, must be same data type and shape as `var`.
  128. - **linear** (Parameter) - the linear coefficient to be updated, must be same data type and shape
  129. as `var`.
  130. - **grad** (Tensor) - A tensor of the same type as `var`, for the gradient.
  131. - **indices** (Tensor) - A vector of indices in the first dimension of `var` and `accum`.
  132. The shape of `indices` must be the same as `grad` in the first dimension. The type must be int32.
  133. Outputs:
  134. Tuple of 3 Tensor, the updated parameters.
  135. - **var** (Tensor) - Tensor, has the same shape
  136. and data type as `var`.
  137. - **accum** (Tensor) - Tensor, has the same shape
  138. and data type as `accum`.
  139. - **linear** (Tensor) - Tensor, has the same shape
  140. and data type as `linear`.
  141. ```
  142. 3. `Note` and `warning`
  143. ```text
  144. .. warning::
  145. This is warning text. Use a warning for information the user must
  146. understand to avoid negative consequences.
  147. If warning text runs over a line, make sure the lines wrap and are indented to
  148. the same level as the warning tag.
  149. ```
  150. In `Args`, there must be a space between the parameter name and the `(` of the type.
  151. ```text
  152. Args:
  153. lr (float): The learning rate value, must be positive.
  154. ```
  155. - `Args` Comment
  156. - Common parameter types are as follows:
  157. - Basic data types: `int`, `float`, `bool`, `str`, `list`, `dict`, `set`, `tuple` and `numpy.ndarray`.
  158. ```text
  159. Args:
  160. arg1 (int): Some description.
  161. arg2 (float): Some description.
  162. arg3 (bool): Some description.
  163. arg4 (str): Some description.
  164. arg5 (list): Some description.
  165. arg6 (dict): Some description.
  166. arg7 (set): Some description.
  167. arg8 (tuple): Some description.
  168. arg9 (numpy.ndarray): Some description.
  169. ```
  170. - 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.
  171. ```text
  172. Args:
  173. arg1 (mindspore.dtype): Some description.
  174. ```
  175. - One parameter with multiple optional types: Union [type 1, type 2], for example, `Union[Tensor, Number]`.
  176. ```text
  177. Args:
  178. arg1 (Union[Tensor, Number]): Some description.
  179. ```
  180. - List type: list[Specific type], for example, `list[str]`.
  181. ```text
  182. Args:
  183. arg1 (list[str]): Some description.
  184. ```
  185. - The format of optional types is as follows: (Type, optional).
  186. ```text
  187. Args:
  188. arg1 (bool, optional): Some description.
  189. ```
  190. - Other types: Tensor, other specific types, or method names.
  191. ```text
  192. Args:
  193. arg1 (Tensor): Some description.
  194. ```
  195. - `Returns` Comment
  196. - If the return value type or dimension changes, describe the relationship between the return value and the input.
  197. - 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.
  198. ```text
  199. Returns:
  200. - DatasetNode, the root node of the IR tree.
  201. - Dataset, the root dataset of the IR tree.
  202. ```
  203. - `Examples` Comment
  204. - 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.
  205. ```text
  206. Examples:
  207. >>> import mindspore as ms
  208. >>> import mindspore.nn as nn
  209. >>> class Net(nn.Cell):
  210. ... def __init__(self, dense_shape):
  211. ... super(Net, self).__init__()
  212. ... self.dense_shape = dense_shape
  213. ... def construct(self, indices, values):
  214. ... x = SparseTensor(indices, values, self.dense_shape)
  215. ... return x.values, x.indices, x.dense_shape
  216. ...
  217. >>> indices = Tensor([[0, 1], [1, 2]])
  218. >>> values = Tensor([1, 2], dtype=ms.float32)
  219. >>> out = Net((3, 4))(indices, values)
  220. >>> print(out[0])
  221. [1. 2.]
  222. >>> print(out[1])
  223. [[0 1]
  224. [1 2]]
  225. >>> print(out[2])
  226. (3, 4)
  227. ```
  228. - Actual code needs to be provided in `Examples`. If you need to refer to other Examples, use Note.
  229. - The comments of the ops operator are written in PyNative mode. If the operator can be executed, the execution result must be provided.
  230. - Import can be omitted in the case of industry consensus, such as np and nn.
  231. - 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.
  232. - `Inputs` and `Outputs` Comment
  233. - If the data type is Tensor, describe the shape in the format of :math:\`(N, C, X)\`.
  234. - Formula
  235. - Line formula (in the middle of the singly occupied line)
  236. ```text
  237. .. math::
  238. formula
  239. ```
  240. - Line-embedded formula (displayed together with other peer text, not in the middle)
  241. ```text
  242. xxx :math:`formula` xxx
  243. ```
  244. - 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:
  245. 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}$.
  246. 2. If a backslash (\\) is added before an underscore (_), for example, xxx\\_yyy, the complete variable name is displayed as xxx_yyy.
  247. - Parent Class Method Display
  248. - By default, the parent class method is not displayed.
  249. - 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>.
  250. - Link
  251. - Only the title (such as the name in the following example) is displayed. The detailed address is not displayed.
  252. Write a quotation in the following format:
  253. ```text
  254. `name`_
  255. ```
  256. Provide a link in the following format:
  257. ```text
  258. .. _`name`: https://xxx
  259. ```
  260. Note:
  261. - If there is a newline character, indent it. For details, see the following table.
  262. - There must be a space before https.
  263. Alternatively, you can use the following simplified format, that is, write only in the place where the reference is made.
  264. ```text
  265. `name <https://xxx>`_
  266. ```
  267. - Display the detailed address:
  268. ```text
  269. https://xxx
  270. ```
  271. - Table (For details, see section <https://sublime-and-sphinx-guide.readthedocs.io/en/latest/tables.html#list-table-directive>.)
  272. ```text
  273. .. list-table:: Title # Table title
  274. :widths: 25 25 25 # Table column width
  275. :header-rows: 1
  276. * - Heading row 1, column 1 # Table header
  277. - Heading row 1, column 2
  278. - Heading row 1, column 3
  279. * - Row 1, column 1
  280. - #The table is empty.
  281. - Row 1, column 3
  282. * - Row 2, column 1
  283. - Row 2, column 2
  284. - Row 2,
  285. # If a newline is required for the table content, add a blank line in the middle.
  286. column 3
  287. ```
  288. Display effect:
  289. ![image](./resource/list_table.png)
  290. - 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.
  291. - List mode:
  292. ```text
  293. - Content1
  294. - Content2
  295. - Content3
  296. ```
  297. - Code-Block mode:
  298. ```text
  299. .. code-block::
  300. Content1
  301. Content2
  302. Content3
  303. ```
  304. - Reference other APIs in comments.
  305. - Reference class.
  306. Only write API name:
  307. ```text
  308. :class:`AdamNoUpdateParam`
  309. ```
  310. If there are duplicate API names, you need to quote the complete module name and class name:
  311. ```text
  312. :class:`mindspore.ops.LARS`
  313. ```
  314. - To quote function, the complete module name and function name must be written.
  315. ```text
  316. :func:`mindspore.compression.quant.create_quant_config`
  317. ```
  318. - In the interface description, the variable name or interface name should be wrapped with the symbol \',
  319. and the variable value should be wrapped with the symbol \' or \".
  320. - Variable name or interface name.
  321. ```text
  322. This part is a more detailed overview of `Mul` operation. For more details about Quantization,
  323. please refer to the implementation of subclass of `Observer`.
  324. Other losses derived from this should implement their own `construct` and use method `self.get_loss`
  325. to apply reduction to loss values.
  326. ```
  327. - variable value.
  328. ```text
  329. If `reduction` is not one of 'none', 'mean', 'sum'.
  330. ```
  331. - The deprecated operator needs to specify the recommended api, and "Deprecated" needs to be added in the Supported Platforms.
  332. ```python
  333. class BasicLSTMCell(PrimitiveWithInfer):
  334. """
  335. It's similar to operator :class:`DynamicRNN`. BasicLSTMCell will be deprecated in the future.
  336. Please use :class:`DynamicRNN` instead.
  337. Supported Platforms:
  338. Deprecated
  339. """
  340. ```
  341. - Add images.
  342. format: `.. image:: {name.png}`
  343. `{name.png}` is the name of the image, and submit the image to the directory of the corresponding module in <https://gitee.com/mindspore/mindspore/tree/master/docs/api/api_python>.
  344. For example, add image named `frequency_masking.png` to the comments of `mindspore.dataset.audio.transforms.FrequencyMasking`:
  345. ```python
  346. class FrequencyMasking(AudioTensorOperation):
  347. """
  348. Some description.
  349. .. image:: frequency_masking.png
  350. """
  351. ```
  352. And then submit the image to <https://gitee.com/mindspore/mindspore/blob/master/docs/api/api_python/dataset_audio/frequency_masking.png>.
  353. ### Python Example
  354. #### Class
  355. ```python
  356. class Tensor(Tensor_):
  357. """
  358. Tensor is used for data storage.
  359. Tensor inherits tensor object in C++.
  360. Some functions are implemented in C++ and some functions are implemented in Python.
  361. Args:
  362. input_data (Tensor, float, int, bool, tuple, list, numpy.ndarray): Input data of the tensor.
  363. dtype (:class:`mindspore.dtype`): Input data should be None, bool or numeric type defined in `mindspore.dtype`.
  364. The argument is used to define the data type of the output tensor. If it is None, the data type of the
  365. output tensor will be as same as the `input_data`. Default: None.
  366. Outputs:
  367. Tensor, with the same shape as `input_data`.
  368. Examples:
  369. >>> # initialize a tensor with input data
  370. >>> t1 = Tensor(np.zeros([1, 2, 3]), mindspore.float32)
  371. >>> assert isinstance(t1, Tensor)
  372. >>> assert t1.shape == (1, 2, 3)
  373. >>> assert t1.dtype == mindspore.float32
  374. ...
  375. >>> # initialize a tensor with a float scalar
  376. >>> t2 = Tensor(0.1)
  377. >>> assert isinstance(t2, Tensor)
  378. >>> assert t2.dtype == mindspore.float64
  379. """
  380. def __init__(self, input_data, dtype=None):
  381. ...
  382. ```
  383. For details about the display effect, click [here](https://www.mindspore.cn/docs/api/en/master/api_python/mindspore/mindspore.Tensor.html).
  384. #### Method
  385. ```python
  386. def ms_function(fn=None, obj=None, input_signature=None):
  387. """
  388. Create a callable MindSpore graph from a python function.
  389. This allows the MindSpore runtime to apply optimizations based on graph.
  390. Args:
  391. fn (Function): The Python function that will be run as a graph. Default: None.
  392. obj (Object): The Python Object that provides the information for identifying the compiled function. Default:
  393. None.
  394. input_signature (MetaTensor): The MetaTensor which describes the input arguments. The MetaTensor specifies
  395. the shape and dtype of the Tensor and they will be supplied to this function. If `input_signature`
  396. is specified, each input to `fn` must be a `Tensor`. And the input parameters of `fn` cannot accept
  397. `**kwargs`. The shape and dtype of actual inputs should keep the same as `input_signature`. Otherwise,
  398. TypeError will be raised. Default: None.
  399. Returns:
  400. Function, if `fn` is not None, returns a callable function that will execute the compiled function; If `fn` is
  401. None, returns a decorator and when this decorator invokes with a single `fn` argument, the callable function is
  402. equal to the case when `fn` is not None.
  403. Examples:
  404. >>> def tensor_add(x, y):
  405. ... z = F.tensor_add(x, y)
  406. ... return z
  407. ...
  408. >>> @ms_function
  409. ... def tensor_add_with_dec(x, y):
  410. ... z = F.tensor_add(x, y)
  411. ... return z
  412. ...
  413. >>> @ms_function(input_signature=(MetaTensor(mindspore.float32, (1, 1, 3, 3)),
  414. ... MetaTensor(mindspore.float32, (1, 1, 3, 3))))
  415. ... def tensor_add_with_sig(x, y):
  416. ... z = F.tensor_add(x, y)
  417. ... return z
  418. ...
  419. >>> x = Tensor(np.ones([1, 1, 3, 3]).astype(np.float32))
  420. >>> y = Tensor(np.ones([1, 1, 3, 3]).astype(np.float32))
  421. ...
  422. >>> tensor_add_graph = ms_function(fn=tensor_add)
  423. >>> out = tensor_add_graph(x, y)
  424. >>> out = tensor_add_with_dec(x, y)
  425. >>> out = tensor_add_with_sig(x, y)
  426. """
  427. ...
  428. ```
  429. For details about the display effect, click [here](https://www.mindspore.cn/docs/api/en/master/api_python/mindspore/mindspore.ms_function.html).
  430. #### Formula
  431. ```python
  432. class Conv2d(_Conv):
  433. r"""
  434. 2D convolution layer.
  435. Apply a 2D convolution over an input tensor which is typically of shape :math:`(N, C_{in}, H_{in}, W_{in})`,
  436. where :math:`N` is batch size, :math:`C_{in}` is channel number, and :math:`H_{in}, W_{in})` are height and width.
  437. For each batch of shape :math:`(C_{in}, H_{in}, W_{in})`, the formula is defined as:
  438. .. math::
  439. out_j = \sum_{i=0}^{C_{in} - 1} ccor(W_{ij}, X_i) + b_j,
  440. ...
  441. """
  442. ```
  443. For details about the display effect, click [here](https://www.mindspore.cn/docs/api/en/master/api_python/nn/mindspore.nn.Conv2d.html).
  444. #### Link
  445. ```python
  446. class BatchNorm(PrimitiveWithInfer):
  447. r"""
  448. Batch Normalization for input data and updated parameters.
  449. Batch Normalization is widely used in convolutional neural networks. This operation
  450. applies Batch Normalization over input to avoid internal covariate shift as described
  451. in the paper `Batch Normalization: Accelerating Deep Network Training by Reducing Internal
  452. Covariate Shift <https://arxiv.org/abs/1502.03167>`_. It rescales and recenters the
  453. features using a mini-batch of data and the learned parameters which can be described
  454. in the following formula,
  455. ...
  456. """
  457. ```
  458. For details about the display effect, click [here](https://www.mindspore.cn/docs/api/en/master/api_python/ops/mindspore.ops.BatchNorm.html).
  459. ## C++ API Comment Specifications
  460. ### Comment Format
  461. All API comments follow the following format:
  462. ```cpp
  463. /// \brief Short description
  464. ///
  465. /// Detailed description.
  466. ///
  467. /// \note
  468. /// Describe what to be aware of when using this interface.
  469. ///
  470. /// \f[
  471. /// math formula
  472. /// \f]
  473. /// XXX \f$ formulas in the line \f$ XXX
  474. ///
  475. /// \param[in] Parameter_name meaning, range of values, other instructions.
  476. ///
  477. /// \return Returns a description of the value, the cause of the error,
  478. /// and the corresponding solution.
  479. ///
  480. /// \par Example
  481. /// \code
  482. /// Example code
  483. /// \endcode
  484. ```
  485. in which,
  486. - `\brief`: A brief description.
  487. ```cpp
  488. /// \brief Function to create a CocoDataset.
  489. ```
  490. - `Detailed description`: A detailed description.
  491. ```cpp
  492. /// Base class for all recognizable patterns.
  493. /// We implement an Expression Template approach using static polymorphism based on
  494. /// the Curiously Recurring Template Pattern (CRTP) which "achieves a similar effect
  495. /// to the use of virtual functions without the costs..." as described in:
  496. /// https://en.wikipedia.org/wiki/Expression_templates and
  497. /// https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern
  498. /// The TryCapture function tries to capture the pattern with the given node.
  499. /// The GetNode function builds a new node using the captured values.
  500. ```
  501. - `\note`: Precautions for using this API.
  502. ```cpp
  503. /// \note
  504. /// The generated dataset has multi-columns
  505. ```
  506. - Formula writing.
  507. Multi-line formula writing:
  508. ```cpp
  509. /// \f[
  510. /// x>=y
  511. /// \f]
  512. ```
  513. Line-embedded formula writing, the formula is located between two `\f$`:
  514. ```cpp
  515. /// \brief Computes the boolean value of \f$x>=y\f$ element-wise.
  516. ```
  517. - `\param[in]`: input parameter description.
  518. ```cpp
  519. /// \param[in] weight Defines the width of memory to request
  520. /// \param[in] height Defines the height of memory to request
  521. /// \param[in] type Defines the data type of memory to request
  522. ```
  523. - `\return`: return value description.
  524. ```cpp
  525. /// \return Reference count of a certain memory currently.
  526. ```
  527. - The format of the sample code is as follows, with `\par Example` as the prefix, and the sample code is located between `\code` and `\endcode`. To make it easier to read, add 4 spaces for relative indentation:
  528. ```cpp
  529. /// \par Example
  530. /// \code
  531. /// /* Set number of workers(threads) to process the dataset in parallel */
  532. /// std::shared_ptr<Dataset> ds = ImageFolder(folder_path, true);
  533. /// ds = ds->SetNumWorkers(16);
  534. /// \endcode
  535. ```
  536. ### Precautions
  537. 1. The API annotation content of the document that needs to be generated is guided by `///` instead of using `//`;
  538. 2. Don't break comments, use `///` for blank lines;
  539. 3. When quoting an external name with the same name in the C++ API, to avoid generating incorrect links, you need to add the `@ref` mark in front:
  540. ```cpp
  541. /// \brief Referring to @ref mindspore.nn.Cell for detail.
  542. ```
  543. ### C++ Example
  544. ```cpp
  545. /// \brief Function to create a MnistDataset.
  546. /// \note The generated dataset has two columns ["image", "label"].
  547. /// \param[in] dataset_dir Path to the root directory that contains the dataset.
  548. /// \param[in] usage Part of dataset of MNIST, can be "train", "test" or "all" (default = "all").
  549. /// \param[in] sampler Shared pointer to a sampler object used to choose samples from the dataset. If sampler is not
  550. /// given, a `RandomSampler` will be used to randomly iterate the entire dataset (default = RandomSampler()).
  551. /// \param[in] cache Tensor cache to use (default=nullptr which means no cache is used).
  552. /// \return Shared pointer to the MnistDataset.
  553. /// \par Example
  554. /// \code
  555. /// /* Define dataset path and MindData object */
  556. /// std::string folder_path = "/path/to/mnist_dataset_directory";
  557. /// std::shared_ptr<Dataset> ds = Mnist(folder_path, "all", std::make_shared<RandomSampler>(false, 20));
  558. ///
  559. /// /* Create iterator to read dataset */
  560. /// std::shared_ptr<Iterator> iter = ds->CreateIterator();
  561. /// std::unordered_map<std::string, mindspore::MSTensor> row;
  562. /// iter->GetNextRow(&row);
  563. ///
  564. /// /* Note: In MNIST dataset, each dictionary has keys "image" and "label" */
  565. /// auto image = row["image"];
  566. /// \endcode
  567. inline std::shared_ptr<MnistDataset> MS_API
  568. Mnist(const std::string &dataset_dir, const std::string &usage = "all",
  569. const std::shared_ptr<Sampler> &sampler = std::make_shared<RandomSampler>(),
  570. const std::shared_ptr<DatasetCache> &cache = nullptr) {
  571. return std::make_shared<MnistDataset>(StringToChar(dataset_dir), StringToChar(usage), sampler, cache);
  572. }
  573. ```
  574. The API document page output according to the above comments is [Function mindspore::dataset::Coco](https://www.mindspore.cn/lite/api/en/master/generate/function_mindspore_dataset_Mnist-1.html).