Unverified Commit 364a5ae1 authored by Lysandre Debut's avatar Lysandre Debut Committed by GitHub
Browse files

Refactor Code samples; Test code samples (#5036)



* Refactor code samples

* Test docstrings

* Style

* Tokenization examples

* Run rust of tests

* First step to testing source docs

* Style and BART comment

* Test the remainder of the code samples

* Style

* let to const

* Formatting fixes

* Ready for merge

* Fix fixture + Style

* Fix last tests

* Update docs/source/quicktour.rst
Co-authored-by: default avatarSylvain Gugger <35901082+sgugger@users.noreply.github.com>

* Addressing @sgugger's comments + Fix MobileBERT in TF
Co-authored-by: default avatarSylvain Gugger <35901082+sgugger@users.noreply.github.com>
parent 315f464b
...@@ -10,3 +10,7 @@ ...@@ -10,3 +10,7 @@
.highlight .kn, .highlight .nv, .highlight .s2, .highlight .ow { .highlight .kn, .highlight .nv, .highlight .s2, .highlight .ow {
color: #6670FF; color: #6670FF;
} }
.highlight .gp {
color: #FB8D68;
}
\ No newline at end of file
...@@ -44,6 +44,7 @@ ...@@ -44,6 +44,7 @@
display: flex; display: flex;
flex-direction: row; flex-direction: row;
justify-content: flex-end; justify-content: flex-end;
margin-right: 30px;
} }
.framework-selector > button { .framework-selector > button {
...@@ -60,6 +61,12 @@ ...@@ -60,6 +61,12 @@
padding: 5px; padding: 5px;
} }
/* Copy button */
a.copybtn {
margin: 3px;
}
/* The literal code blocks */ /* The literal code blocks */
.rst-content tt.literal, .rst-content tt.literal, .rst-content code.literal { .rst-content tt.literal, .rst-content tt.literal, .rst-content code.literal {
color: #6670FF; color: #6670FF;
......
...@@ -157,6 +157,8 @@ function platformToggle() { ...@@ -157,6 +157,8 @@ function platformToggle() {
const codeBlocks = Array.from(document.getElementsByClassName("highlight")); const codeBlocks = Array.from(document.getElementsByClassName("highlight"));
const pytorchIdentifier = "## PYTORCH CODE"; const pytorchIdentifier = "## PYTORCH CODE";
const tensorflowIdentifier = "## TENSORFLOW CODE"; const tensorflowIdentifier = "## TENSORFLOW CODE";
const promptSpanIdentifier = `<span class="gp">&gt;&gt;&gt; </span>`
const pytorchSpanIdentifier = `<span class="c1">${pytorchIdentifier}</span>`; const pytorchSpanIdentifier = `<span class="c1">${pytorchIdentifier}</span>`;
const tensorflowSpanIdentifier = `<span class="c1">${tensorflowIdentifier}</span>`; const tensorflowSpanIdentifier = `<span class="c1">${tensorflowIdentifier}</span>`;
...@@ -169,10 +171,22 @@ function platformToggle() { ...@@ -169,10 +171,22 @@ function platformToggle() {
let tensorflowSpans; let tensorflowSpans;
if(pytorchSpanPosition < tensorflowSpanPosition){ if(pytorchSpanPosition < tensorflowSpanPosition){
pytorchSpans = spans.slice(pytorchSpanPosition + pytorchSpanIdentifier.length + 1, tensorflowSpanPosition); const isPrompt = spans.slice(
spans.indexOf(tensorflowSpanIdentifier) - promptSpanIdentifier.length,
spans.indexOf(tensorflowSpanIdentifier)
) == promptSpanIdentifier;
const finalTensorflowSpanPosition = isPrompt ? tensorflowSpanPosition - promptSpanIdentifier.length : tensorflowSpanPosition;
pytorchSpans = spans.slice(pytorchSpanPosition + pytorchSpanIdentifier.length + 1, finalTensorflowSpanPosition);
tensorflowSpans = spans.slice(tensorflowSpanPosition + tensorflowSpanIdentifier.length + 1, spans.length); tensorflowSpans = spans.slice(tensorflowSpanPosition + tensorflowSpanIdentifier.length + 1, spans.length);
}else{ }else{
tensorflowSpans = spans.slice(tensorflowSpanPosition + tensorflowSpanIdentifier.length + 1, pytorchSpanPosition); const isPrompt = spans.slice(
spans.indexOf(pytorchSpanIdentifier) - promptSpanIdentifier.length,
spans.indexOf(pytorchSpanIdentifier)
) == promptSpanIdentifier;
const finalPytorchSpanPosition = isPrompt ? pytorchSpanPosition - promptSpanIdentifier.length : pytorchSpanPosition;
tensorflowSpans = spans.slice(tensorflowSpanPosition + tensorflowSpanIdentifier.length + 1, finalPytorchSpanPosition);
pytorchSpans = spans.slice(pytorchSpanPosition + pytorchSpanIdentifier.length + 1, spans.length); pytorchSpans = spans.slice(pytorchSpanPosition + pytorchSpanIdentifier.length + 1, spans.length);
} }
......
...@@ -44,7 +44,8 @@ extensions = [ ...@@ -44,7 +44,8 @@ extensions = [
'sphinx.ext.napoleon', 'sphinx.ext.napoleon',
'recommonmark', 'recommonmark',
'sphinx.ext.viewcode', 'sphinx.ext.viewcode',
'sphinx_markdown_tables' 'sphinx_markdown_tables',
'sphinx_copybutton'
] ]
# Add any paths that contain templates here, relative to this directory. # Add any paths that contain templates here, relative to this directory.
...@@ -74,6 +75,8 @@ exclude_patterns = [u'_build', 'Thumbs.db', '.DS_Store'] ...@@ -74,6 +75,8 @@ exclude_patterns = [u'_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use. # The name of the Pygments (syntax highlighting) style to use.
pygments_style = None pygments_style = None
# Remove the prompt when copying examples
copybutton_prompt_text = ">>> "
# -- Options for HTML output ------------------------------------------------- # -- Options for HTML output -------------------------------------------------
......
...@@ -45,17 +45,16 @@ tokenizer, which is a `WordPiece <https://arxiv.org/pdf/1609.08144.pdf>`__ token ...@@ -45,17 +45,16 @@ tokenizer, which is a `WordPiece <https://arxiv.org/pdf/1609.08144.pdf>`__ token
:: ::
from transformers import BertTokenizer >>> from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pretrained("bert-base-cased") >>> tokenizer = BertTokenizer.from_pretrained("bert-base-cased")
sequence = "A Titan RTX has 24GB of VRAM" >>> sequence = "A Titan RTX has 24GB of VRAM"
The tokenizer takes care of splitting the sequence into tokens available in the tokenizer vocabulary. The tokenizer takes care of splitting the sequence into tokens available in the tokenizer vocabulary.
:: ::
tokenized_sequence = tokenizer.tokenize(sequence) >>> tokenized_sequence = tokenizer.tokenize(sequence)
print(tokenized_sequence)
The tokens are either words or subwords. Here for instance, "VRAM" wasn't in the model vocabulary, so it's been split The tokens are either words or subwords. Here for instance, "VRAM" wasn't in the model vocabulary, so it's been split
in "V", "RA" and "M". To indicate those tokens are not separate words but parts of the same word, a double-dash is in "V", "RA" and "M". To indicate those tokens are not separate words but parts of the same word, a double-dash is
...@@ -63,6 +62,7 @@ added for "RA" and "M": ...@@ -63,6 +62,7 @@ added for "RA" and "M":
:: ::
>>> print(tokenized_sequence)
['A', 'Titan', 'R', '##T', '##X', 'has', '24', '##GB', 'of', 'V', '##RA', '##M'] ['A', 'Titan', 'R', '##T', '##X', 'has', '24', '##GB', 'of', 'V', '##RA', '##M']
These tokens can then be converted into IDs which are understandable by the model. This can be done by directly feeding These tokens can then be converted into IDs which are understandable by the model. This can be done by directly feeding
...@@ -71,14 +71,14 @@ the sentence to the tokenizer, which leverages the Rust implementation of ...@@ -71,14 +71,14 @@ the sentence to the tokenizer, which leverages the Rust implementation of
:: ::
encoded_sequence = tokenizer(sequence)["input_ids"] >>> encoded_sequence = tokenizer(sequence)["input_ids"]
print(encoded_sequence)
The tokenizer returns a dictionary with all the arguments necessary for its corresponding model to work properly. The The tokenizer returns a dictionary with all the arguments necessary for its corresponding model to work properly. The
token indices are under the key "input_ids": token indices are under the key "input_ids":
:: ::
>>> print(encoded_sequence)
[101, 138, 18696, 155, 1942, 3190, 1144, 1572, 13745, 1104, 159, 9664, 2107, 102] [101, 138, 18696, 155, 1942, 3190, 1144, 1572, 13745, 1104, 159, 9664, 2107, 102]
Note that the tokenizer automatically adds "special tokens" (if the associated model rely on them) which are special Note that the tokenizer automatically adds "special tokens" (if the associated model rely on them) which are special
...@@ -86,13 +86,14 @@ IDs the model sometimes uses. If we decode the previous sequence of ids, ...@@ -86,13 +86,14 @@ IDs the model sometimes uses. If we decode the previous sequence of ids,
:: ::
tokenizer.decode(encoded_sequence) >>> decoded_sequence = tokenizer.decode(encoded_sequence)
we will see we will see
:: ::
'[CLS] A Titan RTX has 24GB of VRAM [SEP]' >>> print(decoded_sequence)
[CLS] A Titan RTX has 24GB of VRAM [SEP]
because this is the way a :class:`~transformers.BertModel` is going to expect its inputs. because this is the way a :class:`~transformers.BertModel` is going to expect its inputs.
...@@ -108,21 +109,20 @@ For example, consider these two sequences: ...@@ -108,21 +109,20 @@ For example, consider these two sequences:
:: ::
from transformers import BertTokenizer >>> from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pretrained("bert-base-cased") >>> tokenizer = BertTokenizer.from_pretrained("bert-base-cased")
sequence_a = "This is a short sequence." >>> sequence_a = "This is a short sequence."
sequence_b = "This is a rather long sequence. It is at least longer than the sequence A." >>> sequence_b = "This is a rather long sequence. It is at least longer than the sequence A."
encoded_sequence_a = tokenizer(sequence_a)["input_ids"] >>> encoded_sequence_a = tokenizer(sequence_a)["input_ids"]
encoded_sequence_b = tokenizer(sequence_b)["input_ids"] >>> encoded_sequence_b = tokenizer(sequence_b)["input_ids"]
len(encoded_sequence_a), len(encoded_sequence_b)
The encoded versions have different lengths: The encoded versions have different lengths:
:: ::
>>> len(encoded_sequence_a), len(encoded_sequence_b)
(8, 19) (8, 19)
Therefore, we can't be put then together in a same tensor as-is. The first sequence needs to be padded up to the length Therefore, we can't be put then together in a same tensor as-is. The first sequence needs to be padded up to the length
...@@ -133,15 +133,14 @@ it to pad like this: ...@@ -133,15 +133,14 @@ it to pad like this:
:: ::
padded_sequences = tokenizer([sequence_a, sequence_b], padding=True) >>> padded_sequences = tokenizer([sequence_a, sequence_b], padding=True)
padded_sequences["input_ids"]
We can see that 0s have been added on the right of the first sentence to make it the same length as the second one: We can see that 0s have been added on the right of the first sentence to make it the same length as the second one:
:: ::
[[101, 1188, 1110, 170, 1603, 4954, 119, 102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], >>> padded_sequences["input_ids"]
[101, 1188, 1110, 170, 1897, 1263, 4954, 119, 1135, 1110, 1120, 1655, 2039, 1190, 1103, 4954, 138, 119, 102]] [[101, 1188, 1110, 170, 1603, 4954, 119, 102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [101, 1188, 1110, 170, 1897, 1263, 4954, 119, 1135, 1110, 1120, 1655, 2039, 1190, 1103, 4954, 138, 119, 102]]
This can then be converted into a tensor in PyTorch or TensorFlow. The attention mask is a binary tensor indicating This can then be converted into a tensor in PyTorch or TensorFlow. The attention mask is a binary tensor indicating
the position of the padded indices so that the model does not attend to them. For the the position of the padded indices so that the model does not attend to them. For the
...@@ -150,14 +149,8 @@ a padded value. This attention mask is in the dictionary returned by the tokeniz ...@@ -150,14 +149,8 @@ a padded value. This attention mask is in the dictionary returned by the tokeniz
:: ::
padded_sequences["attention_mask"] >>> padded_sequences["attention_mask"]
[[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
will give back
::
[[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
.. _token-type-ids: .. _token-type-ids:
...@@ -170,26 +163,27 @@ tokens. For example, the BERT model builds its two sequence input as such: ...@@ -170,26 +163,27 @@ tokens. For example, the BERT model builds its two sequence input as such:
:: ::
# [CLS] SEQUENCE_A [SEP] SEQUENCE_B [SEP] >>> # [CLS] SEQUENCE_A [SEP] SEQUENCE_B [SEP]
We can use our tokenizer to automatically generate such a sentence by passing the two sequences as two arguments (and We can use our tokenizer to automatically generate such a sentence by passing the two sequences as two arguments (and
not a list like before) like this: not a list like before) like this:
:: ::
from transformers import BertTokenizer >>> from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pretrained("bert-base-cased") >>> tokenizer = BertTokenizer.from_pretrained("bert-base-cased")
sequence_a = "HuggingFace is based in NYC" >>> sequence_a = "HuggingFace is based in NYC"
sequence_b = "Where is HuggingFace based?" >>> sequence_b = "Where is HuggingFace based?"
encoded_dict = tokenizer(sequence_a, sequence_b) >>> encoded_dict = tokenizer(sequence_a, sequence_b)
tokenizer.decode(encoded_dict["input_ids"]) >>> decoded = tokenizer.decode(encoded_dict["input_ids"])
which will return: which will return:
:: ::
"[CLS] HuggingFace is based in NYC [SEP] Where is HuggingFace based? [SEP]" >>> print(decoded)
[CLS] HuggingFace is based in NYC [SEP] Where is HuggingFace based? [SEP]
This is enough for some models to understand where one sequence ends and where another begins. However, other models This is enough for some models to understand where one sequence ends and where another begins. However, other models
such as BERT have an additional mechanism, which are the token type IDs (also called segment IDs). They are a binary such as BERT have an additional mechanism, which are the token type IDs (also called segment IDs). They are a binary
...@@ -199,12 +193,7 @@ The tokenizer returns in the dictionary under the key "token_type_ids": ...@@ -199,12 +193,7 @@ The tokenizer returns in the dictionary under the key "token_type_ids":
:: ::
encoded_dict['token_type_ids'] >>> encoded_dict['token_type_ids']
will return
::
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]
The first sequence, the "context" used for the question, has all its tokens represented by :obj:`0`, whereas the The first sequence, the "context" used for the question, has all its tokens represented by :obj:`0`, whereas the
......
...@@ -36,10 +36,11 @@ Here is an example using the ``xlm-clm-enfr-1024`` checkpoint (Causal language m ...@@ -36,10 +36,11 @@ Here is an example using the ``xlm-clm-enfr-1024`` checkpoint (Causal language m
.. code-block:: .. code-block::
import torch >>> import torch
from transformers import XLMTokenizer, XLMWithLMHeadModel >>> from transformers import XLMTokenizer, XLMWithLMHeadModel
tokenizer = XLMTokenizer.from_pretrained("xlm-clm-1024-enfr") >>> tokenizer = XLMTokenizer.from_pretrained("xlm-clm-enfr-1024")
>>> model = XLMWithLMHeadModel.from_pretrained("xlm-clm-enfr-1024")
The different languages this model/tokenizer handles, as well as the ids of these languages are visible using the The different languages this model/tokenizer handles, as well as the ids of these languages are visible using the
...@@ -47,16 +48,15 @@ The different languages this model/tokenizer handles, as well as the ids of thes ...@@ -47,16 +48,15 @@ The different languages this model/tokenizer handles, as well as the ids of thes
.. code-block:: .. code-block::
# Continuation of the previous script >>> print(tokenizer.lang2id)
print(tokenizer.lang2id) # {'en': 0, 'fr': 1} {'en': 0, 'fr': 1}
These ids should be used when passing a language parameter during a model pass. Let's define our inputs: These ids should be used when passing a language parameter during a model pass. Let's define our inputs:
.. code-block:: .. code-block::
# Continuation of the previous script >>> input_ids = torch.tensor([tokenizer.encode("Wikipedia was used to")]) # batch size of 1
input_ids = torch.tensor([tokenizer.encode("Wikipedia was used to")]) # batch size of 1
We should now define the language embedding by using the previously defined language id. We want to create a tensor We should now define the language embedding by using the previously defined language id. We want to create a tensor
...@@ -64,20 +64,18 @@ filled with the appropriate language ids, of the same size as input_ids. For eng ...@@ -64,20 +64,18 @@ filled with the appropriate language ids, of the same size as input_ids. For eng
.. code-block:: .. code-block::
# Continuation of the previous script >>> language_id = tokenizer.lang2id['en'] # 0
language_id = tokenizer.lang2id['en'] # 0 >>> langs = torch.tensor([language_id] * input_ids.shape[1]) # torch.tensor([0, 0, 0, ..., 0])
langs = torch.tensor([language_id] * input_ids.shape[1]) # torch.tensor([0, 0, 0, ..., 0])
# We reshape it to be of size (batch_size, sequence_length) >>> # We reshape it to be of size (batch_size, sequence_length)
langs = langs.view(1, -1) # is now of shape [1, sequence_length] (we have a batch size of 1) >>> langs = langs.view(1, -1) # is now of shape [1, sequence_length] (we have a batch size of 1)
You can then feed it all as input to your model: You can then feed it all as input to your model:
.. code-block:: .. code-block::
# Continuation of the previous script >>> outputs = model(input_ids, langs=langs)
outputs = model(input_ids, langs=langs)
The example `run_generation.py <https://github.com/huggingface/transformers/blob/master/examples/text-generation/run_generation.py>`__ The example `run_generation.py <https://github.com/huggingface/transformers/blob/master/examples/text-generation/run_generation.py>`__
......
...@@ -32,40 +32,33 @@ provides the following tasks out of the box: ...@@ -32,40 +32,33 @@ provides the following tasks out of the box:
Let's see how this work for sentiment analysis (the other tasks are all covered in the Let's see how this work for sentiment analysis (the other tasks are all covered in the
:doc:`task summary </task_summary>`): :doc:`task summary </task_summary>`):
:: .. code-block::
from transformers import pipeline >>> from transformers import pipeline
classifier = pipeline('sentiment-analysis') >>> classifier = pipeline('sentiment-analysis')
When typing this command for the first time, a pretrained model and its tokenizer are downloaded and cached. We will When typing this command for the first time, a pretrained model and its tokenizer are downloaded and cached. We will
look at both later on, but as an introduction the tokenizer's job is to preprocess the text for the model, which is look at both later on, but as an introduction the tokenizer's job is to preprocess the text for the model, which is
then responsible for making predictions. The pipeline groups all of that together, and post-process the predictions to then responsible for making predictions. The pipeline groups all of that together, and post-process the predictions to
make them readable. For instance make them readable. For instance:
::
classifier('We are very happy to show you the 🤗 Transformers library.')
will return something like this: .. code-block::
::
>>> classifier('We are very happy to show you the 🤗 Transformers library.')
[{'label': 'POSITIVE', 'score': 0.9997795224189758}] [{'label': 'POSITIVE', 'score': 0.9997795224189758}]
That's encouraging! You can use it on a list of sentences, which will be preprocessed then fed to the model as a That's encouraging! You can use it on a list of sentences, which will be preprocessed then fed to the model as a
`batch`: `batch`, returning a list of dictionaries like this one:
::
classifier(["We are very happy to show you the 🤗 Transformers library.", .. code-block::
"We hope you don't hate it."])
returning a list of dictionaries like this one: >>> results = classifier(["We are very happy to show you the 🤗 Transformers library.",
... "We hope you don't hate it."])
:: >>> for result in results:
... print(f"label: {result['label']}, with score: {round(result['score'], 4)}")
[{'label': 'POSITIVE', 'score': 0.9997795224189758}, label: POSITIVE, with score: 0.9998
{'label': 'NEGATIVE', 'score': 0.5308589935302734}] label: NEGATIVE, with score: 0.5309
You can see the second sentence has been classified as negative (it needs to be positive or negative) but its score is You can see the second sentence has been classified as negative (it needs to be positive or negative) but its score is
fairly neutral. fairly neutral.
...@@ -83,9 +76,9 @@ see how we can use it. ...@@ -83,9 +76,9 @@ see how we can use it.
You can directly pass the name of the model to use to :func:`~transformers.pipeline`: You can directly pass the name of the model to use to :func:`~transformers.pipeline`:
:: .. code-block::
classifier = pipeline('sentiment-analysis', model="nlptown/bert-base-multilingual-uncased-sentiment") >>> classifier = pipeline('sentiment-analysis', model="nlptown/bert-base-multilingual-uncased-sentiment")
This classifier can now deal with texts in English, French, but also Dutch, German, Italian and Spanish! You can also This classifier can now deal with texts in English, French, but also Dutch, German, Italian and Spanish! You can also
replace that name by a local folder where you have saved a pretrained model (see below). You can also pass a model replace that name by a local folder where you have saved a pretrained model (see below). You can also pass a model
...@@ -98,29 +91,30 @@ tokenizer associated to the model we picked and instantiate it. The second is ...@@ -98,29 +91,30 @@ tokenizer associated to the model we picked and instantiate it. The second is
the model itself. Note that if we were using the library on an other task, the class of the model would change. The the model itself. Note that if we were using the library on an other task, the class of the model would change. The
:doc:`task summary </task_summary>` tutorial summarizes which class is used for which task. :doc:`task summary </task_summary>` tutorial summarizes which class is used for which task.
:: .. code-block::
## PYTORCH CODE >>> ## PYTORCH CODE
from transformers import AutoTokenizer, AutoModelForSequenceClassification >>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
## TENSORFLOW CODE >>> ## TENSORFLOW CODE
from transformers import AutoTokenizer, TFAutoModelForSequenceClassification >>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
Now, to download the models and tokenizer we found previously, we just have to use the Now, to download the models and tokenizer we found previously, we just have to use the
:func:`~transformers.AutoModelForSequenceClassification.from_pretrained` method (feel free to replace ``model_name`` by :func:`~transformers.AutoModelForSequenceClassification.from_pretrained` method (feel free to replace ``model_name`` by
any other model from the model hub): any other model from the model hub):
:: .. code-block::
## PYTORCH CODE >>> ## PYTORCH CODE
model_name = "nlptown/bert-base-multilingual-uncased-sentiment" >>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
model = AutoModelForSequenceClassification.from_pretrained(model_name) >>> model = AutoModelForSequenceClassification.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name) >>> tokenizer = AutoTokenizer.from_pretrained(model_name)
pipe = pipeline('sentiment-analysis', model=model, tokenizer=tokenizer) >>> pipe = pipeline('sentiment-analysis', model=model, tokenizer=tokenizer)
## TENSORFLOW CODE >>> ## TENSORFLOW CODE
model_name = "nlptown/bert-base-multilingual-uncased-sentiment" >>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
model = TFAutoModelForSequenceClassification.from_pretrained(model_name) >>> # This model only exists in PyTorch, so we use the `from_pt` flag to import that model in TensorFlow.
tokenizer = AutoTokenizer.from_pretrained(model_name) >>> model = TFAutoModelForSequenceClassification.from_pretrained(model_name, from_pt=True)
classifier = pipeline('sentiment-analysis', model=model, tokenizer=tokenizer) >>> tokenizer = AutoTokenizer.from_pretrained(model_name)
>>> classifier = pipeline('sentiment-analysis', model=model, tokenizer=tokenizer)
If you don't find a model that has been pretrained on some data similar to yours, you will need to fine-tune a If you don't find a model that has been pretrained on some data similar to yours, you will need to fine-tune a
pretrained model on your data. We provide :doc:`example scripts </examples>` to do so. Once you're done, don't forget pretrained model on your data. We provide :doc:`example scripts </examples>` to do so. Once you're done, don't forget
...@@ -136,16 +130,16 @@ using the :obj:`from_pretrained` method: ...@@ -136,16 +130,16 @@ using the :obj:`from_pretrained` method:
:: ::
## PYTORCH CODE >>> ## PYTORCH CODE
from transformers import AutoTokenizer, AutoModelForSequenceClassification >>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
model_name = "distilbert-base-uncased-finetuned-sst-2-english" >>> model_name = "distilbert-base-uncased-finetuned-sst-2-english"
model = AutoModelForSequenceClassification.from_pretrained(model_name) >>> pt_model = AutoModelForSequenceClassification.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name) >>> tokenizer = AutoTokenizer.from_pretrained(model_name)
## TENSORFLOW CODE >>> ## TENSORFLOW CODE
from transformers import AutoTokenizer, TFAutoModelForSequenceClassification >>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
model_name = "distilbert-base-uncased-finetuned-sst-2-english" >>> model_name = "distilbert-base-uncased-finetuned-sst-2-english"
model = TFAutoModelForSequenceClassification.from_pretrained(model_name) >>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name) >>> tokenizer = AutoTokenizer.from_pretrained(model_name)
Using the tokenizer Using the tokenizer
^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^
...@@ -161,48 +155,56 @@ the model. To do this, the tokenizer has a `vocab`, which is the part we downloa ...@@ -161,48 +155,56 @@ the model. To do this, the tokenizer has a `vocab`, which is the part we downloa
To apply these steps on a given text, we can just feed it to our tokenizer: To apply these steps on a given text, we can just feed it to our tokenizer:
:: .. code-block::
input = tokenizer("We are very happy to show you the 🤗 Transformers library.") >>> inputs = tokenizer("We are very happy to show you the 🤗 Transformers library.")
print(input)
This returns a dictionary string to list of ints. It contains the `ids of the tokens <glossary.html#input-ids>`__, This returns a dictionary string to list of ints. It contains the `ids of the tokens <glossary.html#input-ids>`__,
as mentioned before, but also additional arguments that will be useful to the model. Here for instance, we also have an as mentioned before, but also additional arguments that will be useful to the model. Here for instance, we also have an
`attention mask <glossary.html#attention-mask>`__ that the model will use to have a better understanding of the sequence: `attention mask <glossary.html#attention-mask>`__ that the model will use to have a better understanding of the sequence:
:: .. code-block::
{'input_ids': [101, 2057, 2024, 2200, 3407, 2000, 2265, 2017, 1996, 100, 19081, 3075, 1012, 102],
'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]} >>> print(inputs)
{'input_ids': [101, 2057, 2024, 2200, 3407, 2000, 2265, 2017, 1996, 100, 19081, 3075, 1012, 102], 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
You can pass a list of sentences directly to your tokenizer. If your goal is to send them through your model as a You can pass a list of sentences directly to your tokenizer. If your goal is to send them through your model as a
batch, you probably want to pad them all to the same length, truncate them to the maximum length the model can accept batch, you probably want to pad them all to the same length, truncate them to the maximum length the model can accept
and get tensors back. You can specify all of that to the tokenizer: and get tensors back. You can specify all of that to the tokenizer:
:: .. code-block::
## PYTORCH CODE >>> ## PYTORCH CODE
batch = tokenizer( >>> pt_batch = tokenizer(
["We are very happy to show you the 🤗 Transformers library.", ... ["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."],
"We hope you don't hate it."], ... padding=True,
padding=True, truncation=True, return_tensors="pt") ... truncation=True,
print(batch) ... return_tensors="pt"
## TENSORFLOW CODE ... )
batch = tokenizer( >>> ## TENSORFLOW CODE
["We are very happy to show you the 🤗 Transformers library.", >>> tf_batch = tokenizer(
"We hope you don't hate it."], ... ["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."],
padding=True, truncation=True, return_tensors="tf") ... padding=True,
print(batch) ... truncation=True,
... return_tensors="tf"
... )
The padding is automatically applied on the side the model expect it (in this case, on the right), with the The padding is automatically applied on the side the model expect it (in this case, on the right), with the
padding token the model was pretrained with. The attention mask is also adapted to take the padding into account: padding token the model was pretrained with. The attention mask is also adapted to take the padding into account:
:: .. code-block::
{'input_ids': tensor([[ 101, 2057, 2024, 2200, 3407, 2000, 2265, 2017, 1996, 100, 19081, 3075, 1012, 102], >>> ## PYTORCH CODE
[ 101, 2057, 3246, 2017, 2123, 1005, 1056, 5223, 2009, 1012, 102, 0, 0, 0]]), >>> for key, value in pt_batch.items():
'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ... print(f"{key}: {value.numpy().tolist()}")
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0]])} input_ids: [[101, 2057, 2024, 2200, 3407, 2000, 2265, 2017, 1996, 100, 19081, 3075, 1012, 102], [101, 2057, 3246, 2017, 2123, 1005, 1056, 5223, 2009, 1012, 102, 0, 0, 0]]
attention_mask: [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0]]
>>> ## TENSORFLOW CODE
>>> for key, value in tf_batch.items():
... print(f"{key}: {value.numpy().tolist()}")
input_ids: [[101, 2057, 2024, 2200, 3407, 2000, 2265, 2017, 1996, 100, 19081, 3075, 1012, 102], [101, 2057, 3246, 2017, 2123, 1005, 1056, 5223, 2009, 1012, 102, 0, 0, 0]]
attention_mask: [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0]]
You can learn more about tokenizers :doc:`here <preprocessing>`. You can learn more about tokenizers :doc:`here <preprocessing>`.
...@@ -213,20 +215,27 @@ Once your input has been preprocessed by the tokenizer, you can directly send it ...@@ -213,20 +215,27 @@ Once your input has been preprocessed by the tokenizer, you can directly send it
contain all the relevant information the model needs. If you're using a TensorFlow model, you can directly pass the contain all the relevant information the model needs. If you're using a TensorFlow model, you can directly pass the
dictionary keys to tensor, for a PyTorch model, you need to unpack the dictionary by adding :obj:`**`. dictionary keys to tensor, for a PyTorch model, you need to unpack the dictionary by adding :obj:`**`.
:: .. code-block::
## PYTORCH CODE >>> ## PYTORCH CODE
outputs = model(**batch) >>> pt_outputs = pt_model(**pt_batch)
## TENSORFLOW CODE >>> ## TENSORFLOW CODE
outputs = model(batch) >>> tf_outputs = tf_model(tf_batch)
In 🤗 Transformers, all outputs are tuples (with only one element potentially). Here, we get a tuple with just the In 🤗 Transformers, all outputs are tuples (with only one element potentially). Here, we get a tuple with just the
final activations of the model. final activations of the model.
:: .. code-block::
(tensor([[-4.1329, 4.3811], >>> ## PYTORCH CODE
[ 0.0818, -0.0418]]),) >>> print(pt_outputs)
(tensor([[-4.0833, 4.3364],
[ 0.0818, -0.0418]], grad_fn=<AddmmBackward>),)
>>> ## TENSORFLOW CODE
>>> print(tf_outputs)
(<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[-4.0832963 , 4.3364134 ],
[ 0.08181238, -0.04178794]], dtype=float32)>,)
.. note:: .. note::
...@@ -235,33 +244,39 @@ final activations of the model. ...@@ -235,33 +244,39 @@ final activations of the model.
Let's apply the SoftMax activation to get predictions. Let's apply the SoftMax activation to get predictions.
:: .. code-block::
## PYTORCH CODE >>> ## PYTORCH CODE
import torch.nn.functional as F >>> import torch.nn.functional as F
predictions = F.softmax(outputs[0], dim=-1) >>> pt_predictions = F.softmax(pt_outputs[0], dim=-1)
print(predictions) >>> ## TENSORFLOW CODE
## TENSORFLOW CODE >>> import tensorflow as tf
predictions = tf.nn.softmax(outputs[0], axis=-1) >>> tf_predictions = tf.nn.softmax(tf_outputs[0], axis=-1)
print(predictions)
We can see we get the numbers from before: We can see we get the numbers from before:
:: .. code-block::
tensor([[2.0060e-04, 9.9980e-01], >>> ## TENSORFLOW CODE
[5.3086e-01, 4.6914e-01]]) >>> print(tf_predictions)
tf.Tensor(
[[2.2042994e-04 9.9977952e-01]
[5.3086078e-01 4.6913919e-01]], shape=(2, 2), dtype=float32)
>>> ## PYTORCH CODE
>>> print(pt_predictions)
tensor([[2.2043e-04, 9.9978e-01],
[5.3086e-01, 4.6914e-01]], grad_fn=<SoftmaxBackward>)
If you have labels, you can provide them to the model, it will return a tuple with the loss and the final activations. If you have labels, you can provide them to the model, it will return a tuple with the loss and the final activations.
:: .. code-block::
## PYTORCH CODE >>> ## PYTORCH CODE
import torch >>> import torch
outputs = model(**batch, labels = torch.tensor([1, 0]) >>> pt_outputs = pt_model(**pt_batch, labels = torch.tensor([1, 0]))
## TENSORFLOW CODE >>> ## TENSORFLOW CODE
import tensorflow as tf >>> import tensorflow as tf
outputs = model(batch, labels = tf.constant([1, 0]) >>> tf_outputs = tf_model(tf_batch, labels = tf.constant([1, 0]))
Models are standard `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`__ or Models are standard `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`__ or
`tf.keras.Model <https://www.tensorflow.org/api_docs/python/tf/keras/Model>`__ so you can use them in your usual `tf.keras.Model <https://www.tensorflow.org/api_docs/python/tf/keras/Model>`__ so you can use them in your usual
...@@ -298,12 +313,12 @@ Lastly, you can also ask the model to return all hidden states and all attention ...@@ -298,12 +313,12 @@ Lastly, you can also ask the model to return all hidden states and all attention
:: ::
## PYTORCH CODE >>> ## PYTORCH CODE
outputs = model(**batch, output_hidden_states=True, output_attentions=True) >>> pt_outputs = pt_model(**pt_batch, output_hidden_states=True, output_attentions=True)
all_hidden_states, all_attentions = outputs[-2:] >>> all_hidden_states, all_attentions = pt_outputs[-2:]
## TENSORFLOW CODE >>> ## TENSORFLOW CODE
outputs = model(batch, output_hidden_states=True, output_attentions=True) >>> tf_outputs = tf_model(tf_batch, output_hidden_states=True, output_attentions=True)
all_hidden_states, all_attentions = outputs[-2:] >>> all_hidden_states, all_attentions = tf_outputs[-2:]
Accessing the code Accessing the code
^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^
...@@ -318,18 +333,18 @@ using the :doc:`DistilBERT </model_doc/distilbert>` architecture. The model auto ...@@ -318,18 +333,18 @@ using the :doc:`DistilBERT </model_doc/distilbert>` architecture. The model auto
to that specific model, or browse the source code. This is how you would directly instantiate model and tokenizer to that specific model, or browse the source code. This is how you would directly instantiate model and tokenizer
without the auto magic: without the auto magic:
:: .. code-block::
## PYTORCH CODE >>> ## PYTORCH CODE
from transformers import DistilBertTokenizer, DistilBertForSequenceClassification >>> from transformers import DistilBertTokenizer, DistilBertForSequenceClassification
model_name = "distilbert-base-uncased-finetuned-sst-2-english" >>> model_name = "distilbert-base-uncased-finetuned-sst-2-english"
model = DistilBertForSequenceClassification.from_pretrained(model_name) >>> model = DistilBertForSequenceClassification.from_pretrained(model_name)
tokenizer = DistilBertTokenizer.from_pretrained(model_name) >>> tokenizer = DistilBertTokenizer.from_pretrained(model_name)
## TENSORFLOW CODE >>> ## TENSORFLOW CODE
from transformers import DistilBertTokenizer, TFDistilBertForSequenceClassification >>> from transformers import DistilBertTokenizer, TFDistilBertForSequenceClassification
model_name = "distilbert-base-uncased-finetuned-sst-2-english" >>> model_name = "distilbert-base-uncased-finetuned-sst-2-english"
model = TFDistilBertForSequenceClassification.from_pretrained(model_name) >>> model = TFDistilBertForSequenceClassification.from_pretrained(model_name)
tokenizer = DistilBertTokenizer.from_pretrained(model_name) >>> tokenizer = DistilBertTokenizer.from_pretrained(model_name)
Customizing the model Customizing the model
^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^
...@@ -345,18 +360,18 @@ Here we use the predefined vocabulary of DistilBERT (hence load the tokenizer wi ...@@ -345,18 +360,18 @@ Here we use the predefined vocabulary of DistilBERT (hence load the tokenizer wi
instantiate the model from the configuration instead of using the instantiate the model from the configuration instead of using the
:func:`~transformers.DistilBertForSequenceClassification.from_pretrained` method). :func:`~transformers.DistilBertForSequenceClassification.from_pretrained` method).
:: .. code-block::
## PYTORCH CODE >>> ## PYTORCH CODE
from transformers import DistilBertConfig, DistilBertTokenizer, DistilBertForSequenceClassification >>> from transformers import DistilBertConfig, DistilBertTokenizer, DistilBertForSequenceClassification
config = DistilBertConfig(n_heads=8, dim=512, hidden_dim=4*512) >>> config = DistilBertConfig(n_heads=8, dim=512, hidden_dim=4*512)
tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased') >>> tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
model = DistilBertForSequenceClassification(config) >>> model = DistilBertForSequenceClassification(config)
## TENSORFLOW CODE >>> ## TENSORFLOW CODE
from transformers import DistilBertConfig, DistilBertTokenizer, TFDistilBertForSequenceClassification >>> from transformers import DistilBertConfig, DistilBertTokenizer, TFDistilBertForSequenceClassification
config = DistilBertConfig(n_heads=8, dim=512, hidden_dim=4*512) >>> config = DistilBertConfig(n_heads=8, dim=512, hidden_dim=4*512)
tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased') >>> tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
model = TFDistilBertForSequenceClassification(config) >>> model = TFDistilBertForSequenceClassification(config)
For something that only changes the head of the model (for instance, the number of labels), you can still use a For something that only changes the head of the model (for instance, the number of labels), you can still use a
pretrained model for the body. For instance, let's define a classifier for 10 different labels using a pretrained body. pretrained model for the body. For instance, let's define a classifier for 10 different labels using a pretrained body.
...@@ -364,15 +379,15 @@ We could create a configuration with all the default values and just change the ...@@ -364,15 +379,15 @@ We could create a configuration with all the default values and just change the
can directly pass any argument a configuration would take to the :func:`from_pretrained` method and it will update the can directly pass any argument a configuration would take to the :func:`from_pretrained` method and it will update the
default configuration with it: default configuration with it:
:: .. code-block::
## PYTORCH CODE >>> ## PYTORCH CODE
from transformers import DistilBertConfig, DistilBertTokenizer, DistilBertForSequenceClassification >>> from transformers import DistilBertConfig, DistilBertTokenizer, DistilBertForSequenceClassification
model_name = "distilbert-base-uncased" >>> model_name = "distilbert-base-uncased"
model = DistilBertForSequenceClassification.from_pretrained(model_name, num_labels=10) >>> model = DistilBertForSequenceClassification.from_pretrained(model_name, num_labels=10)
tokenizer = DistilBertTokenizer.from_pretrained(model_name) >>> tokenizer = DistilBertTokenizer.from_pretrained(model_name)
## TENSORFLOW CODE >>> ## TENSORFLOW CODE
from transformers import DistilBertConfig, DistilBertTokenizer, TFDistilBertForSequenceClassification >>> from transformers import DistilBertConfig, DistilBertTokenizer, TFDistilBertForSequenceClassification
model_name = "distilbert-base-uncased" >>> model_name = "distilbert-base-uncased"
model = TFDistilBertForSequenceClassification.from_pretrained(model_name, num_labels=10) >>> model = TFDistilBertForSequenceClassification.from_pretrained(model_name, num_labels=10)
tokenizer = DistilBertTokenizer.from_pretrained(model_name) >>> tokenizer = DistilBertTokenizer.from_pretrained(model_name)
...@@ -50,21 +50,21 @@ a model on a GLUE sequence classification task, you may leverage the ...@@ -50,21 +50,21 @@ a model on a GLUE sequence classification task, you may leverage the
Here is an example using the pipelines do to sentiment analysis: identifying if a sequence is positive or negative. Here is an example using the pipelines do to sentiment analysis: identifying if a sequence is positive or negative.
It leverages a fine-tuned model on sst2, which is a GLUE task. It leverages a fine-tuned model on sst2, which is a GLUE task.
:: This returns a label ("POSITIVE" or "NEGATIVE") alongside a score, as follows:
from transformers import pipeline
nlp = pipeline("sentiment-analysis") .. code-block::
print(nlp("I hate you")) >>> from transformers import pipeline
print(nlp("I love you"))
This returns a label ("POSITIVE" or "NEGATIVE") alongside a score, as follows: >>> nlp = pipeline("sentiment-analysis")
:: >>> result = nlp("I hate you")[0]
>>> print(f"label: {result['label']}, with score: {round(result['score'], 4)}")
label: NEGATIVE, with score: 0.9991
[{'label': 'NEGATIVE', 'score': 0.9991129}] >>> result = nlp("I love you")[0]
[{'label': 'POSITIVE', 'score': 0.99986565}] >>> print(f"label: {result['label']}, with score: {round(result['score'], 4)}")
label: POSITIVE, with score: 0.9999
Here is an example of doing a sequence classification using a model to determine if two sequences are paraphrases Here is an example of doing a sequence classification using a model to determine if two sequences are paraphrases
...@@ -80,76 +80,72 @@ of each other. The process is the following: ...@@ -80,76 +80,72 @@ of each other. The process is the following:
- Compute the softmax of the result to get probabilities over the classes - Compute the softmax of the result to get probabilities over the classes
- Print the results - Print the results
:: .. code-block::
## PYTORCH CODE
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased-finetuned-mrpc")
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased-finetuned-mrpc")
classes = ["not paraphrase", "is paraphrase"]
sequence_0 = "The company HuggingFace is based in New York City" >>> ## PYTORCH CODE
sequence_1 = "Apples are especially bad for your health" >>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
sequence_2 = "HuggingFace's headquarters are situated in Manhattan" >>> import torch
paraphrase = tokenizer.encode_plus(sequence_0, sequence_2, return_tensors="pt") >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased-finetuned-mrpc")
not_paraphrase = tokenizer.encode_plus(sequence_0, sequence_1, return_tensors="pt") >>> model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased-finetuned-mrpc")
paraphrase_classification_logits = model(**paraphrase)[0] >>> classes = ["not paraphrase", "is paraphrase"]
not_paraphrase_classification_logits = model(**not_paraphrase)[0]
paraphrase_results = torch.softmax(paraphrase_classification_logits, dim=1).tolist()[0] >>> sequence_0 = "The company HuggingFace is based in New York City"
not_paraphrase_results = torch.softmax(not_paraphrase_classification_logits, dim=1).tolist()[0] >>> sequence_1 = "Apples are especially bad for your health"
>>> sequence_2 = "HuggingFace's headquarters are situated in Manhattan"
print("Should be paraphrase") >>> paraphrase = tokenizer.encode_plus(sequence_0, sequence_2, return_tensors="pt")
for i in range(len(classes)): >>> not_paraphrase = tokenizer.encode_plus(sequence_0, sequence_1, return_tensors="pt")
print(f"{classes[i]}: {round(paraphrase_results[i] * 100)}%")
print("\nShould not be paraphrase") >>> paraphrase_classification_logits = model(**paraphrase)[0]
for i in range(len(classes)): >>> not_paraphrase_classification_logits = model(**not_paraphrase)[0]
print(f"{classes[i]}: {round(not_paraphrase_results[i] * 100)}%")
## TENSORFLOW CODE
from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
import tensorflow as tf
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased-finetuned-mrpc") >>> paraphrase_results = torch.softmax(paraphrase_classification_logits, dim=1).tolist()[0]
model = TFAutoModelForSequenceClassification.from_pretrained("bert-base-cased-finetuned-mrpc") >>> not_paraphrase_results = torch.softmax(not_paraphrase_classification_logits, dim=1).tolist()[0]
classes = ["not paraphrase", "is paraphrase"] >>> # Should be paraphrase
>>> for i in range(len(classes)):
sequence_0 = "The company HuggingFace is based in New York City" ... print(f"{classes[i]}: {int(round(paraphrase_results[i] * 100))}%")
sequence_1 = "Apples are especially bad for your health" not paraphrase: 10%
sequence_2 = "HuggingFace's headquarters are situated in Manhattan" is paraphrase: 90%
paraphrase = tokenizer.encode_plus(sequence_0, sequence_2, return_tensors="tf") >>> # Should not be paraphrase
not_paraphrase = tokenizer.encode_plus(sequence_0, sequence_1, return_tensors="tf") >>> 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
paraphrase_classification_logits = model(paraphrase)[0] >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased-finetuned-mrpc")
not_paraphrase_classification_logits = model(not_paraphrase)[0] >>> model = TFAutoModelForSequenceClassification.from_pretrained("bert-base-cased-finetuned-mrpc")
paraphrase_results = tf.nn.softmax(paraphrase_classification_logits, axis=1).numpy()[0] >>> classes = ["not paraphrase", "is paraphrase"]
not_paraphrase_results = tf.nn.softmax(not_paraphrase_classification_logits, axis=1).numpy()[0]
print("Should be paraphrase") >>> sequence_0 = "The company HuggingFace is based in New York City"
for i in range(len(classes)): >>> sequence_1 = "Apples are especially bad for your health"
print(f"{classes[i]}: {round(paraphrase_results[i] * 100)}%") >>> sequence_2 = "HuggingFace's headquarters are situated in Manhattan"
print("\nShould not be paraphrase") >>> paraphrase = tokenizer.encode_plus(sequence_0, sequence_2, return_tensors="tf")
for i in range(len(classes)): >>> not_paraphrase = tokenizer.encode_plus(sequence_0, sequence_1, return_tensors="tf")
print(f"{classes[i]}: {round(not_paraphrase_results[i] * 100)}%")
This outputs the following results: >>> paraphrase_classification_logits = model(paraphrase)[0]
>>> not_paraphrase_classification_logits = model(not_paraphrase)[0]
:: >>> 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]
Should be paraphrase >>> # Should be paraphrase
>>> for i in range(len(classes)):
... print(f"{classes[i]}: {int(round(paraphrase_results[i] * 100))}%")
not paraphrase: 10% not paraphrase: 10%
is paraphrase: 90% is paraphrase: 90%
Should not be paraphrase >>> # Should not be paraphrase
>>> for i in range(len(classes)):
... print(f"{classes[i]}: {int(round(not_paraphrase_results[i] * 100))}%")
not paraphrase: 94% not paraphrase: 94%
is paraphrase: 6% is paraphrase: 6%
...@@ -163,28 +159,30 @@ a model on a SQuAD task, you may leverage the `run_squad.py`. ...@@ -163,28 +159,30 @@ a model on a SQuAD task, you may leverage the `run_squad.py`.
Here is an example using the pipelines do to question answering: extracting an answer from a text given a question. Here is an example using the pipelines do to question answering: extracting an answer from a text given a question.
It leverages a fine-tuned model on SQuAD. It leverages a fine-tuned model on SQuAD.
:: .. code-block::
from transformers import pipeline
nlp = pipeline("question-answering") >>> from transformers import pipeline
context = r""" >>> nlp = pipeline("question-answering")
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
a model on a SQuAD task, you may leverage the `run_squad.py`.
"""
print(nlp(question="What is extractive question answering?", context=context)) >>> context = r"""
print(nlp(question="What is a good example of a question answering dataset?", context=context)) ... 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
... a model on a SQuAD task, you may leverage the examples/question-answering/run_squad.py script.
... """
This returns an answer extracted from the text, a confidence score, alongside "start" and "end" values which 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. are the positions of the extracted answer in the text.
:: .. code-block::
{'score': 0.622232091629833, 'start': 34, 'end': 96, 'answer': 'the task of extracting an answer from a text given a question.'} >>> result = nlp(question="What is extractive question answering?", context=context)
{'score': 0.5115299158662765, 'start': 147, 'end': 161, 'answer': 'SQuAD dataset,'} >>> print(f"Answer: '{result['answer']}', score: {round(result['score'], 4)}, start: {result['start']}, end: {result['end']}")
Answer: 'the task of extracting an answer from a text given a question.', score: 0.6226, start: 34, end: 96
>>> result = nlp(question="What is a good example of a question answering dataset?", context=context)
>>> print(f"Answer: '{result['answer']}', score: {round(result['score'], 4)}, start: {result['start']}, end: {result['end']}")
Answer: 'SQuAD dataset,', score: 0.5053, start: 147, end: 161
Here is an example of question answering using a model and a tokenizer. The process is the following: Here is an example of question answering using a model and a tokenizer. The process is the following:
...@@ -200,92 +198,91 @@ Here is an example of question answering using a model and a tokenizer. The proc ...@@ -200,92 +198,91 @@ Here is an example of question answering using a model and a tokenizer. The proc
- Fetch the tokens from the identified start and stop values, convert those tokens to a string. - Fetch the tokens from the identified start and stop values, convert those tokens to a string.
- Print the results - Print the results
:: .. code-block::
## PYTORCH CODE >>> ## PYTORCH CODE
from transformers import AutoTokenizer, AutoModelForQuestionAnswering >>> from transformers import AutoTokenizer, AutoModelForQuestionAnswering
import torch >>> import torch
tokenizer = AutoTokenizer.from_pretrained("bert-large-uncased-whole-word-masking-finetuned-squad") >>> tokenizer = AutoTokenizer.from_pretrained("bert-large-uncased-whole-word-masking-finetuned-squad")
model = AutoModelForQuestionAnswering.from_pretrained("bert-large-uncased-whole-word-masking-finetuned-squad") >>> model = AutoModelForQuestionAnswering.from_pretrained("bert-large-uncased-whole-word-masking-finetuned-squad")
text = r""" >>> text = r"""
🤗 Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides general-purpose ... 🤗 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 ... 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 ... Language Generation (NLG) with over 32+ pretrained models in 100+ languages and deep interoperability between
TensorFlow 2.0 and PyTorch. ... TensorFlow 2.0 and PyTorch.
""" ... """
questions = [ >>> questions = [
"How many pretrained models are available in 🤗 Transformers?", ... "How many pretrained models are available in 🤗 Transformers?",
"What does 🤗 Transformers provide?", ... "What does 🤗 Transformers provide?",
"🤗 Transformers provides interoperability between which frameworks?", ... "🤗 Transformers provides interoperability between which frameworks?",
] ... ]
for question in questions: >>> for question in questions:
inputs = tokenizer.encode_plus(question, text, add_special_tokens=True, return_tensors="pt") ... inputs = tokenizer.encode_plus(question, text, add_special_tokens=True, return_tensors="pt")
input_ids = inputs["input_ids"].tolist()[0] ... input_ids = inputs["input_ids"].tolist()[0]
...
text_tokens = tokenizer.convert_ids_to_tokens(input_ids) ... text_tokens = tokenizer.convert_ids_to_tokens(input_ids)
answer_start_scores, answer_end_scores = model(**inputs) ... answer_start_scores, answer_end_scores = model(**inputs)
...
answer_start = torch.argmax( ... answer_start = torch.argmax(
answer_start_scores ... answer_start_scores
) # Get the most likely beginning of answer with the argmax of the score ... ) # Get the most likely beginning of answer with the argmax of the score
answer_end = torch.argmax(answer_end_scores) + 1 # Get the most likely end of answer with the argmax of the score ... answer_end = torch.argmax(answer_end_scores) + 1 # Get the most likely end of answer with the argmax of the score
...
answer = tokenizer.convert_tokens_to_string(tokenizer.convert_ids_to_tokens(input_ids[answer_start:answer_end])) ... answer = tokenizer.convert_tokens_to_string(tokenizer.convert_ids_to_tokens(input_ids[answer_start:answer_end]))
...
print(f"Question: {question}") ... print(f"Question: {question}")
print(f"Answer: {answer}\n") ... print(f"Answer: {answer}")
## TENSORFLOW CODE Question: How many pretrained models are available in 🤗 Transformers?
from transformers import AutoTokenizer, TFAutoModelForQuestionAnswering Answer: over 32 +
import tensorflow as tf Question: What does 🤗 Transformers provide?
Answer: general - purpose architectures
tokenizer = AutoTokenizer.from_pretrained("bert-large-uncased-whole-word-masking-finetuned-squad") Question: 🤗 Transformers provides interoperability between which frameworks?
model = TFAutoModelForQuestionAnswering.from_pretrained("bert-large-uncased-whole-word-masking-finetuned-squad") Answer: tensorflow 2 . 0 and pytorch
>>> ## TENSORFLOW CODE
text = r""" >>> from transformers import AutoTokenizer, TFAutoModelForQuestionAnswering
🤗 Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides general-purpose >>> import tensorflow as tf
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 >>> tokenizer = AutoTokenizer.from_pretrained("bert-large-uncased-whole-word-masking-finetuned-squad")
TensorFlow 2.0 and PyTorch. >>> model = TFAutoModelForQuestionAnswering.from_pretrained("bert-large-uncased-whole-word-masking-finetuned-squad")
"""
>>> text = r"""
questions = [ ... 🤗 Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides general-purpose
"How many pretrained models are available in 🤗 Transformers?", ... architectures (BERT, GPT-2, RoBERTa, XLM, DistilBert, XLNet…) for Natural Language Understanding (NLU) and Natural
"What does 🤗 Transformers provide?", ... Language Generation (NLG) with over 32+ pretrained models in 100+ languages and deep interoperability between
"🤗 Transformers provides interoperability between which frameworks?", ... TensorFlow 2.0 and PyTorch.
] ... """
for question in questions: >>> questions = [
inputs = tokenizer.encode_plus(question, text, add_special_tokens=True, return_tensors="tf") ... "How many pretrained models are available in 🤗 Transformers?",
input_ids = inputs["input_ids"].numpy()[0] ... "What does 🤗 Transformers provide?",
... "🤗 Transformers provides interoperability between which frameworks?",
text_tokens = tokenizer.convert_ids_to_tokens(input_ids) ... ]
answer_start_scores, answer_end_scores = model(inputs)
>>> for question in questions:
answer_start = tf.argmax( ... inputs = tokenizer.encode_plus(question, text, add_special_tokens=True, return_tensors="tf")
answer_start_scores, axis=1 ... input_ids = inputs["input_ids"].numpy()[0]
).numpy()[0] # Get the most likely beginning of answer with the argmax of the score ...
answer_end = ( ... text_tokens = tokenizer.convert_ids_to_tokens(input_ids)
tf.argmax(answer_end_scores, axis=1) + 1 ... answer_start_scores, answer_end_scores = model(inputs)
).numpy()[0] # Get the most likely end of answer with the argmax of the score ...
answer = tokenizer.convert_tokens_to_string(tokenizer.convert_ids_to_tokens(input_ids[answer_start:answer_end])) ... answer_start = tf.argmax(
... answer_start_scores, axis=1
print(f"Question: {question}") ... ).numpy()[0] # Get the most likely beginning of answer with the argmax of the score
print(f"Answer: {answer}\n") ... answer_end = (
... tf.argmax(answer_end_scores, axis=1) + 1
This outputs the questions followed by the predicted answers: ... ).numpy()[0] # Get the most likely end of answer with the argmax of the score
... 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? Question: How many pretrained models are available in 🤗 Transformers?
Answer: over 32 + Answer: over 32 +
Question: What does 🤗 Transformers provide? Question: What does 🤗 Transformers provide?
Answer: general - purpose architectures Answer: general - purpose architectures
Question: 🤗 Transformers provides interoperability between which frameworks? Question: 🤗 Transformers provides interoperability between which frameworks?
Answer: tensorflow 2 . 0 and pytorch Answer: tensorflow 2 . 0 and pytorch
...@@ -313,25 +310,44 @@ see `Lewis, Lui, Goyal et al. <https://arxiv.org/abs/1910.13461>`__, part 4.2). ...@@ -313,25 +310,44 @@ see `Lewis, Lui, Goyal et al. <https://arxiv.org/abs/1910.13461>`__, part 4.2).
Here is an example of using pipelines to replace a mask from a sequence: Here is an example of using pipelines to replace a mask from a sequence:
:: .. code-block::
from transformers import pipeline >>> from transformers import pipeline
nlp = pipeline("fill-mask") >>> nlp = pipeline("fill-mask")
print(nlp(f"HuggingFace is creating a {nlp.tokenizer.mask_token} that the community uses to solve NLP tasks."))
This outputs the sequences with the mask filled, the confidence score as well as the token id in the tokenizer This outputs the sequences with the mask filled, the confidence score as well as the token id in the tokenizer
vocabulary: vocabulary:
:: .. code-block::
[ >>> from pprint import pprint
{'sequence': '<s> HuggingFace is creating a tool that the community uses to solve NLP tasks.</s>', 'score': 0.15627853572368622, 'token': 3944}, >>> pprint(nlp(f"HuggingFace is creating a {nlp.tokenizer.mask_token} that the community uses to solve NLP tasks."))
{'sequence': '<s> HuggingFace is creating a framework that the community uses to solve NLP tasks.</s>', 'score': 0.11690319329500198, 'token': 7208}, [{'score': 0.1792745739221573,
{'sequence': '<s> HuggingFace is creating a library that the community uses to solve NLP tasks.</s>', 'score': 0.058063216507434845, 'token': 5560}, 'sequence': '<s>HuggingFace is creating a tool that the community uses to '
{'sequence': '<s> HuggingFace is creating a database that the community uses to solve NLP tasks.</s>', 'score': 0.04211743175983429, 'token': 8503}, 'solve NLP tasks.</s>',
{'sequence': '<s> HuggingFace is creating a prototype that the community uses to solve NLP tasks.</s>', 'score': 0.024718601256608963, 'token': 17715} 'token': 3944,
] 'token_str': 'Ġtool'},
{'score': 0.11349421739578247,
'sequence': '<s>HuggingFace is creating a framework that the community uses '
'to solve NLP tasks.</s>',
'token': 7208,
'token_str': 'Ġframework'},
{'score': 0.05243554711341858,
'sequence': '<s>HuggingFace is creating a library that the community uses to '
'solve NLP tasks.</s>',
'token': 5560,
'token_str': 'Ġlibrary'},
{'score': 0.03493533283472061,
'sequence': '<s>HuggingFace is creating a database that the community uses '
'to solve NLP tasks.</s>',
'token': 8503,
'token_str': 'Ġdatabase'},
{'score': 0.02860250137746334,
'sequence': '<s>HuggingFace is creating a prototype that the community uses '
'to solve NLP tasks.</s>',
'token': 17715,
'token_str': 'Ġprototype'}]
Here is an example doing masked language modeling using a model and a tokenizer. The process is the following: Here is an example doing masked language modeling using a model and a tokenizer. The process is the following:
...@@ -345,51 +361,48 @@ Here is an example doing masked language modeling using a model and a tokenizer. ...@@ -345,51 +361,48 @@ Here is an example doing masked language modeling using a model and a tokenizer.
- Retrieve the top 5 tokens using the PyTorch :obj:`topk` or TensorFlow :obj:`top_k` methods. - Retrieve the top 5 tokens using the PyTorch :obj:`topk` or TensorFlow :obj:`top_k` methods.
- Replace the mask token by the tokens and print the results - Replace the mask token by the tokens and print the results
:: .. code-block::
## PYTORCH CODE
from transformers import AutoModelWithLMHead, AutoTokenizer
import torch
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-cased") >>> ## PYTORCH CODE
model = AutoModelWithLMHead.from_pretrained("distilbert-base-cased") >>> from transformers import AutoModelWithLMHead, AutoTokenizer
>>> import torch
sequence = f"Distilled models are smaller than the models they mimic. Using them instead of the large versions would help {tokenizer.mask_token} our carbon footprint." >>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-cased")
>>> model = AutoModelWithLMHead.from_pretrained("distilbert-base-cased")
input = tokenizer.encode(sequence, return_tensors="pt") >>> sequence = f"Distilled models are smaller than the models they mimic. Using them instead of the large versions would help {tokenizer.mask_token} our carbon footprint."
mask_token_index = torch.where(input == tokenizer.mask_token_id)[1]
token_logits = model(input)[0] >>> input = tokenizer.encode(sequence, return_tensors="pt")
mask_token_logits = token_logits[0, mask_token_index, :] >>> mask_token_index = torch.where(input == tokenizer.mask_token_id)[1]
top_5_tokens = torch.topk(mask_token_logits, 5, dim=1).indices[0].tolist() >>> token_logits = model(input)[0]
>>> mask_token_logits = token_logits[0, mask_token_index, :]
for token in top_5_tokens: >>> top_5_tokens = torch.topk(mask_token_logits, 5, dim=1).indices[0].tolist()
print(sequence.replace(tokenizer.mask_token, tokenizer.decode([token]))) >>> ## TENSORFLOW CODE
## TENSORFLOW CODE >>> from transformers import TFAutoModelWithLMHead, AutoTokenizer
from transformers import TFAutoModelWithLMHead, AutoTokenizer >>> import tensorflow as tf
import tensorflow as tf
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-cased") >>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-cased")
model = TFAutoModelWithLMHead.from_pretrained("distilbert-base-cased") >>> model = TFAutoModelWithLMHead.from_pretrained("distilbert-base-cased")
sequence = f"Distilled models are smaller than the models they mimic. Using them instead of the large versions would help {tokenizer.mask_token} our carbon footprint." >>> sequence = f"Distilled models are smaller than the models they mimic. Using them instead of the large versions would help {tokenizer.mask_token} our carbon footprint."
input = tokenizer.encode(sequence, return_tensors="tf") >>> input = tokenizer.encode(sequence, return_tensors="tf")
mask_token_index = tf.where(input == tokenizer.mask_token_id)[0, 1] >>> mask_token_index = tf.where(input == tokenizer.mask_token_id)[0, 1]
token_logits = model(input)[0] >>> token_logits = model(input)[0]
mask_token_logits = token_logits[0, mask_token_index, :] >>> mask_token_logits = token_logits[0, mask_token_index, :]
top_5_tokens = tf.math.top_k(mask_token_logits, 5).indices.numpy() >>> top_5_tokens = tf.math.top_k(mask_token_logits, 5).indices.numpy()
for token in top_5_tokens:
print(sequence.replace(tokenizer.mask_token, tokenizer.decode([token])))
This prints five sequences, with the top 5 tokens predicted by the model: This prints five sequences, with the top 5 tokens predicted by the model:
:: .. code-block::
>>> 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 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 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 decrease our carbon footprint.
...@@ -408,65 +421,63 @@ Usually, the next token is predicted by sampling from the logits of the last hid ...@@ -408,65 +421,63 @@ Usually, the next token is predicted by sampling from the logits of the last hid
Here is an example 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. Here is an example 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.
:: .. code-block::
## PYTORCH CODE
from transformers import AutoModelWithLMHead, AutoTokenizer, top_k_top_p_filtering
import torch
from torch.nn import functional as F
>>> ## PYTORCH CODE
>>> from transformers import AutoModelWithLMHead, AutoTokenizer, top_k_top_p_filtering
>>> import torch
>>> from torch.nn import functional as F
tokenizer = AutoTokenizer.from_pretrained("gpt2") >>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelWithLMHead.from_pretrained("gpt2") >>> model = AutoModelWithLMHead.from_pretrained("gpt2")
sequence = f"Hugging Face is based in DUMBO, New York City, and " >>> sequence = f"Hugging Face is based in DUMBO, New York City, and "
input_ids = tokenizer.encode(sequence, return_tensors="pt") >>> input_ids = tokenizer.encode(sequence, return_tensors="pt")
# get logits of last hidden state >>> # get logits of last hidden state
next_token_logits = model(input_ids)[0][:, -1, :] >>> next_token_logits = model(input_ids)[0][:, -1, :]
# filter >>> # filter
filtered_next_token_logits = top_k_top_p_filtering(next_token_logits, top_k=50, top_p=1.0) >>> filtered_next_token_logits = top_k_top_p_filtering(next_token_logits, top_k=50, top_p=1.0)
# sample >>> # sample
probs = F.softmax(filtered_next_token_logits, dim=-1) >>> probs = F.softmax(filtered_next_token_logits, dim=-1)
next_token = torch.multinomial(probs, num_samples=1) >>> next_token = torch.multinomial(probs, num_samples=1)
generated = torch.cat([input_ids, next_token], dim=-1) >>> generated = torch.cat([input_ids, next_token], dim=-1)
resulting_string = tokenizer.decode(generated.tolist()[0]) >>> resulting_string = tokenizer.decode(generated.tolist()[0])
print(resulting_string) >>> ## TENSORFLOW CODE
## TENSORFLOW CODE >>> from transformers import TFAutoModelWithLMHead, AutoTokenizer, tf_top_k_top_p_filtering
from transformers import TFAutoModelWithLMHead, AutoTokenizer, tf_top_k_top_p_filtering >>> import tensorflow as tf
import tensorflow as tf
tokenizer = AutoTokenizer.from_pretrained("gpt2") >>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
model = TFAutoModelWithLMHead.from_pretrained("gpt2") >>> model = TFAutoModelWithLMHead.from_pretrained("gpt2")
sequence = f"Hugging Face is based in DUMBO, New York City, and " >>> sequence = f"Hugging Face is based in DUMBO, New York City, and "
input_ids = tokenizer.encode(sequence, return_tensors="tf") >>> input_ids = tokenizer.encode(sequence, return_tensors="tf")
# get logits of last hidden state >>> # get logits of last hidden state
next_token_logits = model(input_ids)[0][:, -1, :] >>> next_token_logits = model(input_ids)[0][:, -1, :]
# filter >>> # filter
filtered_next_token_logits = tf_top_k_top_p_filtering(next_token_logits, top_k=50, top_p=1.0) >>> filtered_next_token_logits = tf_top_k_top_p_filtering(next_token_logits, top_k=50, top_p=1.0)
# sample >>> # sample
next_token = tf.random.categorical(filtered_next_token_logits, dtype=tf.int32, num_samples=1) >>> next_token = tf.random.categorical(filtered_next_token_logits, dtype=tf.int32, num_samples=1)
generated = tf.concat([input_ids, next_token], axis=1) >>> generated = tf.concat([input_ids, next_token], axis=1)
resulting_string = tokenizer.decode(generated.numpy().tolist()[0]) >>> resulting_string = tokenizer.decode(generated.numpy().tolist()[0])
print(resulting_string)
This outputs a (hopefully) coherent next token following the original sequence, which is in our case is the word *has*: This outputs a (hopefully) coherent next token following the original sequence, which is in our case is the word *has*:
:: .. code-block::
print(resulting_string)
Hugging Face is based in DUMBO, New York City, and has Hugging Face is based in DUMBO, New York City, and has
In the next section, we show how this functionality is leveraged in :func:`~transformers.PreTrainedModel.generate` to generate multiple tokens up to a user-defined length. In the next section, we show how this functionality is leveraged in :func:`~transformers.PreTrainedModel.generate` to generate multiple tokens up to a user-defined length.
...@@ -476,12 +487,14 @@ Text Generation ...@@ -476,12 +487,14 @@ Text Generation
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. As an example, is it shown 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). 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. As an example, is it shown 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).
:: .. code-block::
>>> from transformers import pipeline
from transformers import pipeline >>> text_generator = pipeline("text-generation")
>>> print(text_generator("As far as I am concerned, I will", max_length=50, do_sample=False))
[{'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'}]
text_generator = pipeline("text-generation")
print(text_generator("As far as I am concerned, I will", max_length=50))
Here the model generates a random text with a total maximal length of *50* tokens from context *"As far as I am concerned, I will"*. Here the model generates a random text with a total maximal length of *50* tokens from context *"As far as I am concerned, I will"*.
...@@ -489,58 +502,59 @@ The default arguments of ``PreTrainedModel.generate()`` can directly be override ...@@ -489,58 +502,59 @@ The default arguments of ``PreTrainedModel.generate()`` can directly be override
Here is an example for text generation using XLNet and its tokenzier. Here is an example for text generation using XLNet and its tokenzier.
:: .. code-block::
## PYTORCH CODE >>> ## PYTORCH CODE
from transformers import AutoModelWithLMHead, AutoTokenizer >>> from transformers import AutoModelWithLMHead, AutoTokenizer
model = AutoModelWithLMHead.from_pretrained("xlnet-base-cased") >>> model = AutoModelWithLMHead.from_pretrained("xlnet-base-cased")
tokenizer = AutoTokenizer.from_pretrained("xlnet-base-cased") >>> 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 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 >>> PADDING_TEXT = """In 1991, the remains of Russian Tsar Nicholas II and his family
(except for Alexei and Maria) are discovered. ... (except for Alexei and Maria) are discovered.
The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the ... The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the
remainder of the story. 1883 Western Siberia, ... remainder of the story. 1883 Western Siberia,
a young Grigori Rasputin is asked by his father and a group of men to perform magic. ... 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 ... 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 ... 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 ... 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, ... 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>""" ... with people, even a bishop, begging for his blessing. <eod> </s> <eos>"""
prompt = "Today the weather is really nice and I am planning on " >>> 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") >>> 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)) >>> 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) >>> 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:] >>> generated = prompt + tokenizer.decode(outputs[0])[prompt_length:]
print(generated) >>> ## TENSORFLOW CODE
## TENSORFLOW CODE >>> from transformers import TFAutoModelWithLMHead, AutoTokenizer
from transformers import TFAutoModelWithLMHead, AutoTokenizer
>>> model = TFAutoModelWithLMHead.from_pretrained("xlnet-base-cased")
model = TFAutoModelWithLMHead.from_pretrained("xlnet-base-cased") >>> tokenizer = AutoTokenizer.from_pretrained("xlnet-base-cased")
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 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
PADDING_TEXT = """In 1991, the remains of Russian Tsar Nicholas II and his family ... (except for Alexei and Maria) are discovered.
(except for Alexei and Maria) are discovered. ... The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the
The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the ... remainder of the story. 1883 Western Siberia,
remainder of the story. 1883 Western Siberia, ... a young Grigori Rasputin is asked by his father and a group of men to perform magic.
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
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
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
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,
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>"""
with people, even a bishop, begging for his blessing. <eod> </s> <eos>"""
>>> prompt = "Today the weather is really nice and I am planning on "
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")
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))
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)
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:]
generated = prompt + tokenizer.decode(outputs[0])[prompt_length:]
.. code-block::
print(generated) print(generated)
...@@ -575,21 +589,22 @@ of 9 classes: ...@@ -575,21 +589,22 @@ of 9 classes:
It leverages a fine-tuned model on CoNLL-2003, fine-tuned by `@stefan-it <https://github.com/stefan-it>`__ from 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>`__. `dbmdz <https://github.com/dbmdz>`__.
:: .. code-block::
from transformers import pipeline >>> from transformers import pipeline
nlp = pipeline("ner") >>> nlp = pipeline("ner")
sequence = "Hugging Face Inc. is a company based in New York City. Its headquarters are in DUMBO, therefore very" \ >>> sequence = "Hugging Face Inc. is a company based in New York City. Its headquarters are in DUMBO, therefore very"
"close to the Manhattan Bridge which is visible from the window." ... "close to the Manhattan Bridge which is visible from the window."
print(nlp(sequence))
This outputs a list of all words that have been identified as an entity from the 9 classes defined above. Here is the This outputs a list of all words that have been identified as an entity from the 9 classes defined above. Here is the
expected results: expected results:
:: .. code-block::
print(nlp(sequence))
[ [
{'word': 'Hu', 'score': 0.9995632767677307, 'entity': 'I-ORG'}, {'word': 'Hu', 'score': 0.9995632767677307, 'entity': 'I-ORG'},
...@@ -623,75 +638,73 @@ Here is an example doing named entity recognition using a model and a tokenizer. ...@@ -623,75 +638,73 @@ Here is an example doing named entity recognition using a model and a tokenizer.
for each token. for each token.
- Zip together each token with its prediction and print it. - Zip together each token with its prediction and print it.
:: .. code-block::
## PYTORCH CODE >>> ## PYTORCH CODE
from transformers import AutoModelForTokenClassification, AutoTokenizer >>> from transformers import AutoModelForTokenClassification, AutoTokenizer
import torch >>> import torch
model = AutoModelForTokenClassification.from_pretrained("dbmdz/bert-large-cased-finetuned-conll03-english") >>> model = AutoModelForTokenClassification.from_pretrained("dbmdz/bert-large-cased-finetuned-conll03-english")
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
label_list = [ >>> label_list = [
"O", # Outside of a named entity ... "O", # Outside of a named entity
"B-MISC", # Beginning of a miscellaneous entity right after another miscellaneous entity ... "B-MISC", # Beginning of a miscellaneous entity right after another miscellaneous entity
"I-MISC", # Miscellaneous entity ... "I-MISC", # Miscellaneous entity
"B-PER", # Beginning of a person's name right after another person's name ... "B-PER", # Beginning of a person's name right after another person's name
"I-PER", # Person's name ... "I-PER", # Person's name
"B-ORG", # Beginning of an organisation right after another organisation ... "B-ORG", # Beginning of an organisation right after another organisation
"I-ORG", # Organisation ... "I-ORG", # Organisation
"B-LOC", # Beginning of a location right after another location ... "B-LOC", # Beginning of a location right after another location
"I-LOC" # Location ... "I-LOC" # Location
] ... ]
sequence = "Hugging Face Inc. is a company based in New York City. Its headquarters are in DUMBO, therefore very" \ >>> sequence = "Hugging Face Inc. is a company based in New York City. Its headquarters are in DUMBO, therefore very" \
"close to the Manhattan Bridge." ... "close to the Manhattan Bridge."
# Bit of a hack to get the tokens with the special tokens >>> # Bit of a hack to get the tokens with the special tokens
tokens = tokenizer.tokenize(tokenizer.decode(tokenizer.encode(sequence))) >>> tokens = tokenizer.tokenize(tokenizer.decode(tokenizer.encode(sequence)))
inputs = tokenizer.encode(sequence, return_tensors="pt") >>> inputs = tokenizer.encode(sequence, return_tensors="pt")
outputs = model(inputs)[0] >>> outputs = model(inputs)[0]
predictions = torch.argmax(outputs, dim=2) >>> predictions = torch.argmax(outputs, dim=2)
>>> ## TENSORFLOW CODE
print([(token, label_list[prediction]) for token, prediction in zip(tokens, predictions[0].tolist())]) >>> from transformers import TFAutoModelForTokenClassification, AutoTokenizer
## TENSORFLOW CODE >>> import tensorflow as tf
from transformers import TFAutoModelForTokenClassification, AutoTokenizer
import tensorflow as tf >>> model = TFAutoModelForTokenClassification.from_pretrained("dbmdz/bert-large-cased-finetuned-conll03-english")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
model = TFAutoModelForTokenClassification.from_pretrained("dbmdz/bert-large-cased-finetuned-conll03-english")
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") >>> label_list = [
... "O", # Outside of a named entity
label_list = [ ... "B-MISC", # Beginning of a miscellaneous entity right after another miscellaneous entity
"O", # Outside of a named entity ... "I-MISC", # Miscellaneous entity
"B-MISC", # Beginning of a miscellaneous entity right after another miscellaneous entity ... "B-PER", # Beginning of a person's name right after another person's name
"I-MISC", # Miscellaneous entity ... "I-PER", # Person's name
"B-PER", # Beginning of a person's name right after another person's name ... "B-ORG", # Beginning of an organisation right after another organisation
"I-PER", # Person's name ... "I-ORG", # Organisation
"B-ORG", # Beginning of an organisation right after another organisation ... "B-LOC", # Beginning of a location right after another location
"I-ORG", # Organisation ... "I-LOC" # Location
"B-LOC", # Beginning of a location right after another location ... ]
"I-LOC" # Location
] >>> sequence = "Hugging Face Inc. is a company based in New York City. Its headquarters are in DUMBO, therefore very" \
... "close to the Manhattan Bridge."
sequence = "Hugging Face Inc. is a company based in New York City. Its headquarters are in DUMBO, therefore very" \
"close to the Manhattan Bridge." >>> # Bit of a hack to get the tokens with the special tokens
>>> tokens = tokenizer.tokenize(tokenizer.decode(tokenizer.encode(sequence)))
>>> inputs = tokenizer.encode(sequence, return_tensors="tf")
>>> outputs = model(inputs)[0]
>>> predictions = tf.argmax(outputs, axis=2)
# Bit of a hack to get the tokens with the special tokens
tokens = tokenizer.tokenize(tokenizer.decode(tokenizer.encode(sequence)))
inputs = tokenizer.encode(sequence, return_tensors="tf")
outputs = model(inputs)[0]
predictions = tf.argmax(outputs, axis=2)
print([(token, label_list[prediction]) for token, prediction in zip(tokens, predictions[0].numpy())])
This outputs a list of each token mapped to their prediction. Differently from the pipeline, here every token has This outputs a list of each token mapped to their prediction. Differently from the pipeline, here every token has
a prediction as we didn't remove the "0" class which means that no particular entity was found on that token. The a prediction as we didn't remove the "0" class which means that no particular entity was found on that token. The
following array should be the output: following array should be the output:
:: .. code-block::
>>> print([(token, label_list[prediction]) for token, prediction in zip(tokens, predictions[0].numpy())])
[('[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'), ('##c', 'O'), ('##lose', 'O'), ('to', 'O'), ('the', 'O'), ('Manhattan', 'I-LOC'), ('Bridge', 'I-LOC'), ('.', 'O'), ('[SEP]', 'O')] [('[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'), ('##c', 'O'), ('##lose', 'O'), ('to', 'O'), ('the', 'O'), ('Manhattan', 'I-LOC'), ('Bridge', 'I-LOC'), ('.', 'O'), ('[SEP]', 'O')]
Summarization Summarization
...@@ -705,40 +718,39 @@ If you would like to fine-tune a model on a summarization task, you may leverage ...@@ -705,40 +718,39 @@ If you would like to fine-tune a model on a summarization task, you may leverage
Here is an example using the pipelines do to summarization. Here is an example using the pipelines do to summarization.
It leverages a Bart model that was fine-tuned on the CNN / Daily Mail data set. It leverages a Bart model that was fine-tuned on the CNN / Daily Mail data set.
:: .. code-block::
from transformers import pipeline >>> from transformers import pipeline
summarizer = pipeline("summarization") >>> summarizer = pipeline("summarization")
ARTICLE = """ New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County, New York. >>> 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. ... 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. ... 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. ... 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 ... 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. ... 2010 marriage license application, according to court documents.
Prosecutors said the marriages were part of an immigration scam. ... 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. ... 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 ... 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. ... 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. ... 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. ... 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. ... 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 ... 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. ... 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. ... 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. ... If convicted, Barrientos faces up to four years in prison. Her next court appearance is scheduled for May 18.
""" ... """
print(summarizer(ARTICLE, max_length=130, min_length=30))
Because the summarization pipeline depends on the ``PretrainedModel.generate()`` method, we can override the default arguments Because the summarization 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`` and ``min_length`` above. of ``PretrainedModel.generate()`` directly in the pipeline as is shown for ``max_length`` and ``min_length`` above.
This outputs the following summary: This outputs the following summary:
:: .. code-block::
Liana Barrientos has been married 10 times, sometimes within two weeks of each other. Prosecutors say the marriages were part of an immigration scam. She pleaded not guilty at State Supreme Court in the Bronx on Friday. >>> print(summarizer(ARTICLE, max_length=130, min_length=30, do_sample=False))
[{'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. She is believed to still be married to four men.'}]
Here is an example doing summarization using a model and a tokenizer. The process is the following: Here is an example doing summarization using a model and a tokenizer. The process is the following:
...@@ -748,29 +760,26 @@ Here is an example doing summarization using a model and a tokenizer. The proces ...@@ -748,29 +760,26 @@ Here is an example doing summarization using a model and a tokenizer. The proces
- Add the T5 specific prefix "summarize: ". - Add the T5 specific prefix "summarize: ".
Here Google`s T5 model is used that was only pre-trained on a multi-task mixed data set (including CNN / Daily Mail), but nevertheless yields very good results. Here Google`s T5 model is used that was only pre-trained on a multi-task mixed data set (including CNN / Daily Mail), but nevertheless yields very good results.
:: .. code-block::
## PYTORCH CODE
from transformers import AutoModelWithLMHead, AutoTokenizer
model = AutoModelWithLMHead.from_pretrained("t5-base") >>> ## PYTORCH CODE
tokenizer = AutoTokenizer.from_pretrained("t5-base") >>> from transformers import AutoModelWithLMHead, AutoTokenizer
# T5 uses a max_length of 512 so we cut the article to 512 tokens. >>> model = AutoModelWithLMHead.from_pretrained("t5-base")
inputs = tokenizer.encode("summarize: " + ARTICLE, return_tensors="pt", max_length=512) >>> tokenizer = AutoTokenizer.from_pretrained("t5-base")
outputs = model.generate(inputs, max_length=150, min_length=40, length_penalty=2.0, num_beams=4, early_stopping=True)
print(outputs)
## TENSORFLOW CODE >>> # T5 uses a max_length of 512 so we cut the article to 512 tokens.
from transformers import TFAutoModelWithLMHead, AutoTokenizer >>> inputs = tokenizer.encode("summarize: " + ARTICLE, return_tensors="pt", max_length=512)
>>> outputs = model.generate(inputs, max_length=150, min_length=40, length_penalty=2.0, num_beams=4, early_stopping=True)
>>> ## TENSORFLOW CODE
>>> from transformers import TFAutoModelWithLMHead, AutoTokenizer
model = TFAutoModelWithLMHead.from_pretrained("t5-base") >>> model = TFAutoModelWithLMHead.from_pretrained("t5-base")
tokenizer = AutoTokenizer.from_pretrained("t5-base") >>> tokenizer = AutoTokenizer.from_pretrained("t5-base")
# T5 uses a max_length of 512 so we cut the article to 512 tokens. >>> # T5 uses a max_length of 512 so we cut the article to 512 tokens.
inputs = tokenizer.encode("summarize: " + ARTICLE, return_tensors="tf", max_length=512) >>> inputs = tokenizer.encode("summarize: " + ARTICLE, return_tensors="tf", max_length=512)
outputs = model.generate(inputs, max_length=150, min_length=40, length_penalty=2.0, num_beams=4, early_stopping=True) >>> outputs = model.generate(inputs, max_length=150, min_length=40, length_penalty=2.0, num_beams=4, early_stopping=True)
print(outputs)
Translation Translation
---------------------------------------------------- ----------------------------------------------------
...@@ -784,12 +793,13 @@ Here is an example using the pipelines do to translation. ...@@ -784,12 +793,13 @@ Here is an example using the pipelines do to translation.
It leverages a T5 model that was only pre-trained on a multi-task mixture dataset (including WMT), but yields impressive It leverages a T5 model that was only pre-trained on a multi-task mixture dataset (including WMT), but yields impressive
translation results nevertheless. translation results nevertheless.
:: .. code-block::
from transformers import pipeline >>> from transformers import pipeline
translator = pipeline("translation_en_to_de") >>> translator = pipeline("translation_en_to_de")
print(translator("Hugging Face is a technology company based in New York and Paris", max_length=40)) >>> 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.'}]
Because the translation pipeline depends on the ``PretrainedModel.generate()`` method, we can override the default arguments 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. of ``PretrainedModel.generate()`` directly in the pipeline as is shown for ``max_length`` above.
...@@ -806,26 +816,30 @@ Here is an example doing translation using a model and a tokenizer. The process ...@@ -806,26 +816,30 @@ Here is an example doing translation using a model and a tokenizer. The process
- Leverage the ``PretrainedModel.generate()`` method. - Leverage the ``PretrainedModel.generate()`` method.
- Add the T5 specific prefix "translate English to German: " - Add the T5 specific prefix "translate English to German: "
:: .. code-block::
## PYTORCH CODE
from transformers import AutoModelWithLMHead, AutoTokenizer
model = AutoModelWithLMHead.from_pretrained("t5-base") >>> ## PYTORCH CODE
tokenizer = AutoTokenizer.from_pretrained("t5-base") >>> from transformers import AutoModelWithLMHead, AutoTokenizer
inputs = tokenizer.encode("translate English to German: Hugging Face is a technology company based in New York and Paris", return_tensors="pt") >>> model = AutoModelWithLMHead.from_pretrained("t5-base")
outputs = model.generate(inputs, max_length=40, num_beams=4, early_stopping=True) >>> tokenizer = AutoTokenizer.from_pretrained("t5-base")
print(outputs) >>> inputs = tokenizer.encode("translate English to German: Hugging Face is a technology company based in New York and Paris", return_tensors="pt")
>>> outputs = model.generate(inputs, max_length=40, num_beams=4, early_stopping=True)
## TENSORFLOW CODE >>> print(outputs)
from transformers import TFAutoModelWithLMHead, AutoTokenizer tensor([[ 0, 11560, 3896, 8881, 229, 236, 3, 14366, 15377, 181,
11216, 16, 368, 1060, 64, 1919, 5]])
>>> ## TENSORFLOW CODE
>>> from transformers import TFAutoModelWithLMHead, AutoTokenizer
model = TFAutoModelWithLMHead.from_pretrained("t5-base") >>> model = TFAutoModelWithLMHead.from_pretrained("t5-base")
tokenizer = AutoTokenizer.from_pretrained("t5-base") >>> tokenizer = AutoTokenizer.from_pretrained("t5-base")
inputs = tokenizer.encode("translate English to German: Hugging Face is a technology company based in New York and Paris", return_tensors="tf") >>> inputs = tokenizer.encode("translate English to German: Hugging Face is a technology company based in New York and Paris", return_tensors="tf")
outputs = model.generate(inputs, max_length=40, num_beams=4, early_stopping=True) >>> outputs = model.generate(inputs, max_length=40, num_beams=4, early_stopping=True)
print(outputs) >>> print(outputs)
tf.Tensor(
[[ 0 11560 3896 8881 229 236 3 14366 15377 181 11216 16
368 1060 64 1919 5]], shape=(1, 17), dtype=int32)
...@@ -86,7 +86,7 @@ extras["all"] = extras["serving"] + ["tensorflow", "torch"] ...@@ -86,7 +86,7 @@ extras["all"] = extras["serving"] + ["tensorflow", "torch"]
extras["testing"] = ["pytest", "pytest-xdist", "timeout-decorator", "psutil"] extras["testing"] = ["pytest", "pytest-xdist", "timeout-decorator", "psutil"]
# sphinx-rtd-theme==0.5.0 introduced big changes in the style. # sphinx-rtd-theme==0.5.0 introduced big changes in the style.
extras["docs"] = ["recommonmark", "sphinx", "sphinx-markdown-tables", "sphinx-rtd-theme==0.4.3"] extras["docs"] = ["recommonmark", "sphinx", "sphinx-markdown-tables", "sphinx-rtd-theme==0.4.3", "sphinx-copybutton"]
extras["quality"] = [ extras["quality"] = [
"black", "black",
"isort @ git+git://github.com/timothycrosley/isort.git@e63ae06ec7d70b06df9e528357650281a3d3ec22#egg=isort", "isort @ git+git://github.com/timothycrosley/isort.git@e63ae06ec7d70b06df9e528357650281a3d3ec22#egg=isort",
......
...@@ -81,22 +81,22 @@ class AlbertConfig(PretrainedConfig): ...@@ -81,22 +81,22 @@ class AlbertConfig(PretrainedConfig):
Example:: Example::
from transformers import AlbertConfig, AlbertModel >>> from transformers import AlbertConfig, AlbertModel
# Initializing an ALBERT-xxlarge style configuration >>> # Initializing an ALBERT-xxlarge style configuration
albert_xxlarge_configuration = AlbertConfig() >>> albert_xxlarge_configuration = AlbertConfig()
# Initializing an ALBERT-base style configuration >>> # Initializing an ALBERT-base style configuration
albert_base_configuration = AlbertConfig( >>> albert_base_configuration = AlbertConfig(
hidden_size=768, ... hidden_size=768,
num_attention_heads=12, ... num_attention_heads=12,
intermediate_size=3072, ... intermediate_size=3072,
) ... )
# Initializing a model from the ALBERT-base style configuration >>> # Initializing a model from the ALBERT-base style configuration
model = AlbertModel(albert_xxlarge_configuration) >>> model = AlbertModel(albert_xxlarge_configuration)
# Accessing the model configuration >>> # Accessing the model configuration
configuration = model.config >>> configuration = model.config
""" """
model_type = "albert" model_type = "albert"
......
...@@ -73,9 +73,13 @@ class BartConfig(PretrainedConfig): ...@@ -73,9 +73,13 @@ class BartConfig(PretrainedConfig):
): ):
r""" r"""
:class:`~transformers.BartConfig` is the configuration class for `BartModel`. :class:`~transformers.BartConfig` is the configuration class for `BartModel`.
Examples:
config = BartConfig.from_pretrained('bart-large') Examples::
model = BartModel(config)
>>> from transformers import BartConfig, BartModel
>>> config = BartConfig.from_pretrained('facebook/bart-large')
>>> model = BartModel(config)
""" """
if "hidden_size" in common_kwargs: if "hidden_size" in common_kwargs:
raise ValueError("hidden size is called d_model") raise ValueError("hidden size is called d_model")
......
...@@ -95,16 +95,16 @@ class BertConfig(PretrainedConfig): ...@@ -95,16 +95,16 @@ class BertConfig(PretrainedConfig):
Example:: Example::
from transformers import BertModel, BertConfig >>> from transformers import BertModel, BertConfig
# Initializing a BERT bert-base-uncased style configuration >>> # Initializing a BERT bert-base-uncased style configuration
configuration = BertConfig() >>> configuration = BertConfig()
# Initializing a model from the bert-base-uncased style configuration >>> # Initializing a model from the bert-base-uncased style configuration
model = BertModel(configuration) >>> model = BertModel(configuration)
# Accessing the model configuration >>> # Accessing the model configuration
configuration = model.config >>> configuration = model.config
""" """
model_type = "bert" model_type = "bert"
......
...@@ -66,16 +66,16 @@ class CTRLConfig(PretrainedConfig): ...@@ -66,16 +66,16 @@ class CTRLConfig(PretrainedConfig):
Example:: Example::
from transformers import CTRLModel, CTRLConfig >>> from transformers import CTRLModel, CTRLConfig
# Initializing a CTRL configuration >>> # Initializing a CTRL configuration
configuration = CTRLConfig() >>> configuration = CTRLConfig()
# Initializing a model from the configuration >>> # Initializing a model from the configuration
model = CTRLModel(configuration) >>> model = CTRLModel(configuration)
# Accessing the model configuration >>> # Accessing the model configuration
configuration = model.config >>> configuration = model.config
""" """
model_type = "ctrl" model_type = "ctrl"
......
...@@ -80,16 +80,16 @@ class DistilBertConfig(PretrainedConfig): ...@@ -80,16 +80,16 @@ class DistilBertConfig(PretrainedConfig):
Example:: Example::
from transformers import DistilBertModel, DistilBertConfig >>> from transformers import DistilBertModel, DistilBertConfig
# Initializing a DistilBERT configuration >>> # Initializing a DistilBERT configuration
configuration = DistilBertConfig() >>> configuration = DistilBertConfig()
# Initializing a model from the configuration >>> # Initializing a model from the configuration
model = DistilBertModel(configuration) >>> model = DistilBertModel(configuration)
# Accessing the model configuration >>> # Accessing the model configuration
configuration = model.config >>> configuration = model.config
""" """
model_type = "distilbert" model_type = "distilbert"
......
...@@ -101,16 +101,16 @@ class ElectraConfig(PretrainedConfig): ...@@ -101,16 +101,16 @@ class ElectraConfig(PretrainedConfig):
Example:: Example::
from transformers import ElectraModel, ElectraConfig >>> from transformers import ElectraModel, ElectraConfig
# Initializing a ELECTRA electra-base-uncased style configuration >>> # Initializing a ELECTRA electra-base-uncased style configuration
configuration = ElectraConfig() >>> configuration = ElectraConfig()
# Initializing a model from the electra-base-uncased style configuration >>> # Initializing a model from the electra-base-uncased style configuration
model = ElectraModel(configuration) >>> model = ElectraModel(configuration)
# Accessing the model configuration >>> # Accessing the model configuration
configuration = model.config >>> configuration = model.config
""" """
model_type = "electra" model_type = "electra"
......
...@@ -42,20 +42,20 @@ class EncoderDecoderConfig(PretrainedConfig): ...@@ -42,20 +42,20 @@ class EncoderDecoderConfig(PretrainedConfig):
Example:: Example::
from transformers import BertConfig, EncoderDecoderConfig, EncoderDecoderModel >>> from transformers import BertConfig, EncoderDecoderConfig, EncoderDecoderModel
# Initializing a BERT bert-base-uncased style configuration >>> # Initializing a BERT bert-base-uncased style configuration
config_encoder = BertConfig() >>> config_encoder = BertConfig()
config_decoder = BertConfig() >>> config_decoder = BertConfig()
config = EncoderDecoderConfig.from_encoder_decoder_configs(config_encoder, config_decoder) >>> config = EncoderDecoderConfig.from_encoder_decoder_configs(config_encoder, config_decoder)
# Initializing a Bert2Bert model from the bert-base-uncased style configurations >>> # Initializing a Bert2Bert model from the bert-base-uncased style configurations
model = EncoderDecoderModel(config=config) >>> model = EncoderDecoderModel(config=config)
# Accessing the model configuration >>> # Accessing the model configuration
config_encoder = model.config.encoder >>> config_encoder = model.config.encoder
config_decoder = model.config.decoder >>> config_decoder = model.config.decoder
""" """
model_type = "encoder_decoder" model_type = "encoder_decoder"
......
...@@ -100,16 +100,16 @@ class GPT2Config(PretrainedConfig): ...@@ -100,16 +100,16 @@ class GPT2Config(PretrainedConfig):
Example:: Example::
from transformers import GPT2Model, GPT2Config >>> from transformers import GPT2Model, GPT2Config
# Initializing a GPT2 configuration >>> # Initializing a GPT2 configuration
configuration = GPT2Config() >>> configuration = GPT2Config()
# Initializing a model from the configuration >>> # Initializing a model from the configuration
model = GPT2Model(configuration) >>> model = GPT2Model(configuration)
# Accessing the model configuration >>> # Accessing the model configuration
configuration = model.config >>> configuration = model.config
""" """
model_type = "gpt2" model_type = "gpt2"
......
...@@ -49,16 +49,16 @@ class LongformerConfig(RobertaConfig): ...@@ -49,16 +49,16 @@ class LongformerConfig(RobertaConfig):
Example:: Example::
from transformers import LongformerConfig, LongformerModel >>> from transformers import LongformerConfig, LongformerModel
# Initializing a Longformer configuration >>> # Initializing a Longformer configuration
configuration = LongformerConfig() >>> configuration = LongformerConfig()
# Initializing a model from the configuration >>> # Initializing a model from the configuration
model = LongformerModel(configuration) >>> model = LongformerModel(configuration)
# Accessing the model configuration >>> # Accessing the model configuration
configuration = model.config >>> configuration = model.config
""" """
model_type = "longformer" model_type = "longformer"
......
...@@ -85,16 +85,16 @@ class MobileBertConfig(PretrainedConfig): ...@@ -85,16 +85,16 @@ class MobileBertConfig(PretrainedConfig):
Example: Example:
from transformers import MobileBertModel, MobileBertConfig >>> from transformers import MobileBertModel, MobileBertConfig
# Initializing a MobileBERT configuration >>> # Initializing a MobileBERT configuration
configuration = MobileBertConfig() >>> configuration = MobileBertConfig()
# Initializing a model from the configuration above >>> # Initializing a model from the configuration above
model = MobileBertModel(configuration) >>> model = MobileBertModel(configuration)
# Accessing the model configuration >>> # Accessing the model configuration
configuration = model.config >>> configuration = model.config
Attributes: Attributes:
pretrained_config_archive_map (Dict[str, str]): pretrained_config_archive_map (Dict[str, str]):
......
...@@ -98,16 +98,16 @@ class OpenAIGPTConfig(PretrainedConfig): ...@@ -98,16 +98,16 @@ class OpenAIGPTConfig(PretrainedConfig):
Example:: Example::
from transformers import OpenAIGPTConfig, OpenAIGPTModel >>> from transformers import OpenAIGPTConfig, OpenAIGPTModel
# Initializing a GPT configuration >>> # Initializing a GPT configuration
configuration = OpenAIGPTConfig() >>> configuration = OpenAIGPTConfig()
# Initializing a model from the configuration >>> # Initializing a model from the configuration
model = OpenAIGPTModel(configuration) >>> model = OpenAIGPTModel(configuration)
# Accessing the model configuration >>> # Accessing the model configuration
configuration = model.config >>> configuration = model.config
""" """
model_type = "openai-gpt" model_type = "openai-gpt"
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment