README.md 11.1 KB
Newer Older
Sylvain Gugger's avatar
Sylvain Gugger committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!---
Copyright 2020 The HuggingFace Team. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

17
18
# Generating the documentation

19
To generate the documentation, you first have to build it. Several packages are necessary to build the doc,
20
you can install them with the following command, at the root of the code repository:
21
22

```bash
23
pip install -e ".[docs]"
24
```
25

26
27
28
29
30
31
Then you need to install our special tool that builds the documentation:

```bash
pip install git+https://github.com/huggingface/doc-builder
```

32
33
34
---
**NOTE**

35
You only need to generate the documentation to inspect it locally (if you're planning changes and want to
36
37
38
39
check how they look like before committing for instance). You don't have to commit the built documentation.

---

40
41
## Building the documentation

42
Once you have setup the `doc-builder` and additional packages, you can generate the documentation by typing th
43
following command:
44
45

```bash
46
doc-builder build transformers docs/source/ --build_dir ~/tmp/test-build
47
48
```

49
50
51
You can adapt the `--build_dir` to set any temporary folder that you prefer. This command will create it and generate
the MDX files that will be rendered as the documentation on the main website. You can inspect them in your favorite
Markdown editor.
52

53
54
55
---
**NOTE**

56
57
It's not possible to see locally how the final documentation will look like for now. Once you have opened a PR, you
will see a bot add a comment to a link where the documentation with your changes lives.
58
59
60

---

61
## Adding a new element to the navigation bar
62

63
Accepted files are Markdown (.md or .mdx).
64

65
66
Create a file with its extension and put it in the source directory. You can then link it to the toc-tree by putting
the filename without the extension in the [`_toctree.yml`](https://github.com/huggingface/transformers/blob/master/docs/source/_toctree.yml) file.
67

68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
## Renaming section headers and moving sections

It helps to keep the old links working when renaming section header and/or moving sections from one document to another. This is because the old links are likely to be used in Issues, Forums and Social media and it'd be make for a much more superior user experience if users reading those months later could still easily navigate to the originally intended information.

Therefore we simply keep a little map of moved sections at the end of the document where the original section was. The key is to preserve the original anchor.

So if you renamed a section from: "Section A" to "Section B", then you can add at the end of the file:

```
Sections that were moved:

[ <a href="#section-b">Section A</a><a id="section-a"></a> ]
```
and of course if you moved it to another file, then:

```
Sections that were moved:

[ <a href="../new-file#section-b">Section A</a><a id="section-a"></a> ]
```

Use the relative style to link to the new file so that the versioned docs continue to work.

For an example of a rich moved sections set please see the very end of [the Trainer doc](https://github.com/huggingface/transformers/blob/master/docs/source/main_classes/trainer.mdx).


94
95
96
## Writing Documentation - Specification

The `huggingface/transformers` documentation follows the
97
[Google documentation](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html) style for docstrings,
98
although we can write them directly in Markdown.
99

100
101
102
### Adding a new tutorial

Adding a new tutorial or section is done in two steps:
103
104

- Add a new file under `./source`. This file can either be ReStructuredText (.rst) or Markdown (.md).
105
- Link that file in `./source/_toctree.yml` on the correct toc-tree.
106

107
108
109
110
Make sure to put your new file under the proper section. It's unlikely to go in the first section (*Get Started*), so
depending on the intended targets (beginners, more advanced users or researchers) it should go in section two, three or
four.

111
112
113
### Adding a new model

When adding a new model:
114

115
116
- Create a file `xxx.mdx` or under `./source/model_doc` (don't hesitate to copy an existing file as template).
- Link that file in `./source/_toctree.yml`.
117
118
119
120
121
122
- Write a short overview of the model:
    - Overview with paper & authors
    - Paper abstract
    - Tips and tricks and how to use it best
- Add the classes that should be linked in the model. This generally includes the configuration, the tokenizer, and
  every model of that class (the base model, alongside models with additional heads), both in PyTorch and TensorFlow.
123
124
  The order is generally:
    - Configuration,
125
126
127
128
129
    - Tokenizer
    - PyTorch base model
    - PyTorch head models
    - TensorFlow base model
    - TensorFlow head models
130
131
    - Flax base model
    - Flax head models
132

133
134
These classes should be added using our Markdown syntax. Usually as follows:

135
```
136
## XXXConfig
137

138
[[autodoc]] XXXConfig
139
140
```

141
142
This will include every public method of the configuration that is documented. If for some reason you wish for a method
not to be displayed in the documentation, you can do so by specifying which methods should be in the docs:
143
144

```
145
146
147
148
149
150
151
152
## XXXTokenizer

[[autodoc]] XXXTokenizer
    - build_inputs_with_special_tokens
    - get_special_tokens_mask
    - create_token_type_ids_from_sequences
    - save_vocabulary
```
153

154
155
If you just want to add a method that is not documented (for instance magic method like `__call__` are not documented
byt default) you can put the list of methods to add in a list that contains `all`:
156
157

```
158
## XXXTokenizer
159

160
161
162
163
[[autodoc]] XXXTokenizer
    - all
    - __call__
```
164

165
### Writing source documentation
166

167
168
Values that should be put in `code` should either be surrounded by backticks: \`like so\`. Note that argument names
and objects like True, None or any strings should usually be put in `code`.
169

170
171
172
When mentioning a class, function or method, it is recommended to use our syntax for internal links so that our tool
adds a link to its documentation with this syntax: \[\`XXXClass\`\] or \[\`function\`\]. This requires the class or 
function to be in the main package.
173

174
175
176
If you want to create a link to some internal class or function, you need to
provide its path. For instance: \[\`file_utils.ModelOutput\`\]. This will be converted into a link with
`file_utils.ModelOutput` in the description. To get rid of the path and only keep the name of the object you are
177
linking to in the description, add a ~: \[\`~file_utils.ModelOutput\`\] will generate a link with `ModelOutput` in the description.
178

Kamal Raj's avatar
Kamal Raj committed
179
The same works for methods so you can either use \[\`XXXClass.method\`\] or \[~\`XXXClass.method\`\].
180
181
182

#### Defining arguments in a method

183
184
185
186
187
188
189
190
191
192
193
Arguments should be defined with the `Args:` (or `Arguments:` or `Parameters:`) prefix, followed by a line return and
an indentation. The argument should be followed by its type, with its shape if it is a tensor, a colon and its
description:

```
    Args:
        n_layers (`int`): The number of layers of the model.
```

If the description is too long to fit in one line, another indentation is necessary before writing the description
after th argument.
194
195
196
197
198

Here's an example showcasing everything so far:

```
    Args:
199
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
200
201
            Indices of input sequence tokens in the vocabulary.

202
203
            Indices can be obtained using [`AlbertTokenizer`]. See [`~PreTrainedTokenizer.encode`] and
            [`~PreTrainedTokenizer.__call__`] for details.
204

205
            [What are input IDs?](../glossary#input-ids)
206
207
```

208
209
210
211
212
213
214
215
216
217
218
For optional arguments or arguments with defaults we follow the following syntax: imagine we have a function with the
following signature:

```
def my_function(x: str = None, a: float = 1):
```

then its documentation should look like this:

```
    Args:
219
        x (`str`, *optional*):
220
            This argument controls ...
221
        a (`float`, *optional*, defaults to 1):
222
223
224
            This argument is used to ...
```

225
Note that we always omit the "defaults to \`None\`" when None is the default for any argument. Also note that even
226
if the first line describing your argument type and its default gets long, you can't break it on several lines. You can
227
however write as many lines as you want in the indented description (see the example above with `input_ids`).
228

229
#### Writing a multi-line code block
230

231
Multi-line code blocks can be useful for displaying examples. They are done between two lines of three backticks as usual in Markdown:
232
233


234
````
235
```
236
237
238
239
240
# first line of code
# second line
# etc
```
````
241

242
243
244
We follow the [doctest](https://docs.python.org/3/library/doctest.html) syntax for the examples to automatically test
the results stay consistent with the library.

245
246
#### Writing a return block

247
The return block should be introduced with the `Returns:` prefix, followed by a line return and an indentation.
248
249
250
251
252
253
254
The first line should be the type of the return, followed by a line return. No need to indent further for the elements
building the return.

Here's an example for a single value return:

```
    Returns:
255
        `List[int]`: A list of integers in the range [0, 1] --- 1 for a special token, 0 for a sequence token.
256
257
```

258
Here's an example for tuple return, comprising several objects:
259
260

```
261
262
263
264
265
266
    Returns:
        `tuple(torch.FloatTensor)` comprising various elements depending on the configuration ([`BertConfig`]) and inputs:
        - ** loss** (*optional*, returned when `masked_lm_labels` is provided) `torch.FloatTensor` of shape `(1,)` --
          Total loss as the sum of the masked language modeling loss and the next sequence prediction (classification) loss.
        - **prediction_scores** (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`) --
          Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
267
268
```

269
270
271
272
273
274
275
#### Adding an image

Due to the rapidly growing repository, it is important to make sure that no files that would significantly weigh down the repository are added. This includes images, videos and other non-text files. We prefer to leverage a hf.co hosted `dataset` like
the ones hosted on [`hf-internal-testing`](https://huggingface.co/hf-internal-testing) in which to place these files and reference
them by URL. We recommend putting them in the following dataset: [huggingface/documentation-images](https://huggingface.co/datasets/huggingface/documentation-images).
If an external contribution, feel free to add the images to your PR and ask a Hugging Face member to migrate your images
to this dataset.
276

277
278
279
280
281
282
283
284
285
## Styling the docstring

We have an automatic script running with the `make style` comment that will make sure that:
- the docstrings fully take advantage of the line width
- all code examples are formatted using black, like the code of the Transformers library

This script may have some weird failures if you made a syntax mistake or if you uncover a bug. Therefore, it's
recommended to commit your changes before running `make style`, so you can revert the changes done by that script
easily.