task_summary.rst 48.8 KB
Newer Older
1
..
Sylvain Gugger's avatar
Sylvain Gugger committed
2
3
4
5
6
7
8
9
10
11
12
    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.

Sylvain Gugger's avatar
Sylvain Gugger committed
13
Summary of the tasks
Sylvain Gugger's avatar
Sylvain Gugger committed
14
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
15
16

This page shows the most frequent use-cases when using the library. The models available allow for many different
Sylvain Gugger's avatar
Sylvain Gugger committed
17
18
configurations and a great versatility in use-cases. The most simple ones are presented here, showcasing usage for
tasks such as question answering, sequence classification, named entity recognition and others.
19
20
21

These examples leverage auto-models, which are classes that will instantiate a model according to a given checkpoint,
automatically selecting the correct model architecture. Please check the :class:`~transformers.AutoModel` documentation
Sylvain Gugger's avatar
Sylvain Gugger committed
22
for more information. Feel free to modify the code to be more specific and adapt it to your specific use-case.
23
24
25
26
27
28

In order for a model to perform well on a task, it must be loaded from a checkpoint corresponding to that task. These
checkpoints are usually pre-trained on a large corpus of data and fine-tuned on a specific task. This means the
following:

- Not all models were fine-tuned on all tasks. If you want to fine-tune a model on a specific task, you can leverage
Sylvain Gugger's avatar
Sylvain Gugger committed
29
30
31
32
33
34
  one of the `run_$TASK.py` scripts in the `examples
  <https://github.com/huggingface/transformers/tree/master/examples>`__ directory.
- Fine-tuned models were fine-tuned on a specific dataset. This dataset may or may not overlap with your use-case and
  domain. As mentioned previously, you may leverage the `examples
  <https://github.com/huggingface/transformers/tree/master/examples>`__ scripts to fine-tune your model, or you may
  create your own training script.
35
36
37
38

In order to do an inference on a task, several mechanisms are made available by the library:

- Pipelines: very easy-to-use abstractions, which require as little as two lines of code.
Sylvain Gugger's avatar
Sylvain Gugger committed
39
40
- Direct model use: Less abstractions, but more flexibility and power via a direct access to a tokenizer
  (PyTorch/TensorFlow) and full inference capacity.
41
42
43
44
45
46
47
48
49
50
51
52

Both approaches are showcased here.

.. note::

    All tasks presented here leverage pre-trained checkpoints that were fine-tuned on specific tasks. Loading a
    checkpoint that was not fine-tuned on a specific task would load only the base transformer layers and not the
    additional head that is used for the task, initializing the weights of that head randomly.

    This would produce random output.

Sequence Classification
Sylvain Gugger's avatar
Sylvain Gugger committed
53
-----------------------------------------------------------------------------------------------------------------------
54

Sylvain Gugger's avatar
Sylvain Gugger committed
55
56
Sequence classification is the task of classifying sequences according to a given number of classes. An example of
sequence classification is the GLUE dataset, which is entirely based on that task. If you would like to fine-tune a
57
model on a GLUE sequence classification task, you may leverage the :prefix_link:`run_glue.py
Sylvain Gugger's avatar
Sylvain Gugger committed
58
59
60
61
<examples/pytorch/text-classification/run_glue.py>`, :prefix_link:`run_tf_glue.py
<examples/tensorflow/text-classification/run_tf_glue.py>`, :prefix_link:`run_tf_text_classification.py
<examples/tensorflow/text-classification/run_tf_text_classification.py>` or :prefix_link:`run_xnli.py
<examples/pytorch/text-classification/run_xnli.py>` scripts.
62

Sylvain Gugger's avatar
Sylvain Gugger committed
63
64
Here is an example of using pipelines to do sentiment analysis: identifying if a sequence is positive or negative. It
leverages a fine-tuned model on sst2, which is a GLUE task.
65

66
This returns a label ("POSITIVE" or "NEGATIVE") alongside a score, as follows:
67

68
.. code-block::
69

70
    >>> from transformers import pipeline
71

72
    >>> classifier = pipeline("sentiment-analysis")
73

74
    >>> result = classifier("I hate you")[0]
75
76
    >>> print(f"label: {result['label']}, with score: {round(result['score'], 4)}")
    label: NEGATIVE, with score: 0.9991
77

78
    >>> result = classifier("I love you")[0]
79
80
    >>> print(f"label: {result['label']}, with score: {round(result['score'], 4)}")
    label: POSITIVE, with score: 0.9999
81
82


Sylvain Gugger's avatar
Sylvain Gugger committed
83
84
Here is an example of doing a sequence classification using a model to determine if two sequences are paraphrases of
each other. The process is the following:
85

Sylvain Gugger's avatar
Sylvain Gugger committed
86
87
1. Instantiate a tokenizer and a model from the checkpoint name. The model is identified as a BERT model and loads it
   with the weights stored in the checkpoint.
88
89
2. Build a sequence from the two sentences, with the correct model-specific separators, token type ids and attention
   masks (which will be created automatically by the tokenizer).
Sylvain Gugger's avatar
Sylvain Gugger committed
90
91
3. Pass this sequence through the model so that it is classified in one of the two available classes: 0 (not a
   paraphrase) and 1 (is a paraphrase).
92
93
4. Compute the softmax of the result to get probabilities over the classes.
5. Print the results.
94

95
.. code-block::
96

97
98
99
    >>> ## PYTORCH CODE
    >>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
    >>> import torch
100

101
    >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased-finetuned-mrpc")
102
    >>> model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased-finetuned-mrpc")
103

104
    >>> classes = ["not paraphrase", "is paraphrase"]
105

106
107
108
    >>> sequence_0 = "The company HuggingFace is based in New York City"
    >>> sequence_1 = "Apples are especially bad for your health"
    >>> sequence_2 = "HuggingFace's headquarters are situated in Manhattan"
109

110
111
    >>> # The tokenizer will automatically add any model specific separators (i.e. <CLS> and <SEP>) and tokens to
    >>> # the sequence, as well as compute the attention masks.
112
113
    >>> paraphrase = tokenizer(sequence_0, sequence_2, return_tensors="pt")
    >>> not_paraphrase = tokenizer(sequence_0, sequence_1, return_tensors="pt")
114

115
116
    >>> paraphrase_classification_logits = model(**paraphrase).logits
    >>> not_paraphrase_classification_logits = model(**not_paraphrase).logits
117

118
119
    >>> paraphrase_results = torch.softmax(paraphrase_classification_logits, dim=1).tolist()[0]
    >>> not_paraphrase_results = torch.softmax(not_paraphrase_classification_logits, dim=1).tolist()[0]
120

121
122
123
124
125
    >>> # Should be paraphrase
    >>> for i in range(len(classes)):
    ...     print(f"{classes[i]}: {int(round(paraphrase_results[i] * 100))}%")
    not paraphrase: 10%
    is paraphrase: 90%
126

127
128
129
130
131
132
133
134
    >>> # Should not be paraphrase
    >>> for i in range(len(classes)):
    ...     print(f"{classes[i]}: {int(round(not_paraphrase_results[i] * 100))}%")
    not paraphrase: 94%
    is paraphrase: 6%
    >>> ## TENSORFLOW CODE
    >>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
    >>> import tensorflow as tf
135

136
    >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased-finetuned-mrpc")
137
    >>> model = TFAutoModelForSequenceClassification.from_pretrained("bert-base-cased-finetuned-mrpc")
138

139
    >>> classes = ["not paraphrase", "is paraphrase"]
140

141
142
143
    >>> sequence_0 = "The company HuggingFace is based in New York City"
    >>> sequence_1 = "Apples are especially bad for your health"
    >>> sequence_2 = "HuggingFace's headquarters are situated in Manhattan"
144

145
146
    >>> # The tokenizer will automatically add any model specific separators (i.e. <CLS> and <SEP>) and tokens to
    >>> # the sequence, as well as compute the attention masks.
147
148
    >>> paraphrase = tokenizer(sequence_0, sequence_2, return_tensors="tf")
    >>> not_paraphrase = tokenizer(sequence_0, sequence_1, return_tensors="tf")
149

150
151
    >>> paraphrase_classification_logits = model(paraphrase).logits
    >>> not_paraphrase_classification_logits = model(not_paraphrase).logits
152

153
154
    >>> paraphrase_results = tf.nn.softmax(paraphrase_classification_logits, axis=1).numpy()[0]
    >>> not_paraphrase_results = tf.nn.softmax(not_paraphrase_classification_logits, axis=1).numpy()[0]
155

156
157
158
    >>> # Should be paraphrase
    >>> for i in range(len(classes)):
    ...     print(f"{classes[i]}: {int(round(paraphrase_results[i] * 100))}%")
159
160
161
    not paraphrase: 10%
    is paraphrase: 90%

162
163
164
    >>> # Should not be paraphrase
    >>> for i in range(len(classes)):
    ...     print(f"{classes[i]}: {int(round(not_paraphrase_results[i] * 100))}%")
165
166
167
168
    not paraphrase: 94%
    is paraphrase: 6%

Extractive Question Answering
Sylvain Gugger's avatar
Sylvain Gugger committed
169
-----------------------------------------------------------------------------------------------------------------------
170
171

Extractive Question Answering is the task of extracting an answer from a text given a question. An example of a
Sylvain Gugger's avatar
Sylvain Gugger committed
172
question answering dataset is the SQuAD dataset, which is entirely based on that task. If you would like to fine-tune a
173
model on a SQuAD task, you may leverage the `run_qa.py
Sylvain Gugger's avatar
Sylvain Gugger committed
174
175
176
177
<https://github.com/huggingface/transformers/tree/master/examples/pytorch/question-answering/run_qa.py>`__ and
`run_tf_squad.py
<https://github.com/huggingface/transformers/tree/master/examples/tensorflow/question-answering/run_tf_squad.py>`__
scripts.
178

179

Sylvain Gugger's avatar
Sylvain Gugger committed
180
181
Here is an example of using pipelines to do question answering: extracting an answer from a text given a question. It
leverages a fine-tuned model on SQuAD.
182

183
.. code-block::
184

185
    >>> from transformers import pipeline
186

187
    >>> question_answerer = pipeline("question-answering")
188

189
190
191
    >>> context = r"""
    ... Extractive Question Answering is the task of extracting an answer from a text given a question. An example of a
    ... question answering dataset is the SQuAD dataset, which is entirely based on that task. If you would like to fine-tune
Sylvain Gugger's avatar
Sylvain Gugger committed
192
    ... a model on a SQuAD task, you may leverage the examples/pytorch/question-answering/run_squad.py script.
193
    ... """
194

Sylvain Gugger's avatar
Sylvain Gugger committed
195
196
This returns an answer extracted from the text, a confidence score, alongside "start" and "end" values, which are the
positions of the extracted answer in the text.
197

198
199
.. code-block::

200
    >>> result = question_answerer(question="What is extractive question answering?", context=context)
201
    >>> print(f"Answer: '{result['answer']}', score: {round(result['score'], 4)}, start: {result['start']}, end: {result['end']}")
202
    Answer: 'the task of extracting an answer from a text given a question', score: 0.6177, start: 34, end: 95
203

204
    >>> result = question_answerer(question="What is a good example of a question answering dataset?", context=context)
205
    >>> print(f"Answer: '{result['answer']}', score: {round(result['score'], 4)}, start: {result['start']}, end: {result['end']}")
206
    Answer: 'SQuAD dataset', score: 0.5152, start: 147, end: 160
207
208
209
210


Here is an example of question answering using a model and a tokenizer. The process is the following:

Sylvain Gugger's avatar
Sylvain Gugger committed
211
212
1. Instantiate a tokenizer and a model from the checkpoint name. The model is identified as a BERT model and loads it
   with the weights stored in the checkpoint.
213
2. Define a text and a few questions.
Sylvain Gugger's avatar
Sylvain Gugger committed
214
215
216
217
3. Iterate over the questions and build a sequence from the text and the current question, with the correct
   model-specific separators token type ids and attention masks.
4. Pass this sequence through the model. This outputs a range of scores across the entire sequence tokens (question and
   text), for both the start and end positions.
218
219
220
5. Compute the softmax of the result to get probabilities over the tokens.
6. Fetch the tokens from the identified start and stop values, convert those tokens to a string.
7. Print the results.
221

222
223
224
225
226
227
228
.. code-block::

    >>> ## PYTORCH CODE
    >>> from transformers import AutoTokenizer, AutoModelForQuestionAnswering
    >>> import torch

    >>> tokenizer = AutoTokenizer.from_pretrained("bert-large-uncased-whole-word-masking-finetuned-squad")
229
    >>> model = AutoModelForQuestionAnswering.from_pretrained("bert-large-uncased-whole-word-masking-finetuned-squad")
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244

    >>> text = r"""
    ... 🤗 Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides general-purpose
    ... architectures (BERT, GPT-2, RoBERTa, XLM, DistilBert, XLNet…) for Natural Language Understanding (NLU) and Natural
    ... Language Generation (NLG) with over 32+ pretrained models in 100+ languages and deep interoperability between
    ... TensorFlow 2.0 and PyTorch.
    ... """

    >>> questions = [
    ...     "How many pretrained models are available in 🤗 Transformers?",
    ...     "What does 🤗 Transformers provide?",
    ...     "🤗 Transformers provides interoperability between which frameworks?",
    ... ]

    >>> for question in questions:
245
    ...     inputs = tokenizer(question, text, add_special_tokens=True, return_tensors="pt")
246
247
    ...     input_ids = inputs["input_ids"].tolist()[0]
    ...
248
249
250
    ...     outputs = model(**inputs)
    ...     answer_start_scores = outputs.start_logits
    ...     answer_end_scores = outputs.end_logits
251
    ...
252
253
254
255
    ...     # Get the most likely beginning of answer with the argmax of the score
    ...     answer_start = torch.argmax(answer_start_scores)
    ...     # Get the most likely end of answer with the argmax of the score 
    ...     answer_end = torch.argmax(answer_end_scores) + 1
256
257
258
259
260
261
262
263
264
265
    ...
    ...     answer = tokenizer.convert_tokens_to_string(tokenizer.convert_ids_to_tokens(input_ids[answer_start:answer_end]))
    ...
    ...     print(f"Question: {question}")
    ...     print(f"Answer: {answer}")
    Question: How many pretrained models are available in 🤗 Transformers?
    Answer: over 32 +
    Question: What does 🤗 Transformers provide?
    Answer: general - purpose architectures
    Question: 🤗 Transformers provides interoperability between which frameworks?
266
    Answer: tensorflow 2. 0 and pytorch
267
268
269
270
271
    >>> ## TENSORFLOW CODE
    >>> from transformers import AutoTokenizer, TFAutoModelForQuestionAnswering
    >>> import tensorflow as tf

    >>> tokenizer = AutoTokenizer.from_pretrained("bert-large-uncased-whole-word-masking-finetuned-squad")
272
    >>> model = TFAutoModelForQuestionAnswering.from_pretrained("bert-large-uncased-whole-word-masking-finetuned-squad")
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287

    >>> text = r"""
    ... 🤗 Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides general-purpose
    ... architectures (BERT, GPT-2, RoBERTa, XLM, DistilBert, XLNet…) for Natural Language Understanding (NLU) and Natural
    ... Language Generation (NLG) with over 32+ pretrained models in 100+ languages and deep interoperability between
    ... TensorFlow 2.0 and PyTorch.
    ... """

    >>> questions = [
    ...     "How many pretrained models are available in 🤗 Transformers?",
    ...     "What does 🤗 Transformers provide?",
    ...     "🤗 Transformers provides interoperability between which frameworks?",
    ... ]

    >>> for question in questions:
288
    ...     inputs = tokenizer(question, text, add_special_tokens=True, return_tensors="tf")
289
290
    ...     input_ids = inputs["input_ids"].numpy()[0]
    ...
291
292
293
    ...     outputs = model(inputs)
    ...     answer_start_scores = outputs.start_logits
    ...     answer_end_scores = outputs.end_logits
294
    ...
295
296
297
298
299
    ...     # Get the most likely beginning of answer with the argmax of the score
    ...     answer_start = tf.argmax(answer_start_scores, axis=1).numpy()[0]
    ...     # Get the most likely end of answer with the argmax of the score
    ...     answer_end = tf.argmax(answer_end_scores, axis=1).numpy()[0] + 1
    ...
300
301
302
303
    ...     answer = tokenizer.convert_tokens_to_string(tokenizer.convert_ids_to_tokens(input_ids[answer_start:answer_end]))
    ...
    ...     print(f"Question: {question}")
    ...     print(f"Answer: {answer}")
Sylvain Gugger's avatar
Sylvain Gugger committed
304
    Question: How many pretrained models are available in 🤗 Transformers?
305
    Answer: over 32 +
Sylvain Gugger's avatar
Sylvain Gugger committed
306
    Question: What does 🤗 Transformers provide?
307
    Answer: general - purpose architectures
Sylvain Gugger's avatar
Sylvain Gugger committed
308
    Question: 🤗 Transformers provides interoperability between which frameworks?
309
    Answer: tensorflow 2. 0 and pytorch
310
311
312
313



Language Modeling
Sylvain Gugger's avatar
Sylvain Gugger committed
314
-----------------------------------------------------------------------------------------------------------------------
315

Sylvain Gugger's avatar
Sylvain Gugger committed
316
317
318
Language modeling is the task of fitting a model to a corpus, which can be domain specific. All popular
transformer-based models are trained using a variant of language modeling, e.g. BERT with masked language modeling,
GPT-2 with causal language modeling.
319

320
Language modeling can be useful outside of pretraining as well, for example to shift the model distribution to be
Sylvain Gugger's avatar
Sylvain Gugger committed
321
322
domain-specific: using a language model trained over a very large corpus, and then fine-tuning it to a news dataset or
on scientific papers e.g. `LysandreJik/arxiv-nlp <https://huggingface.co/lysandre/arxiv-nlp>`__.
323
324

Masked Language Modeling
Sylvain Gugger's avatar
Sylvain Gugger committed
325
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
326
327
328

Masked language modeling is the task of masking tokens in a sequence with a masking token, and prompting the model to
fill that mask with an appropriate token. This allows the model to attend to both the right context (tokens on the
Sylvain Gugger's avatar
Sylvain Gugger committed
329
right of the mask) and the left context (tokens on the left of the mask). Such a training creates a strong basis for
330
downstream tasks requiring bi-directional context, such as SQuAD (question answering, see `Lewis, Lui, Goyal et al.
331
<https://arxiv.org/abs/1910.13461>`__, part 4.2). If you would like to fine-tune a model on a masked language modeling
Sylvain Gugger's avatar
Sylvain Gugger committed
332
task, you may leverage the :prefix_link:`run_mlm.py <examples/pytorch/language-modeling/run_mlm.py>` script.
333
334
335

Here is an example of using pipelines to replace a mask from a sequence:

336
.. code-block::
337

338
    >>> from transformers import pipeline
339

340
    >>> unmasker = pipeline("fill-mask")
341

Sylvain Gugger's avatar
Sylvain Gugger committed
342
This outputs the sequences with the mask filled, the confidence score, and the token id in the tokenizer vocabulary:
343

344
345
346
.. code-block::

    >>> from pprint import pprint
347
    >>> pprint(unmasker(f"HuggingFace is creating a {unmasker.tokenizer.mask_token} that the community uses to solve NLP tasks."))
348
349
350
    [{'score': 0.179275,
      'sequence': 'HuggingFace is creating a tool that the community uses to solve '
                  'NLP tasks.',
351
      'token': 3944,
352
353
354
355
      'token_str': ' tool'},
     {'score': 0.113494,
      'sequence': 'HuggingFace is creating a framework that the community uses to '
                  'solve NLP tasks.',
356
      'token': 7208,
357
358
359
360
      'token_str': ' framework'},
     {'score': 0.0524355,
      'sequence': 'HuggingFace is creating a library that the community uses to '
                  'solve NLP tasks.',
361
      'token': 5560,
362
363
364
365
      'token_str': ' library'},
     {'score': 0.0349353,
      'sequence': 'HuggingFace is creating a database that the community uses to '
                  'solve NLP tasks.',
366
      'token': 8503,
367
368
369
370
      'token_str': ' database'},
     {'score': 0.0286025,
      'sequence': 'HuggingFace is creating a prototype that the community uses to '
                  'solve NLP tasks.',
371
      'token': 17715,
372
      'token_str': ' prototype'}]
373

374
Here is an example of doing masked language modeling using a model and a tokenizer. The process is the following:
375

Sylvain Gugger's avatar
Sylvain Gugger committed
376
377
1. Instantiate a tokenizer and a model from the checkpoint name. The model is identified as a DistilBERT model and
   loads it with the weights stored in the checkpoint.
378
379
2. Define a sequence with a masked token, placing the :obj:`tokenizer.mask_token` instead of a word.
3. Encode that sequence into a list of IDs and find the position of the masked token in that list.
Sylvain Gugger's avatar
Sylvain Gugger committed
380
381
4. Retrieve the predictions at the index of the mask token: this tensor has the same size as the vocabulary, and the
   values are the scores attributed to each token. The model gives higher score to tokens it deems probable in that
382
383
384
   context.
5. Retrieve the top 5 tokens using the PyTorch :obj:`topk` or TensorFlow :obj:`top_k` methods.
6. Replace the mask token by the tokens and print the results
385

386
.. code-block::
387

388
    >>> ## PYTORCH CODE
389
    >>> from transformers import AutoModelForMaskedLM, AutoTokenizer
390
    >>> import torch
391

392
    >>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-cased")
393
    >>> model = AutoModelForMaskedLM.from_pretrained("distilbert-base-cased")
394

395
396
    >>> sequence = "Distilled models are smaller than the models they mimic. Using them instead of the large " \
    ...     f"versions would help {tokenizer.mask_token} our carbon footprint."
397

398
399
    >>> inputs = tokenizer(sequence, return_tensors="pt")
    >>> mask_token_index = torch.where(inputs["input_ids"] == tokenizer.mask_token_id)[1]
400

401
    >>> token_logits = model(**inputs).logits
402
    >>> mask_token_logits = token_logits[0, mask_token_index, :]
403

404
    >>> top_5_tokens = torch.topk(mask_token_logits, 5, dim=1).indices[0].tolist()
405
406
407
408
409
410
411
412

    >>> for token in top_5_tokens:
    ...     print(sequence.replace(tokenizer.mask_token, tokenizer.decode([token])))
    Distilled models are smaller than the models they mimic. Using them instead of the large versions would help reduce our carbon footprint.
    Distilled models are smaller than the models they mimic. Using them instead of the large versions would help increase our carbon footprint.
    Distilled models are smaller than the models they mimic. Using them instead of the large versions would help decrease our carbon footprint.
    Distilled models are smaller than the models they mimic. Using them instead of the large versions would help offset our carbon footprint.
    Distilled models are smaller than the models they mimic. Using them instead of the large versions would help improve our carbon footprint.
413
    >>> ## TENSORFLOW CODE
414
    >>> from transformers import TFAutoModelForMaskedLM, AutoTokenizer
415
    >>> import tensorflow as tf
416

417
    >>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-cased")
418
    >>> model = TFAutoModelForMaskedLM.from_pretrained("distilbert-base-cased")
419

420
421
    >>> sequence = "Distilled models are smaller than the models they mimic. Using them instead of the large " \
    ...     f"versions would help {tokenizer.mask_token} our carbon footprint."
422

423
424
    >>> inputs = tokenizer(sequence, return_tensors="tf")
    >>> mask_token_index = tf.where(inputs["input_ids"] == tokenizer.mask_token_id)[0, 1]
425

426
    >>> token_logits = model(**inputs).logits
427
    >>> mask_token_logits = token_logits[0, mask_token_index, :]
428

429
    >>> top_5_tokens = tf.math.top_k(mask_token_logits, 5).indices.numpy()
430

431
432
    >>> for token in top_5_tokens:
    ...     print(sequence.replace(tokenizer.mask_token, tokenizer.decode([token])))
433
434
435
436
437
438
439
    Distilled models are smaller than the models they mimic. Using them instead of the large versions would help reduce our carbon footprint.
    Distilled models are smaller than the models they mimic. Using them instead of the large versions would help increase our carbon footprint.
    Distilled models are smaller than the models they mimic. Using them instead of the large versions would help decrease our carbon footprint.
    Distilled models are smaller than the models they mimic. Using them instead of the large versions would help offset our carbon footprint.
    Distilled models are smaller than the models they mimic. Using them instead of the large versions would help improve our carbon footprint.


440
441
442
This prints five sequences, with the top 5 tokens predicted by the model.


443
Causal Language Modeling
Sylvain Gugger's avatar
Sylvain Gugger committed
444
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
445
446
447

Causal language modeling is the task of predicting the token following a sequence of tokens. In this situation, the
model only attends to the left context (tokens on the left of the mask). Such a training is particularly interesting
448
for generation tasks. If you would like to fine-tune a model on a causal language modeling task, you may leverage the
Sylvain Gugger's avatar
Sylvain Gugger committed
449
:prefix_link:`run_clm.py <examples/pytorch/language-modeling/run_clm.py>` script.
450

Sylvain Gugger's avatar
Sylvain Gugger committed
451
452
Usually, the next token is predicted by sampling from the logits of the last hidden state the model produces from the
input sequence.
453

Sylvain Gugger's avatar
Sylvain Gugger committed
454
455
456
Here is an example of using the tokenizer and model and leveraging the
:func:`~transformers.PreTrainedModel.top_k_top_p_filtering` method to sample the next token following an input sequence
of tokens.
457

458
.. code-block::
459

460
    >>> ## PYTORCH CODE
461
    >>> from transformers import AutoModelForCausalLM, AutoTokenizer, set_seed, top_k_top_p_filtering
462
    >>> import torch
463
    >>> from torch import nn
464

465
    >>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
466
    >>> model = AutoModelForCausalLM.from_pretrained("gpt2")
467

468
    >>> sequence = f"Hugging Face is based in DUMBO, New York City, and"
469

470
471
    >>> inputs = tokenizer(sequence, return_tensors="pt")
    >>> input_ids = inputs["input_ids"]
472

473
    >>> # get logits of last hidden state
474
    >>> next_token_logits = model(**inputs).logits[:, -1, :]
475

476
477
    >>> # filter
    >>> filtered_next_token_logits = top_k_top_p_filtering(next_token_logits, top_k=50, top_p=1.0)
478

479
480
481
    >>> # set seed for reproducibility
    >>> set_seed(42)

482
    >>> # sample
483
    >>> probs = nn.functional.softmax(filtered_next_token_logits, dim=-1)
484
    >>> next_token = torch.multinomial(probs, num_samples=1)
485

486
    >>> generated = torch.cat([input_ids, next_token], dim=-1)
487

488
489
    >>> resulting_string = tokenizer.decode(generated.tolist()[0])
    >>> ## TENSORFLOW CODE
490
    >>> from transformers import TFAutoModelForCausalLM, AutoTokenizer, set_seed, tf_top_k_top_p_filtering
491
    >>> import tensorflow as tf
492

493
    >>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
494
    >>> model = TFAutoModelForCausalLM.from_pretrained("gpt2")
495

496
    >>> sequence = f"Hugging Face is based in DUMBO, New York City, and"
497

498
499
    >>> inputs = tokenizer(sequence, return_tensors="tf")
    >>> input_ids = inputs["input_ids"]
500

501
    >>> # get logits of last hidden state
502
    >>> next_token_logits = model(**inputs).logits[:, -1, :]
503

504
505
    >>> # filter
    >>> filtered_next_token_logits = tf_top_k_top_p_filtering(next_token_logits, top_k=50, top_p=1.0)
506

507
508
509
    >>> # set seed for reproducibility
    >>> set_seed(42)

510
511
    >>> # sample
    >>> next_token = tf.random.categorical(filtered_next_token_logits, dtype=tf.int32, num_samples=1)
512

513
    >>> generated = tf.concat([input_ids, next_token], axis=1)
514

515
    >>> resulting_string = tokenizer.decode(generated.numpy().tolist()[0])
516
517


518
519
This outputs a (hopefully) coherent next token following the original sequence, which in our case is the word
*features*:
520

521
.. code-block::
522

Sylvain Gugger's avatar
Sylvain Gugger committed
523
    >>> print(resulting_string)
524
    Hugging Face is based in DUMBO, New York City, and features
525

526
527
In the next section, we show how :func:`~transformers.generation_utils.GenerationMixin.generate` can be used to
generate multiple tokens up to a specified length instead of one token at a time.
528
529

Text Generation
Sylvain Gugger's avatar
Sylvain Gugger committed
530
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
531

Sylvain Gugger's avatar
Sylvain Gugger committed
532
533
534
535
In text generation (*a.k.a* *open-ended text generation*) the goal is to create a coherent portion of text that is a
continuation from the given context. The following example shows how *GPT-2* can be used in pipelines to generate text.
As a default all models apply *Top-K* sampling when used in pipelines, as configured in their respective configurations
(see `gpt-2 config <https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-config.json>`__ for example).
536

537
538
539
.. code-block::

    >>> from transformers import pipeline
540

541
542
    >>> text_generator = pipeline("text-generation")
    >>> print(text_generator("As far as I am concerned, I will", max_length=50, do_sample=False))
543
544
    [{'generated_text': 'As far as I am concerned, I will be the first to admit that I am not a fan of the idea of a
    "free market." I think that the idea of a free market is a bit of a stretch. I think that the idea'}]
545
546
547



Sylvain Gugger's avatar
Sylvain Gugger committed
548
Here, the model generates a random text with a total maximal length of *50* tokens from context *"As far as I am
549
550
551
concerned, I will"*. Behind the scenes, the pipeline object calls the method
:func:`~transformers.PreTrainedModel.generate` to generate text. The default arguments for this method can be
overridden in the pipeline, as is shown above for the arguments ``max_length`` and ``do_sample``.
552

553
Below is an example of text generation using ``XLNet`` and its tokenizer, which includes calling ``generate`` directly:
554

555
.. code-block::
556

557
    >>> ## PYTORCH CODE
558
    >>> from transformers import AutoModelForCausalLM, AutoTokenizer, set_seed
559

560
    >>> model = AutoModelForCausalLM.from_pretrained("xlnet-base-cased")
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
    >>> tokenizer = AutoTokenizer.from_pretrained("xlnet-base-cased")

    >>> # Padding text helps XLNet with short prompts - proposed by Aman Rusia in https://github.com/rusiaaman/XLNet-gen#methodology
    >>> PADDING_TEXT = """In 1991, the remains of Russian Tsar Nicholas II and his family
    ... (except for Alexei and Maria) are discovered.
    ... The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the
    ... remainder of the story. 1883 Western Siberia,
    ... a young Grigori Rasputin is asked by his father and a group of men to perform magic.
    ... Rasputin has a vision and denounces one of the men as a horse thief. Although his
    ... father initially slaps him for making such an accusation, Rasputin watches as the
    ... man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
    ... the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous,
    ... with people, even a bishop, begging for his blessing. <eod> </s> <eos>"""

    >>> prompt = "Today the weather is really nice and I am planning on "
    >>> inputs = tokenizer.encode(PADDING_TEXT + prompt, add_special_tokens=False, return_tensors="pt")

    >>> prompt_length = len(tokenizer.decode(inputs[0], skip_special_tokens=True, clean_up_tokenization_spaces=True))
    >>> outputs = model.generate(inputs, max_length=250, do_sample=True, top_p=0.95, top_k=60)
580
581
    >>> # set seed for reproducibility
    >>> set_seed(42)
582
583
    >>> generated = prompt + tokenizer.decode(outputs[0])[prompt_length:]

584
585
586
587
588
    >>> print(generated)
    Today the weather is really nice and I am planning on anning on going to a nearby restaurant on Monday. It is very
    cool with the clouds and the wind. A nice afternoon is on the way out of there, when I get my phone in the sun.
    Sounds like its a good day in my house, but on that "good"" thing. There is a group of people who'd want to be out
    and
589
    >>> ## TENSORFLOW CODE
590
    >>> from transformers import TFAutoModelForCausalLM, AutoTokenizer
591

592
    >>> model = TFAutoModelForCausalLM.from_pretrained("xlnet-base-cased")
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
    >>> tokenizer = AutoTokenizer.from_pretrained("xlnet-base-cased")

    >>> # Padding text helps XLNet with short prompts - proposed by Aman Rusia in https://github.com/rusiaaman/XLNet-gen#methodology
    >>> PADDING_TEXT = """In 1991, the remains of Russian Tsar Nicholas II and his family
    ... (except for Alexei and Maria) are discovered.
    ... The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the
    ... remainder of the story. 1883 Western Siberia,
    ... a young Grigori Rasputin is asked by his father and a group of men to perform magic.
    ... Rasputin has a vision and denounces one of the men as a horse thief. Although his
    ... father initially slaps him for making such an accusation, Rasputin watches as the
    ... man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
    ... the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous,
    ... with people, even a bishop, begging for his blessing. <eod> </s> <eos>"""

    >>> prompt = "Today the weather is really nice and I am planning on "
    >>> inputs = tokenizer.encode(PADDING_TEXT + prompt, add_special_tokens=False, return_tensors="tf")

    >>> prompt_length = len(tokenizer.decode(inputs[0], skip_special_tokens=True, clean_up_tokenization_spaces=True))
611
612
    >>> # set seed for reproducibility
    >>> set_seed(42)
613
614
615
    >>> outputs = model.generate(inputs, max_length=250, do_sample=True, top_p=0.95, top_k=60)
    >>> generated = prompt + tokenizer.decode(outputs[0])[prompt_length:]

616
    >>> print(generated)
617
618
619
620
    Today the weather is really nice and I am planning on anning on riding a "" over to the coast. It is also an ideal
    day to fly to Bali and see more of the local "".<eop> “...The weather is great for travel and traveling as far as
    local "".”. When the weather is good, I will ride my "" over to the coast and see more of

621

Sylvain Gugger's avatar
Sylvain Gugger committed
622
623
624
625
Text generation is currently possible with *GPT-2*, *OpenAi-GPT*, *CTRL*, *XLNet*, *Transfo-XL* and *Reformer* in
PyTorch and for most models in Tensorflow as well. As can be seen in the example above *XLNet* and *Transfo-XL* often
need to be padded to work well. GPT-2 is usually a good choice for *open-ended text generation* because it was trained
on millions of webpages with a causal language modeling objective.
626

Sylvain Gugger's avatar
Sylvain Gugger committed
627
628
For more information on how to apply different decoding strategies for text generation, please also refer to our text
generation blog post `here <https://huggingface.co/blog/how-to-generate>`__.
629
630
631


Named Entity Recognition
Sylvain Gugger's avatar
Sylvain Gugger committed
632
-----------------------------------------------------------------------------------------------------------------------
633

Sylvain Gugger's avatar
Sylvain Gugger committed
634
635
636
Named Entity Recognition (NER) is the task of classifying tokens according to a class, for example, identifying a token
as a person, an organisation or a location. An example of a named entity recognition dataset is the CoNLL-2003 dataset,
which is entirely based on that task. If you would like to fine-tune a model on an NER task, you may leverage the
Sylvain Gugger's avatar
Sylvain Gugger committed
637
:prefix_link:`run_ner.py <examples/pytorch/token-classification/run_ner.py>` script.
638

Sylvain Gugger's avatar
Sylvain Gugger committed
639
640
Here is an example of using pipelines to do named entity recognition, specifically, trying to identify tokens as
belonging to one of 9 classes:
641
642
643
644
645
646
647
648
649
650
651

- O, Outside of a named entity
- B-MIS, Beginning of a miscellaneous entity right after another miscellaneous entity
- I-MIS, Miscellaneous entity
- B-PER, Beginning of a person's name right after another person's name
- I-PER, Person's name
- B-ORG, Beginning of an organisation right after another organisation
- I-ORG, Organisation
- B-LOC, Beginning of a location right after another location
- I-LOC, Location

Sylvain Gugger's avatar
Sylvain Gugger committed
652
653
It leverages a fine-tuned model on CoNLL-2003, fine-tuned by `@stefan-it <https://github.com/stefan-it>`__ from `dbmdz
<https://github.com/dbmdz>`__.
654

655
.. code-block::
656

657
    >>> from transformers import pipeline
658

659
    >>> ner_pipe = pipeline("ner")
660

661
    >>> sequence = """Hugging Face Inc. is a company based in New York City. Its headquarters are in DUMBO,
662
    ... therefore very close to the Manhattan Bridge which is visible from the window."""
663
664


Sylvain Gugger's avatar
Sylvain Gugger committed
665
666
This outputs a list of all words that have been identified as one of the entities from the 9 classes defined above.
Here are the expected results:
667

668
669
.. code-block::

670
671
672
673
674
675
676
677
678
679
680
681
682
683
    >>> for entity in ner_pipe(sequence):
    ...     print(entity)
    {'entity': 'I-ORG', 'score': 0.999579, 'index': 1, 'word': 'Hu', 'start': 0, 'end': 2}
    {'entity': 'I-ORG', 'score': 0.990976, 'index': 2, 'word': '##gging', 'start': 2, 'end': 7}
    {'entity': 'I-ORG', 'score': 0.998223, 'index': 3, 'word': 'Face', 'start': 8, 'end': 12}
    {'entity': 'I-ORG', 'score': 0.999488, 'index': 4, 'word': 'Inc', 'start': 13, 'end': 16}
    {'entity': 'I-LOC', 'score': 0.999434, 'index': 11, 'word': 'New', 'start': 40, 'end': 43}
    {'entity': 'I-LOC', 'score': 0.999320, 'index': 12, 'word': 'York', 'start': 44, 'end': 48}
    {'entity': 'I-LOC', 'score': 0.999379, 'index': 13, 'word': 'City', 'start': 49, 'end': 53}
    {'entity': 'I-LOC', 'score': 0.986258, 'index': 19, 'word': 'D', 'start': 79, 'end': 80}
    {'entity': 'I-LOC', 'score': 0.951427, 'index': 20, 'word': '##UM', 'start': 80, 'end': 82}
    {'entity': 'I-LOC', 'score': 0.933659, 'index': 21, 'word': '##BO', 'start': 82, 'end': 84}
    {'entity': 'I-LOC', 'score': 0.976165, 'index': 28, 'word': 'Manhattan', 'start': 114, 'end': 123}
    {'entity': 'I-LOC', 'score': 0.991463, 'index': 29, 'word': 'Bridge', 'start': 124, 'end': 130}
684

685
Note how the tokens of the sequence "Hugging Face" have been identified as an organisation, and "New York City",
Sylvain Gugger's avatar
Sylvain Gugger committed
686
"DUMBO" and "Manhattan Bridge" have been identified as locations.
687

688
689
Here is an example of doing named entity recognition, using a model and a tokenizer. The process is the following:

Sylvain Gugger's avatar
Sylvain Gugger committed
690
691
1. Instantiate a tokenizer and a model from the checkpoint name. The model is identified as a BERT model and loads it
   with the weights stored in the checkpoint.
692
693
2. Define a sequence with known entities, such as "Hugging Face" as an organisation and "New York City" as a location.
3. Split words into tokens so that they can be mapped to predictions. We use a small hack by, first, completely
Sylvain Gugger's avatar
Sylvain Gugger committed
694
   encoding and decoding the sequence, so that we're left with a string that contains the special tokens.
695
696
4. Encode that sequence into IDs (special tokens are added automatically).
5. Retrieve the predictions by passing the input to the model and getting the first output. This results in a
Sylvain Gugger's avatar
Sylvain Gugger committed
697
698
   distribution over the 9 possible classes for each token. We take the argmax to retrieve the most likely class for
   each token.
699
6. Zip together each token with its prediction and print it.
700

701
702
703
704
705
706
.. code-block::

    >>> ## PYTORCH CODE
    >>> from transformers import AutoModelForTokenClassification, AutoTokenizer
    >>> import torch

707
    >>> model = AutoModelForTokenClassification.from_pretrained("dbmdz/bert-large-cased-finetuned-conll03-english")
708
709
    >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")

710
711
    >>> sequence = "Hugging Face Inc. is a company based in New York City. Its headquarters are in DUMBO, " \
    ...            "therefore very close to the Manhattan Bridge."
712

713
714
    >>> inputs = tokenizer(sequence, return_tensors="pt")
    >>> tokens = inputs.tokens()
715

716
    >>> outputs = model(**inputs).logits
717
718
719
720
721
    >>> predictions = torch.argmax(outputs, dim=2)
    >>> ## TENSORFLOW CODE
    >>> from transformers import TFAutoModelForTokenClassification, AutoTokenizer
    >>> import tensorflow as tf

722
    >>> model = TFAutoModelForTokenClassification.from_pretrained("dbmdz/bert-large-cased-finetuned-conll03-english")
723
724
    >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")

725
726
    >>> sequence = "Hugging Face Inc. is a company based in New York City. Its headquarters are in DUMBO, " \
    ...            "therefore very close to the Manhattan Bridge."
727

728
729
    >>> inputs = tokenizer(sequence, return_tensors="tf")
    >>> tokens = inputs.tokens()
730

731
    >>> outputs = model(**inputs)[0]
732
    >>> predictions = tf.argmax(outputs, axis=2)
733
734


Sylvain Gugger's avatar
Sylvain Gugger committed
735
736
This outputs a list of each token mapped to its corresponding prediction. Differently from the pipeline, here every
token has a prediction as we didn't remove the "0"th class, which means that no particular entity was found on that
737
738
739
740
741
token.

In the above example, ``predictions`` is an integer that corresponds to the predicted class. We can use the
``model.config.id2label`` property in order to recover the class name corresponding to the class number, which is
illustrated below:
742

743
.. code-block::
744

745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
    >>> for token, prediction in zip(tokens, predictions[0].numpy()):
    ...     print((token, model.config.id2label[prediction]))
    ('[CLS]', 'O')
    ('Hu', 'I-ORG')
    ('##gging', 'I-ORG')
    ('Face', 'I-ORG')
    ('Inc', 'I-ORG')
    ('.', 'O')
    ('is', 'O')
    ('a', 'O')
    ('company', 'O')
    ('based', 'O')
    ('in', 'O')
    ('New', 'I-LOC')
    ('York', 'I-LOC')
    ('City', 'I-LOC')
    ('.', 'O')
    ('Its', 'O')
    ('headquarters', 'O')
    ('are', 'O')
    ('in', 'O')
    ('D', 'I-LOC')
    ('##UM', 'I-LOC')
    ('##BO', 'I-LOC')
    (',', 'O')
    ('therefore', 'O')
    ('very', 'O')
772
    ('close', 'O')
773
774
775
776
777
778
    ('to', 'O')
    ('the', 'O')
    ('Manhattan', 'I-LOC')
    ('Bridge', 'I-LOC')
    ('.', 'O')
    ('[SEP]', 'O')
779

780

781
Summarization
Sylvain Gugger's avatar
Sylvain Gugger committed
782
-----------------------------------------------------------------------------------------------------------------------
783

784
Summarization is the task of summarizing a document or an article into a shorter text. If you would like to fine-tune a
785
model on a summarization task, you may leverage the `run_summarization.py
Sylvain Gugger's avatar
Sylvain Gugger committed
786
787
<https://github.com/huggingface/transformers/tree/master/examples/pytorch/summarization/run_summarization.py>`__
script.
788

Sylvain Gugger's avatar
Sylvain Gugger committed
789
790
An example of a summarization dataset is the CNN / Daily Mail dataset, which consists of long news articles and was
created for the task of summarization. If you would like to fine-tune a model on a summarization task, various
Sylvain Gugger's avatar
Sylvain Gugger committed
791
approaches are described in this :prefix_link:`document <examples/pytorch/summarization/README.md>`.
792

Sylvain Gugger's avatar
Sylvain Gugger committed
793
794
Here is an example of using the pipelines to do summarization. It leverages a Bart model that was fine-tuned on the CNN
/ Daily Mail data set.
795

796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
.. code-block::

    >>> from transformers import pipeline

    >>> summarizer = pipeline("summarization")

    >>> ARTICLE = """ New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County, New York.
    ... A year later, she got married again in Westchester County, but to a different man and without divorcing her first husband.
    ... Only 18 days after that marriage, she got hitched yet again. Then, Barrientos declared "I do" five more times, sometimes only within two weeks of each other.
    ... In 2010, she married once more, this time in the Bronx. In an application for a marriage license, she stated it was her "first and only" marriage.
    ... Barrientos, now 39, is facing two criminal counts of "offering a false instrument for filing in the first degree," referring to her false statements on the
    ... 2010 marriage license application, according to court documents.
    ... Prosecutors said the marriages were part of an immigration scam.
    ... On Friday, she pleaded not guilty at State Supreme Court in the Bronx, according to her attorney, Christopher Wright, who declined to comment further.
    ... After leaving court, Barrientos was arrested and charged with theft of service and criminal trespass for allegedly sneaking into the New York subway through an emergency exit, said Detective
    ... Annette Markowski, a police spokeswoman. In total, Barrientos has been married 10 times, with nine of her marriages occurring between 1999 and 2002.
    ... All occurred either in Westchester County, Long Island, New Jersey or the Bronx. She is believed to still be married to four men, and at one time, she was married to eight men at once, prosecutors say.
    ... Prosecutors said the immigration scam involved some of her husbands, who filed for permanent residence status shortly after the marriages.
    ... Any divorces happened only after such filings were approved. It was unclear whether any of the men will be prosecuted.
    ... The case was referred to the Bronx District Attorney\'s Office by Immigration and Customs Enforcement and the Department of Homeland Security\'s
    ... Investigation Division. Seven of the men are from so-called "red-flagged" countries, including Egypt, Turkey, Georgia, Pakistan and Mali.
    ... Her eighth husband, Rashid Rajput, was deported in 2006 to his native Pakistan after an investigation by the Joint Terrorism Task Force.
    ... If convicted, Barrientos faces up to four years in prison.  Her next court appearance is scheduled for May 18.
    ... """
820

Sylvain Gugger's avatar
Sylvain Gugger committed
821
822
823
Because the summarization pipeline depends on the ``PreTrainedModel.generate()`` method, we can override the default
arguments of ``PreTrainedModel.generate()`` directly in the pipeline for ``max_length`` and ``min_length`` as shown
below. This outputs the following summary:
824

825
826
827
.. code-block::

    >>> print(summarizer(ARTICLE, max_length=130, min_length=30, do_sample=False))
828
829
830
    [{'summary_text': ' Liana Barrientos, 39, is charged with two counts of "offering a false instrument for filing in
    the first degree" In total, she has been married 10 times, with nine of her marriages occurring between 1999 and
    2002 . At one time, she was married to eight men at once, prosecutors say .'}]
831

832
Here is an example of doing summarization using a model and a tokenizer. The process is the following:
833

Sylvain Gugger's avatar
Sylvain Gugger committed
834
835
1. Instantiate a tokenizer and a model from the checkpoint name. Summarization is usually done using an encoder-decoder
   model, such as ``Bart`` or ``T5``.
836
837
2. Define the article that should be summarized.
3. Add the T5 specific prefix "summarize: ".
838
4. Use the ``PreTrainedModel.generate()`` method to generate the summary.
839

Sylvain Gugger's avatar
Sylvain Gugger committed
840
In this example we use Google's T5 model. Even though it was pre-trained only on a multi-task mixed dataset (including
Sylvain Gugger's avatar
Sylvain Gugger committed
841
CNN / Daily Mail), it yields very good results.
842

843
.. code-block::
844

845
    >>> ## PYTORCH CODE
846
    >>> from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
847

848
    >>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base")
849
    >>> tokenizer = AutoTokenizer.from_pretrained("t5-base")
850

851
    >>> # T5 uses a max_length of 512 so we cut the article to 512 tokens.
852
853
854
855
856
857
858
859
860
    >>> inputs = tokenizer("summarize: " + ARTICLE, return_tensors="pt", max_length=512, truncation=True)
    >>> outputs = model.generate(
    ...     inputs["input_ids"], max_length=150, min_length=40, length_penalty=2.0, num_beams=4, early_stopping=True
    ... )

    >>> print(tokenizer.decode(outputs[0]))
    <pad> prosecutors say the marriages were part of an immigration scam. if convicted, barrientos faces two criminal
    counts of "offering a false instrument for filing in the first degree" she has been married 10 times, nine of them
    between 1999 and 2002.</s>
861
    >>> ## TENSORFLOW CODE
862
    >>> from transformers import TFAutoModelForSeq2SeqLM, AutoTokenizer
863

864
    >>> model = TFAutoModelForSeq2SeqLM.from_pretrained("t5-base")
865
    >>> tokenizer = AutoTokenizer.from_pretrained("t5-base")
866

867
    >>> # T5 uses a max_length of 512 so we cut the article to 512 tokens.
868
869
870
871
    >>> inputs = tokenizer("summarize: " + ARTICLE, return_tensors="tf", max_length=512)
    >>> outputs = model.generate(
    ...     inputs["input_ids"], max_length=150, min_length=40, length_penalty=2.0, num_beams=4, early_stopping=True
    ... )
872
873

    >>> print(tokenizer.decode(outputs[0]))
874
875
876
    <pad> prosecutors say the marriages were part of an immigration scam. if convicted, barrientos faces two criminal
    counts of "offering a false instrument for filing in the first degree" she has been married 10 times, nine of them
    between 1999 and 2002.
877
878


879
Translation
Sylvain Gugger's avatar
Sylvain Gugger committed
880
-----------------------------------------------------------------------------------------------------------------------
881

882
Translation is the task of translating a text from one language to another. If you would like to fine-tune a model on a
883
translation task, you may leverage the `run_translation.py
Sylvain Gugger's avatar
Sylvain Gugger committed
884
<https://github.com/huggingface/transformers/tree/master/examples/pytorch/translation/run_translation.py>`__ script.
885

Sylvain Gugger's avatar
Sylvain Gugger committed
886
887
An example of a translation dataset is the WMT English to German dataset, which has sentences in English as the input
data and the corresponding sentences in German as the target data. If you would like to fine-tune a model on a
Sylvain Gugger's avatar
Sylvain Gugger committed
888
889
translation task, various approaches are described in this :prefix_link:`document
<examples/pytorch.translation/README.md>`.
890

Sylvain Gugger's avatar
Sylvain Gugger committed
891
892
Here is an example of using the pipelines to do translation. It leverages a T5 model that was only pre-trained on a
multi-task mixture dataset (including WMT), yet, yielding impressive translation results.
893

894
.. code-block::
895

896
    >>> from transformers import pipeline
897

898
899
900
    >>> translator = pipeline("translation_en_to_de")
    >>> print(translator("Hugging Face is a technology company based in New York and Paris", max_length=40))
    [{'translation_text': 'Hugging Face ist ein Technologieunternehmen mit Sitz in New York und Paris.'}]
901

Sylvain Gugger's avatar
Sylvain Gugger committed
902
903
Because the translation pipeline depends on the ``PreTrainedModel.generate()`` method, we can override the default
arguments of ``PreTrainedModel.generate()`` directly in the pipeline as is shown for ``max_length`` above.
904

905
906
Here is an example of doing translation using a model and a tokenizer. The process is the following:

Sylvain Gugger's avatar
Sylvain Gugger committed
907
908
1. Instantiate a tokenizer and a model from the checkpoint name. Summarization is usually done using an encoder-decoder
   model, such as ``Bart`` or ``T5``.
909
2. Define the article that should be summarized.
910
3. Add the T5 specific prefix "translate English to German: "
911
4. Use the ``PreTrainedModel.generate()`` method to perform the translation.
912

913
.. code-block::
914

915
    >>> ## PYTORCH CODE
916
    >>> from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
917

918
    >>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base")
919
    >>> tokenizer = AutoTokenizer.from_pretrained("t5-base")
920

921
922
923
924
925
926
927
928
    >>> inputs = tokenizer(
    ...     "translate English to German: Hugging Face is a technology company based in New York and Paris",
    ...     return_tensors="pt"
    ... )
    >>> outputs = model.generate(inputs["input_ids"], max_length=40, num_beams=4, early_stopping=True)

    >>> print(tokenizer.decode(outputs[0]))
    <pad> Hugging Face ist ein Technologieunternehmen mit Sitz in New York und Paris.</s>
929
    >>> ## TENSORFLOW CODE
930
    >>> from transformers import TFAutoModelForSeq2SeqLM, AutoTokenizer
931

932
    >>> model = TFAutoModelForSeq2SeqLM.from_pretrained("t5-base")
933
    >>> tokenizer = AutoTokenizer.from_pretrained("t5-base")
934

935
936
937
938
939
    >>> inputs = tokenizer(
    ...     "translate English to German: Hugging Face is a technology company based in New York and Paris",
    ...     return_tensors="tf"
    ... )
    >>> outputs = model.generate(inputs["input_ids"], max_length=40, num_beams=4, early_stopping=True)
940
941

    >>> print(tokenizer.decode(outputs[0]))
942
943
944
    <pad> Hugging Face ist ein Technologieunternehmen mit Sitz in New York und Paris.

We get the same translation as with the pipeline example.