Compare commits
41
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4c7fe867f7 | ||
|
|
17a831a158 | ||
|
|
84081e0919 | ||
|
|
9b23585e4d | ||
|
|
58cca47c16 | ||
|
|
991172922f | ||
|
|
b58a15a31e | ||
|
|
fedabcd154 | ||
|
|
17ade127b9 | ||
|
|
814ed7ee76 | ||
|
|
49281ac939 | ||
|
|
97355339f6 | ||
|
|
55b932a818 | ||
|
|
21cd8c4086 | ||
|
|
8438bab38e | ||
|
|
6b735a7253 | ||
|
|
ef0e9d806c | ||
|
|
13a8588f2d | ||
|
|
a0a6387a0d | ||
|
|
215db688da | ||
|
|
69d313e808 | ||
|
|
84e56669af | ||
|
|
c6a510c6fa | ||
|
|
6726416e4a | ||
|
|
812def00c9 | ||
|
|
306f1a2695 | ||
|
|
d16e36c7e5 | ||
|
|
f4323dbf8c | ||
|
|
35befd9ce3 | ||
|
|
fe81f7d12c | ||
|
|
d697b6ca75 | ||
|
|
e0d58ddb65 | ||
|
|
608d5a7c44 | ||
|
|
6c55e9fc32 | ||
|
|
734a28a767 | ||
|
|
43cb03a93d | ||
|
|
13deb95a40 | ||
|
|
9c219305f5 | ||
|
|
64e3d966b1 | ||
|
|
4ade7491f4 | ||
|
|
d60d231ea4 |
@@ -87,7 +87,7 @@ function addVersionControl() {
|
||||
const parts = location.toString().split('/');
|
||||
let versionIndex = parts.length - 2;
|
||||
// Index page may not have a last part with filename.html so we need to go up
|
||||
if (parts[parts.length - 1] != "" && ! parts[parts.length - 1].match(/\.html$/)) {
|
||||
if (parts[parts.length - 1] != "" && ! parts[parts.length - 1].match(/\.html$|^search.html?/)) {
|
||||
versionIndex = parts.length - 1;
|
||||
}
|
||||
// Main classes and models are nested so we need to go deeper
|
||||
|
||||
@@ -11,7 +11,7 @@ General terms
|
||||
tokens at a certain timestep.
|
||||
- MLM: masked language modeling, a pretraining task where the model sees a corrupted version of the texts, usually done
|
||||
by masking some tokens randomly, and has to predict the original text.
|
||||
- multimodal: a task taht combines texts with another kind of inputs (for instance images).
|
||||
- multimodal: a task that combines texts with another kind of inputs (for instance images).
|
||||
- NLG: natural language generation, all tasks related to generating text ( for instance talk with transformers,
|
||||
translation)
|
||||
- NLP: natural language processing, a generic way to say "deal with texts".
|
||||
|
||||
@@ -142,6 +142,7 @@ conversion utilities for the following models:
|
||||
preprocessing
|
||||
training
|
||||
model_sharing
|
||||
tokenizer_summary
|
||||
multilingual
|
||||
|
||||
.. toctree::
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Optimizer
|
||||
Optimization
|
||||
----------------------------------------------------
|
||||
|
||||
The ``.optimization`` module provides:
|
||||
@@ -7,24 +7,25 @@ The ``.optimization`` module provides:
|
||||
- several schedules in the form of schedule objects that inherit from ``_LRSchedule``:
|
||||
- a gradient accumulation class to accumulate the gradients of multiple batches
|
||||
|
||||
``AdamW``
|
||||
~~~~~~~~~~~~~~~~
|
||||
``AdamW`` (PyTorch)
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.AdamW
|
||||
:members:
|
||||
|
||||
``AdamWeightDecay``
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
``AdamWeightDecay`` (TensorFlow)
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.AdamWeightDecay
|
||||
|
||||
.. autofunction:: transformers.create_optimizer
|
||||
|
||||
Schedules
|
||||
----------------------------------------------------
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Learning Rate Schedules (Pytorch)
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Learning Rate Schedules
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
.. autofunction:: transformers.get_constant_schedule
|
||||
|
||||
|
||||
@@ -56,16 +57,16 @@ Learning Rate Schedules
|
||||
:target: /imgs/warmup_linear_schedule.png
|
||||
:alt:
|
||||
|
||||
``Warmup``
|
||||
~~~~~~~~~~~~~~~~
|
||||
``Warmup`` (TensorFlow)
|
||||
^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
.. autoclass:: transformers.WarmUp
|
||||
:members:
|
||||
|
||||
Gradient Strategies
|
||||
----------------------------------------------------
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
``GradientAccumulator``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
``GradientAccumulator`` (TensorFlow)
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
.. autoclass:: transformers.GradientAccumulator
|
||||
|
||||
@@ -112,3 +112,17 @@ ReformerModelWithLMHead
|
||||
|
||||
.. autoclass:: transformers.ReformerModelWithLMHead
|
||||
:members:
|
||||
|
||||
|
||||
ReformerForMaskedLM
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.ReformerForMaskedLM
|
||||
:members:
|
||||
|
||||
|
||||
ReformerForQuestionAnswering
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.ReformerForQuestionAnswering
|
||||
:members:
|
||||
|
||||
@@ -146,8 +146,9 @@ Using the tokenizer
|
||||
|
||||
We mentioned the tokenizer is responsible for the preprocessing of your texts. First, it will split a given text in
|
||||
words (or part of words, punctuation symbols, etc.) usually called `tokens`. There are multiple rules that can govern
|
||||
that process, which is why we need to instantiate the tokenizer using the name of the model, to make sure we use the
|
||||
same rules as when the model was pretrained.
|
||||
that process (you can learn more about them in the :doc:`tokenizer_summary <tokenizer_summary>`, which is why we need
|
||||
to instantiate the tokenizer using the name of the model, to make sure we use the same rules as when the model was
|
||||
pretrained.
|
||||
|
||||
The second step is to convert those `tokens` into numbers, to be able to build a tensor out of them and feed them to
|
||||
the model. To do this, the tokenizer has a `vocab`, which is the part we download when we instantiate it with the
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
Tokenizer summary
|
||||
-----------------
|
||||
|
||||
In this page, we will have a closer look at tokenization. As we saw in
|
||||
:doc:`the preprocessing tutorial <preprocessing>`, tokenizing a text is splitting it into words or subwords, which then
|
||||
are converted to ids. The second part is pretty straightforward, here we will focus on the first part. More
|
||||
specifically, we will look at the three main different kinds of tokenizers used in 🤗 Transformers:
|
||||
:ref:`Byte-Pair Encoding (BPE) <byte-pair-encoding>`, :ref:`WordPiece <wordpiece>` and
|
||||
:ref:`SentencePiece <sentencepiece>`, and provide examples of models using each of those.
|
||||
|
||||
Note that on each model page, you can look at the documentation of the associated tokenizer to know which of those
|
||||
algorithms the pretrained model used. For instance, if we look at :class:`~transformers.BertTokenizer`, we can see it's
|
||||
using :ref:`WordPiece <wordpiece>`.
|
||||
|
||||
Introduction to tokenization
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Splitting a text in smaller chunks is a task that's harder than it looks, and there are multiple ways of doing it. For
|
||||
instance, let's look at the sentence "Don't you love 🤗 Transformers? We sure do." A first simple way of tokenizing
|
||||
this text is just to split it by spaces, which would give:
|
||||
|
||||
::
|
||||
|
||||
["Don't", "you", "love", "🤗", "Transformers?", "We", "sure", "do."]
|
||||
|
||||
This is a nice first step, but if we look at the tokens "Transformers?" or "do.", we can see we can do better. Those
|
||||
will be different than the tokens "Transformers" and "do" for our model, so we should probably take the punctuation
|
||||
into account. This would give:
|
||||
|
||||
::
|
||||
|
||||
["Don", "'", "t", "you", "love", "🤗", "Transformers", "?", "We", "sure", "do", "."]
|
||||
|
||||
which is better already. One thing that is annoying though is how it dealt with "Don't". "Don't" stands for do not, so
|
||||
it should probably be better tokenized as ``["Do", "n't"]``. This is where things start getting more complicated, and
|
||||
part of the reason each kind of model has its own tokenizer class. Depending on the rules we apply to split our texts
|
||||
into tokens, we'll get different tokenized versions of the same text. And of course, a given pretrained model won't
|
||||
perform properly if you don't use the exact same rules as the persons who pretrained it.
|
||||
|
||||
`spaCy <https://spacy.io/>`__ and `Moses <http://www.statmt.org/moses/?n=Development.GetStarted>`__ are two popular
|
||||
rule-based tokenizers. On the text above, they'd output something like:
|
||||
|
||||
::
|
||||
|
||||
["Do", "n't", "you", "love", "🤗", "Transformers", "?", "We", "sure", "do", "."]
|
||||
|
||||
Space/punctuation-tokenization and rule-based tokenization are both examples of word tokenization, which is splitting a
|
||||
sentence into words. While it's the most intuitive way to separate texts in smaller chunks, it can have a problem when
|
||||
you have a huge corpus: it usually yields a very big vocabulary (the set of all unique tokens used).
|
||||
:doc:`Transformer XL <model_doc/transformerxl>` for instance uses space/punctuation-tokenization, and has a vocabulary
|
||||
size of 267,735!
|
||||
|
||||
A huge vocabulary size means a huge embedding matrix at the start of the model, which will cause memory problems.
|
||||
TransformerXL deals with it by using a special kind of embeddings called adaptive embeddings, but in general,
|
||||
transformers model rarely have a vocabulary size greater than 50,000, especially if they are trained on a single
|
||||
language.
|
||||
|
||||
So if tokenizing on words is unsatisfactory, we could go on the opposite direction and simply tokenize on characters.
|
||||
While it's very simple and would save a lot of memory, this doesn't allow the model to learn representations of texts
|
||||
as meaningful as when using a word tokenization, leading to a loss of performance. So to get the best of both worlds,
|
||||
all transformers models use a hybrid between word-level and character-level tokenization called subword tokenization.
|
||||
|
||||
Subword tokenization
|
||||
^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Subword tokenization algorithms rely on the principle that most common words should be left as is, but rare words
|
||||
should be decomposed in meaningful subword units. For instance "annoyingly" might be considered a rare word and
|
||||
decomposed as "annoying" and "ly". This is especially useful in agglutinative languages such as Turkish, where you can
|
||||
form (almost) arbitrarily long complex words by stringing together some subwords.
|
||||
|
||||
This allows the model to keep a reasonable vocabulary while still learning useful representations for common words or
|
||||
subwords. This also gives the ability to the model to process words it has never seen before, by decomposing them into
|
||||
subwords it knows. For instance, the base :class:`~transformers.BertTokenizer` will tokenize "I have a new GPU!" like
|
||||
this:
|
||||
|
||||
::
|
||||
|
||||
>>> from transformers import BertTokenizer
|
||||
>>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
|
||||
>>> tokenizer.tokenize("I have a new GPU!")
|
||||
['i', 'have', 'a', 'new', 'gp', '##u', '!']
|
||||
|
||||
Since we are considering the uncased model, the sentence was lowercased first. Then all the words were present in the
|
||||
vocabulary of the tokenizer, except for "gpu", so the tokenizer split it in subwords it knows: "gp" and "##u". The "##"
|
||||
means that the rest of the token should be attached to the previous one, without space (for when we need to decode
|
||||
predictions and reverse the tokenization).
|
||||
|
||||
Another example is when we use the base :class:`~transformers.XLNetTokenizer` to tokenize our previous text:
|
||||
|
||||
::
|
||||
|
||||
>>> from transformers import XLNetTokenizer
|
||||
>>> tokenizer = XLNetTokenizer.from_pretrained('xlnet-base-cased')
|
||||
>>> tokenizer.tokenize("Don't you love 🤗 Transformers? We sure do.")
|
||||
['▁Don', "'", 't', '▁you', '▁love', '▁', '🤗', '▁', 'Transform', 'ers', '?', '▁We', '▁sure', '▁do', '.']
|
||||
|
||||
We'll get back to the meaning of those '▁' when we look at :ref:`SentencePiece <sentencepiece>` but you can see
|
||||
Transformers has been split into "Transform" and "ers".
|
||||
|
||||
Let's now look at how the different subword tokenization algorithms work. Note that they all rely on some form of
|
||||
training which is usually done on the corpus the corresponding model will be trained on.
|
||||
|
||||
.. _byte-pair-encoding:
|
||||
|
||||
Byte-Pair Encoding
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Byte-Pair Encoding was introduced in `this paper <https://arxiv.org/abs/1508.07909>`__. It relies on a pretokenizer
|
||||
splitting the training data into words, which can be a simple space tokenization
|
||||
(:doc:`GPT-2 <model_doc/gpt2>` and :doc:`Roberta <model_doc/roberta>` uses this for instance) or a rule-based tokenizer
|
||||
(:doc:`XLM <model_doc/xlm>` use Moses for most languages, as does :doc:`FlauBERT <model_doc/flaubert>`),
|
||||
|
||||
:doc:`GPT <model_doc/gpt>` uses Spacy and ftfy) and, counts the frequency of each word in the training corpus.
|
||||
|
||||
It then begins from the list of all characters, and will learn merge rules to form a new token from two symbols in the
|
||||
vocabulary until it has learned a vocabulary of the desired size (this is a hyperparameter to pick).
|
||||
|
||||
Let's say that after the pre-tokenization we have the following words (the number indicating the frequency of each
|
||||
word):
|
||||
|
||||
::
|
||||
|
||||
('hug', 10), ('pug', 5), ('pun', 12), ('bun', 4), ('hugs', 5)
|
||||
|
||||
Then the base vocabulary is ['b', 'g', 'h', 'n', 'p', 's', 'u'] and all our words are first split by character:
|
||||
|
||||
::
|
||||
|
||||
('h' 'u' 'g', 10), ('p' 'u' 'g', 5), ('p' 'u' 'n', 12), ('b' 'u' 'n', 4), ('h' 'u' 'g' 's', 5)
|
||||
|
||||
We then take each pair of symbols and look at the most frequent. For instance 'hu' is present `10 + 5 = 15` times (10
|
||||
times in the 10 occurrences of 'hug', 5 times in the 5 occurrences of 'hugs'). The most frequent here is 'ug', present
|
||||
`10 + 5 + 2 + 5 = 22` times in total. So the first merge rule the tokenizer learns is to group all 'u' and 'g' together
|
||||
then it adds 'ug' to the vocabulary. Our corpus then becomes
|
||||
|
||||
::
|
||||
|
||||
('h' 'ug', 10), ('p' 'ug', 5), ('p' 'u' 'n', 12), ('b' 'u' 'n', 4), ('h' 'ug' 's', 5)
|
||||
|
||||
and we continue by looking at the next most common pair of symbols. It's 'un', present 16 times, so we merge those two
|
||||
and add 'un' to the vocabulary. Then it's 'hug' (as 'h' + 'ug'), present 15 times, so we merge those two and add 'hug'
|
||||
to the vocabulary.
|
||||
|
||||
At this stage, the vocabulary is ``['b', 'g', 'h', 'n', 'p', 's', 'u', 'ug', 'un', 'hug']`` and our corpus is
|
||||
represented as
|
||||
|
||||
::
|
||||
|
||||
('hug', 10), ('p' 'ug', 5), ('p' 'un', 12), ('b' 'un', 4), ('hug' 's', 5)
|
||||
|
||||
If we stop there, the tokenizer can apply the rules it learned to new words (as long as they don't contain characters that
|
||||
were not in the base vocabulary). For instance 'bug' would be tokenized as ``['b', 'ug']`` but mug would be tokenized as
|
||||
``['<unk>', 'ug']`` since the 'm' is not in the base vocabulary. This doesn't happen to letters in general (since the
|
||||
base corpus uses all of them), but to special characters like emojis.
|
||||
|
||||
As we said before, the vocabulary size (which is the base vocabulary size + the number of merges) is a hyperparameter
|
||||
to choose. For instance :doc:`GPT <model_doc/gpt>` has a vocabulary size of 40,478 since they have 478 base characters
|
||||
and chose to stop the training of the tokenizer at 40,000 merges.
|
||||
|
||||
Byte-level BPE
|
||||
^^^^^^^^^^^^^^
|
||||
|
||||
To deal with the fact the base vocabulary needs to get all base characters, which can be quite big if one allows for
|
||||
all unicode characters, the
|
||||
`GPT-2 paper <https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf>`__
|
||||
introduces a clever trick, which is to use bytes as the base vocabulary (which gives a size of 256). With some
|
||||
additional rules to deal with punctuation, this manages to be able to tokenize every text without needing an unknown
|
||||
token. For instance, the :doc:`GPT-2 model <model_doc/gpt>` has a vocabulary size of 50,257, which corresponds to the
|
||||
256 bytes base tokens, a special end-of-text token and the symbols learned with 50,000 merges.
|
||||
|
||||
.. _wordpiece:
|
||||
|
||||
WordPiece
|
||||
=========
|
||||
|
||||
WordPiece is the subword tokenization algorithm used for :doc:`BERT <model_doc/bert>` (as well as
|
||||
:doc:`DistilBERT <model_doc/distilbert>` and :doc:`Electra <model_doc/electra>`) and was outlined in
|
||||
`this paper <https://static.googleusercontent.com/media/research.google.com/ja//pubs/archive/37842.pdf>`__. It relies
|
||||
on the same base as BPE, which is to initialize the vocabulary to every character present in the corpus and
|
||||
progressively learn a given number of merge rules, the difference is that it doesn't choose the pair that is the most
|
||||
frequent but the one that will maximize the likelihood on the corpus once merged.
|
||||
|
||||
What does this mean? Well, in the previous example, it means we would only merge 'u' and 'g' if the probability of
|
||||
having 'ug' divided by the probability of having 'u' then 'g' is greater than for any other pair of symbols. It's
|
||||
subtly different from what BPE does in the sense that it evaluates what it "loses" by merging two symbols and makes
|
||||
sure it's `worth it`.
|
||||
|
||||
.. _unigram:
|
||||
|
||||
Unigram
|
||||
=======
|
||||
|
||||
Unigram is a subword tokenization algorithm introduced in `this paper <https://arxiv.org/pdf/1804.10959.pdf>`__.
|
||||
Instead of starting with a group of base symbols and learning merges with some rule, like BPE or WordPiece, it starts
|
||||
from a large vocabulary (for instance, all pretokenized words and the most common substrings) that it will trim down
|
||||
progressively. It's not used directly for any of the pretrained models in the library, but it's used in conjunction
|
||||
with :ref:`SentencePiece <sentencepiece>`.
|
||||
|
||||
More specifically, at a given step, unigram computes a loss from the corpus we have and the current vocabulary, then,
|
||||
for each subword, evaluate how much the loss would augment if the subword was removed from the vocabulary. It then
|
||||
sorts the subwords by this quantity (that represents how worse the loss becomes if the token is removed) and removes
|
||||
all the worst p tokens (for instance p could be 10% or 20%). It then repeats the process until the vocabulary has
|
||||
reached the desired size, always keeping the base characters (to be able to tokenize any word written with them, like
|
||||
BPE or WordPiece).
|
||||
|
||||
Contrary to BPE and WordPiece that work out rules in a certain order that you can then apply in the same order when
|
||||
tokenizing new text, Unigram will have several ways of tokenizing a new text. For instance, if it ends up with the
|
||||
vocabulary
|
||||
|
||||
::
|
||||
|
||||
['b', 'g', 'h', 'n', 'p', 's', 'u', 'ug', 'un', 'hug']
|
||||
|
||||
we had before, it could tokenize "hugs" as ``['hug', 's']``, ``['h', 'ug', 's']`` or ``['h', 'u', 'g', 's']``. So which
|
||||
one choose? On top of saving the vocabulary, the trained tokenizer will save the probability of each token in the
|
||||
training corpus. You can then give a probability to each tokenization (which is the product of the probabilities of the
|
||||
tokens forming it) and pick the most likely one (or if you want to apply some data augmentation, you could sample one
|
||||
of the tokenization according to their probabilities).
|
||||
|
||||
Those probabilities are what are used to define the loss that trains the tokenizer: if our corpus consists of the
|
||||
words :math:`x_{1}, \dots, x_{N}` and if for the word :math:`x_{i}` we note :math:`S(x_{i})` the set of all possible
|
||||
tokenizations of :math:`x_{i}` (with the current vocabulary), then the loss is defined as
|
||||
|
||||
.. math::
|
||||
\mathcal{L} = -\sum_{i=1}^{N} \log \left ( \sum_{x \in S(x_{i})} p(x) \right )
|
||||
|
||||
.. _sentencepiece:
|
||||
|
||||
SentencePiece
|
||||
=============
|
||||
|
||||
All the methods we have been looking at so far required some from of pretrokenization, which has a central problem: not
|
||||
all languages use spaces to separate words. This is a problem :doc:`XLM <model_doc/xlm>` solves by using specific
|
||||
pretokenizers for each of those languages (in this case, Chinese, Japanese and Thai). To solve this problem,
|
||||
SentencePiece (introduced in `this paper <https://arxiv.org/pdf/1808.06226.pdf>`__) treats the input as a raw stream,
|
||||
includes the space in the set of characters to use, then uses BPE or unigram to construct the appropriate vocabulary.
|
||||
|
||||
That's why in the example we saw before using :class:`~transformers.XLNetTokenizer` (which uses SentencePiece), we had
|
||||
some '▁' characters, that represent spaces. Decoding a tokenized text is then super easy: we just have to concatenate
|
||||
all of them together and replace those '▁' by spaces.
|
||||
|
||||
All transformers models in the library that use SentencePiece use it with unigram. Examples of models using it are
|
||||
:doc:`ALBERT <model_doc/albert>`, :doc:`XLNet <model_doc/xlnet>` or the :doc:`Marian framework <model_doc/marian>`.
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
## Examples
|
||||
# Examples
|
||||
|
||||
Version 2.9 of 🤗 Transformers introduces a new [`Trainer`](https://github.com/huggingface/transformers/blob/master/src/transformers/trainer.py) class for PyTorch, and its equivalent [`TFTrainer`](https://github.com/huggingface/transformers/blob/master/src/transformers/trainer_tf.py) for TF 2.
|
||||
Running the examples requires PyTorch 1.3.1+ or TensorFlow 2.1+.
|
||||
@@ -13,7 +13,7 @@ Here is the list of all our examples:
|
||||
This is still a work-in-progress – in particular documentation is still sparse – so please **contribute improvements/pull requests.**
|
||||
|
||||
|
||||
# The Big Table of Tasks
|
||||
## The Big Table of Tasks
|
||||
|
||||
| Task | Example datasets | Trainer support | TFTrainer support | pytorch-lightning | Colab
|
||||
|---|---|:---:|:---:|:---:|:---:|
|
||||
|
||||
@@ -108,7 +108,10 @@ def main():
|
||||
level=logging.INFO,
|
||||
)
|
||||
logger.warning(
|
||||
"device: %s, n_gpu: %s, 16-bits training: %s", training_args.device, training_args.n_gpu, training_args.fp16,
|
||||
"device: %s, n_replicas: %s, 16-bits training: %s",
|
||||
training_args.device,
|
||||
training_args.n_replicas,
|
||||
training_args.fp16,
|
||||
)
|
||||
logger.info("Training/evaluation parameters %s", training_args)
|
||||
|
||||
|
||||
@@ -137,9 +137,9 @@ def main():
|
||||
level=logging.INFO,
|
||||
)
|
||||
logger.info(
|
||||
"n_gpu: %s, distributed training: %s, 16-bits training: %s",
|
||||
training_args.n_gpu,
|
||||
bool(training_args.n_gpu > 1),
|
||||
"n_replicas: %s, distributed training: %s, 16-bits training: %s",
|
||||
training_args.n_replicas,
|
||||
bool(training_args.n_replicas > 1),
|
||||
training_args.fp16,
|
||||
)
|
||||
logger.info("Training/evaluation parameters %s", training_args)
|
||||
|
||||
@@ -12,7 +12,7 @@ export OUTPUT_DIR=${CURRENT_DIR}/${OUTPUT_DIR_NAME}
|
||||
# Make output directory if it doesn't exist
|
||||
mkdir -p $OUTPUT_DIR
|
||||
|
||||
# Add parent directory to python path to access lightning_base.py and utils.py
|
||||
# Add parent directory to python path to access lightning_base.py and testing_utils.py
|
||||
export PYTHONPATH="../":"${PYTHONPATH}"
|
||||
python finetune.py \
|
||||
--data_dir=cnn_tiny/ \
|
||||
|
||||
@@ -12,6 +12,7 @@ import torch
|
||||
from torch.utils.data import DataLoader
|
||||
|
||||
from transformers import AutoTokenizer
|
||||
from transformers.testing_utils import require_multigpu
|
||||
|
||||
from .distillation import distill_main, evaluate_checkpoint
|
||||
from .finetune import main
|
||||
@@ -107,7 +108,7 @@ class TestSummarizationDistiller(unittest.TestCase):
|
||||
logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks
|
||||
return cls
|
||||
|
||||
@unittest.skipUnless(torch.cuda.device_count() > 1, "skipping multiGPU test")
|
||||
@require_multigpu
|
||||
def test_multigpu(self):
|
||||
updates = dict(no_teacher=True, freeze_encoder=True, gpus=2, sortish_sampler=False,)
|
||||
self._test_distiller_cli(updates)
|
||||
|
||||
@@ -131,9 +131,9 @@ def main():
|
||||
level=logging.INFO,
|
||||
)
|
||||
logger.info(
|
||||
"n_gpu: %s, distributed training: %s, 16-bits training: %s",
|
||||
training_args.n_gpu,
|
||||
bool(training_args.n_gpu > 1),
|
||||
"n_replicas: %s, distributed training: %s, 16-bits training: %s",
|
||||
training_args.n_replicas,
|
||||
bool(training_args.n_replicas > 1),
|
||||
training_args.fp16,
|
||||
)
|
||||
logger.info("Training/evaluation parameters %s", training_args)
|
||||
|
||||
@@ -109,9 +109,9 @@ def main():
|
||||
level=logging.INFO,
|
||||
)
|
||||
logger.info(
|
||||
"n_gpu: %s, distributed training: %s, 16-bits training: %s",
|
||||
training_args.n_gpu,
|
||||
bool(training_args.n_gpu > 1),
|
||||
"n_replicas: %s, distributed training: %s, 16-bits training: %s",
|
||||
training_args.n_replicas,
|
||||
bool(training_args.n_replicas > 1),
|
||||
training_args.fp16,
|
||||
)
|
||||
logger.info("Training/evaluation parameters %s", training_args)
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
language: setswana
|
||||
---
|
||||
|
||||
# TswanaBert
|
||||
Pretrained model on the Tswana language using a masked language modeling (MLM) objective.
|
||||
|
||||
## Model Description.
|
||||
TswanaBERT is a transformer model pre-trained on a corpus of Setswana in a self-supervised fashion by masking part of the input words and training to predict the masks by using byte-level tokens.
|
||||
|
||||
## Intended uses & limitations
|
||||
The model can be used for either masked language modeling or next word prediction. It can also be fine-tuned on a specific down-stream NLP application.
|
||||
|
||||
#### How to use
|
||||
|
||||
```python
|
||||
>>> from transformers import pipeline
|
||||
>>> from transformers import AutoTokenizer, AutoModelWithLMHead
|
||||
|
||||
>>> tokenizer = AutoTokenizer.from_pretrained("MoseliMotsoehli/TswanaBert")
|
||||
>>> model = AutoModelWithLMHead.from_pretrained("MoseliMotsoehli/TswanaBert")
|
||||
>>> unmasker = pipeline('fill-mask', model=model, tokenizer=tokenizer)
|
||||
>>> unmasker("Ntshopotse <mask> e godile.")
|
||||
|
||||
[{'score': 0.32749542593955994,
|
||||
'sequence': '<s>Ntshopotse setse e godile.</s>',
|
||||
'token': 538,
|
||||
'token_str': 'Ġsetse'},
|
||||
{'score': 0.060260992497205734,
|
||||
'sequence': '<s>Ntshopotse le e godile.</s>',
|
||||
'token': 270,
|
||||
'token_str': 'Ġle'},
|
||||
{'score': 0.058460816740989685,
|
||||
'sequence': '<s>Ntshopotse bone e godile.</s>',
|
||||
'token': 364,
|
||||
'token_str': 'Ġbone'},
|
||||
{'score': 0.05694682151079178,
|
||||
'sequence': '<s>Ntshopotse ga e godile.</s>',
|
||||
'token': 298,
|
||||
'token_str': 'Ġga'},
|
||||
{'score': 0.0565204992890358,
|
||||
'sequence': '<s>Ntshopotse, e godile.</s>',
|
||||
'token': 16,
|
||||
'token_str': ','}]
|
||||
```
|
||||
|
||||
#### Limitations and bias
|
||||
The model is trained on a relatively small collection of setwana, mostly from news articles and creative writtings, and so is not representative enough of the language as yet.
|
||||
|
||||
## Training data
|
||||
|
||||
1. The largest portion of this dataset (10k) sentences of text, comes from the [Leipzig Corpora Collection](https://wortschatz.uni-leipzig.de/en/download)
|
||||
|
||||
2. I Then added SABC news headlines collected by Marivate Vukosi, & Sefara Tshephisho, (2020) that is generously made available on [zenoodo](http://doi.org/10.5281/zenodo.3668495 ). This added 185 tswana sentences to my corpus.
|
||||
|
||||
3. I went on to add 300 more sentences by scrapping following news sites and blogs that mosty originate in Botswana. I actively continue to expand the dataset.
|
||||
|
||||
* http://setswana.blogspot.com/
|
||||
* https://omniglot.com/writing/tswana.php
|
||||
* http://www.dailynews.gov.bw/
|
||||
* http://www.mmegi.bw/index.php
|
||||
* https://tsena.co.bw
|
||||
* http://www.botswana.co.za/Cultural_Issues-travel/botswana-country-guide-en-route.html
|
||||
* https://www.poemhunter.com/poem/2013-setswana/
|
||||
https://www.poemhunter.com/poem/ngwana-wa-mosetsana/
|
||||
|
||||
|
||||
### BibTeX entry and citation info
|
||||
|
||||
```bibtex
|
||||
@inproceedings{author = {Moseli Motsoehli},
|
||||
year={2020}
|
||||
}
|
||||
```
|
||||
@@ -18,7 +18,7 @@ This GPT-2 (774M) model is capable of generating abstracts given paper titles. I
|
||||
|
||||
#### How to use
|
||||
|
||||
To generate paper abstracts, use the provided `generate.py` [here](https://gist.github.com/chrisliu298/ccb8144888eace069da64ad3e6472d64). This is very similar to the HuggingFace's `run_generation.py` [here](https://github.com/huggingface/transformers/tree/master/examples/text-generation). You can simply replace the text with with your own model path (line 89) and change the input string to your paper title (line 127).
|
||||
To generate paper abstracts, use the provided `generate.py` [here](https://gist.github.com/chrisliu298/ccb8144888eace069da64ad3e6472d64). This is very similar to the HuggingFace's `run_generation.py` [here](https://github.com/huggingface/transformers/tree/master/examples/text-generation). You can simply replace the text with with your own model path (line 89) and change the input string to your paper title (line 127). If you want to use your own script, make sure to prepend `<|startoftext|> ` at the front and append ` <|sep|>` at the end of the paper title.
|
||||
|
||||
## Training data
|
||||
I selected a subset of the [arXiv Archive](https://github.com/staeiou/arxiv_archive) dataset (Geiger, 2019) as the training and evaluation data to fine-tune GPT-2. The original arXiv Archive dataset contains a full archive of metadata about papers on arxiv.org, from the start of the site in 1993 to the end of 2019. Our subset includes all the paper titles (query) and abstracts (context) under the Artificial Intelligence (cs.AI), Machine Learning (cs.LG), Computation and Language (cs.CL), and Computer Vision and Pattern Recognition (cs.CV) categories. I provide the information of the sub-dataset and the distribution of the training and evaluation dataset as follows.
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
---
|
||||
language: english
|
||||
---
|
||||
|
||||
# Electra base ⚡ + SQuAD v1 ❓
|
||||
|
||||
[Electra-base-discriminator](https://huggingface.co/google/electra-base-discriminator) fine-tuned on [SQUAD v1.1 dataset](https://rajpurkar.github.io/SQuAD-explorer/explore/1.1/dev/) for **Q&A** downstream task.
|
||||
|
||||
## Details of the downstream task (Q&A) - Model 🧠
|
||||
|
||||
**ELECTRA** is a new method for self-supervised language representation learning. It can be used to pre-train transformer networks using relatively little compute. ELECTRA models are trained to distinguish "real" input tokens vs "fake" input tokens generated by another neural network, similar to the discriminator of a [GAN](https://arxiv.org/pdf/1406.2661.pdf). At small scale, ELECTRA achieves strong results even when trained on a single GPU. At large scale, ELECTRA achieves state-of-the-art results on the [SQuAD 2.0](https://rajpurkar.github.io/SQuAD-explorer/) dataset.
|
||||
|
||||
|
||||
## Details of the downstream task (Q&A) - Dataset 📚
|
||||
|
||||
**S**tanford **Q**uestion **A**nswering **D**ataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by crowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span, from the corresponding reading passage, or the question might be unanswerable.
|
||||
SQuAD v1.1 contains **100,000+** question-answer pairs on **500+** articles.
|
||||
|
||||
## Model training 🏋️
|
||||
|
||||
The model was trained on a Tesla P100 GPU and 25GB of RAM with the following command:
|
||||
|
||||
```bash
|
||||
python transformers/examples/question-answering/run_squad.py \
|
||||
--model_type electra \
|
||||
--model_name_or_path 'google/electra-base-discriminator' \
|
||||
--do_eval \
|
||||
--do_train \
|
||||
--do_lower_case \
|
||||
--train_file '/content/dataset/train-v1.1.json' \
|
||||
--predict_file '/content/dataset/dev-v1.1.json' \
|
||||
--per_gpu_train_batch_size 16 \
|
||||
--learning_rate 3e-5 \
|
||||
--num_train_epochs 10 \
|
||||
--max_seq_length 384 \
|
||||
--doc_stride 128 \
|
||||
--output_dir '/content/output' \
|
||||
--overwrite_output_dir \
|
||||
--save_steps 1000
|
||||
```
|
||||
|
||||
## Test set Results 🧾
|
||||
|
||||
| Metric | # Value |
|
||||
| ------ | --------- |
|
||||
| **EM** | **83.03** |
|
||||
| **F1** | **90.77** |
|
||||
| **Size**| **+ 400 MB** |
|
||||
|
||||
Very good metrics for such a "small" model!
|
||||
|
||||
```json
|
||||
{
|
||||
'exact': 83.03689687795648,
|
||||
'f1': 90.77486052446231,
|
||||
'total': 10570,
|
||||
'HasAns_exact': 83.03689687795648,
|
||||
'HasAns_f1': 90.77486052446231,
|
||||
'HasAns_total': 10570,
|
||||
'best_exact': 83.03689687795648,
|
||||
'best_exact_thresh': 0.0,
|
||||
'best_f1': 90.77486052446231,
|
||||
'best_f1_thresh': 0.0
|
||||
}
|
||||
```
|
||||
|
||||
### Model in action 🚀
|
||||
|
||||
Fast usage with **pipelines**:
|
||||
|
||||
```python
|
||||
from transformers import pipeline
|
||||
|
||||
QnA_pipeline = pipeline('question-answering', model='mrm8488/electra-base-finetuned-squadv1')
|
||||
|
||||
QnA_pipeline({
|
||||
'context': 'A new strain of flu that has the potential to become a pandemic has been identified in China by scientists.',
|
||||
'question': 'What has been discovered by scientists from China ?'
|
||||
})
|
||||
# Output:
|
||||
{'answer': 'A new strain of flu', 'end': 19, 'score': 0.9995211430099182, 'start': 0}
|
||||
```
|
||||
|
||||
> Created by [Manuel Romero/@mrm8488](https://twitter.com/mrm8488) | [LinkedIn](https://www.linkedin.com/in/manuel-romero-cs/)
|
||||
> Made with <span style="color: #e25555;">♥</span> in Spain
|
||||
@@ -0,0 +1,86 @@
|
||||
---
|
||||
language: english
|
||||
---
|
||||
|
||||
# Electra small ⚡ + SQuAD v2 ❓
|
||||
|
||||
[Electra-small-discriminator](https://huggingface.co/google/electra-small-discriminator) fine-tuned on [SQUAD v2.0 dataset](https://rajpurkar.github.io/SQuAD-explorer/explore/v2.0/dev/) for **Q&A** downstream task.
|
||||
|
||||
## Details of the downstream task (Q&A) - Model 🧠
|
||||
|
||||
**ELECTRA** is a new method for self-supervised language representation learning. It can be used to pre-train transformer networks using relatively little compute. ELECTRA models are trained to distinguish "real" input tokens vs "fake" input tokens generated by another neural network, similar to the discriminator of a [GAN](https://arxiv.org/pdf/1406.2661.pdf). At small scale, ELECTRA achieves strong results even when trained on a single GPU. At large scale, ELECTRA achieves state-of-the-art results on the [SQuAD 2.0](https://rajpurkar.github.io/SQuAD-explorer/) dataset.
|
||||
|
||||
|
||||
## Details of the downstream task (Q&A) - Dataset 📚
|
||||
|
||||
**SQuAD2.0** combines the 100,000 questions in SQuAD1.1 with over 50,000 unanswerable questions written adversarially by crowdworkers to look similar to answerable ones. To do well on SQuAD2.0, systems must not only answer questions when possible, but also determine when no answer is supported by the paragraph and abstain from answering.
|
||||
|
||||
## Model training 🏋️
|
||||
|
||||
The model was trained on a Tesla P100 GPU and 25GB of RAM with the following command:
|
||||
|
||||
```bash
|
||||
python transformers/examples/question-answering/run_squad.py \
|
||||
--model_type electra \
|
||||
--model_name_or_path 'google/electra-small-discriminator' \
|
||||
--do_eval \
|
||||
--do_train \
|
||||
--do_lower_case \
|
||||
--train_file '/content/dataset/train-v2.0.json' \
|
||||
--predict_file '/content/dataset/dev-v2.0.json' \
|
||||
--per_gpu_train_batch_size 16 \
|
||||
--learning_rate 3e-5 \
|
||||
--num_train_epochs 10 \
|
||||
--max_seq_length 384 \
|
||||
--doc_stride 128 \
|
||||
--output_dir '/content/output' \
|
||||
--overwrite_output_dir \
|
||||
--save_steps 1000 \
|
||||
--version_2_with_negative
|
||||
```
|
||||
|
||||
## Test set Results 🧾
|
||||
|
||||
| Metric | # Value |
|
||||
| ------ | --------- |
|
||||
| **EM** | **69.71** |
|
||||
| **F1** | **73.44** |
|
||||
| **Size**| **50 MB** |
|
||||
|
||||
|
||||
```json
|
||||
{
|
||||
'exact': 69.71279373368147,
|
||||
'f1': 73.4439546123672,
|
||||
'total': 11873,
|
||||
'HasAns_exact': 69.92240215924427,
|
||||
'HasAns_f1': 77.39542393937836,
|
||||
'HasAns_total': 5928,
|
||||
'NoAns_exact': 69.50378469301934,
|
||||
'NoAns_f1': 69.50378469301934,
|
||||
'NoAns_total': 5945,
|
||||
'best_exact': 69.71279373368147,
|
||||
'best_exact_thresh': 0.0,
|
||||
'best_f1': 73.44395461236732,
|
||||
'best_f1_thresh': 0.0
|
||||
}
|
||||
```
|
||||
|
||||
### Model in action 🚀
|
||||
|
||||
Fast usage with **pipelines**:
|
||||
|
||||
```python
|
||||
from transformers import pipeline
|
||||
QnA_pipeline = pipeline('question-answering', model='mrm8488/electra-base-finetuned-squadv2')
|
||||
QnA_pipeline({
|
||||
'context': 'A new strain of flu that has the potential to become a pandemic has been identified in China by scientists.',
|
||||
'question': 'What has been discovered by scientists from China ?'
|
||||
})
|
||||
# Output:
|
||||
{'answer': 'A new strain of flu', 'end': 19, 'score': 0.8650811568752914, 'start': 0}
|
||||
```
|
||||
|
||||
> Created by [Manuel Romero/@mrm8488](https://twitter.com/mrm8488) | [LinkedIn](https://www.linkedin.com/in/manuel-romero-cs/)
|
||||
|
||||
> Made with <span style="color: #e25555;">♥</span> in Spain
|
||||
@@ -0,0 +1,102 @@
|
||||
---
|
||||
language: spanish
|
||||
thumbnail: https://imgur.com/uxAvBfh
|
||||
---
|
||||
|
||||
# Electricidad small + Spanish SQuAD v1 ⚡❓
|
||||
|
||||
[Electricidad-small-discriminator](https://huggingface.co/mrm8488/electricidad-small-discriminator) fine-tuned on [Spanish SQUAD v1.1 dataset](https://github.com/ccasimiro88/TranslateAlignRetrieve/tree/master/SQuAD-es-v1.1) for **Q&A** downstream task.
|
||||
|
||||
## Details of the downstream task (Q&A) - Dataset 📚
|
||||
|
||||
[SQuAD-es-v1.1](https://github.com/ccasimiro88/TranslateAlignRetrieve/tree/master/SQuAD-es-v1.1)
|
||||
|
||||
| Dataset split | # Samples |
|
||||
| ------------- | --------- |
|
||||
| Train | 130 K |
|
||||
| Test | 11 K |
|
||||
|
||||
## Model training 🏋️
|
||||
|
||||
The model was trained on a Tesla P100 GPU and 25GB of RAM with the following command:
|
||||
|
||||
```bash
|
||||
python /content/transformers/examples/question-answering/run_squad.py \
|
||||
--model_type electra \
|
||||
--model_name_or_path 'mrm8488/electricidad-small-discriminator' \
|
||||
--do_eval \
|
||||
--do_train \
|
||||
--do_lower_case \
|
||||
--train_file '/content/dataset/train-v1.1-es.json' \
|
||||
--predict_file '/content/dataset/dev-v1.1-es.json' \
|
||||
--per_gpu_train_batch_size 16 \
|
||||
--learning_rate 3e-5 \
|
||||
--num_train_epochs 10 \
|
||||
--max_seq_length 384 \
|
||||
--doc_stride 128 \
|
||||
--output_dir '/content/electricidad-small-finetuned-squadv1-es' \
|
||||
--overwrite_output_dir \
|
||||
--save_steps 1000
|
||||
```
|
||||
|
||||
## Test set Results 🧾
|
||||
|
||||
| Metric | # Value |
|
||||
| ------ | --------- |
|
||||
| **EM** | **46.82** |
|
||||
| **F1** | **64.79** |
|
||||
|
||||
```json
|
||||
{
|
||||
'exact': 46.82119205298013,
|
||||
'f1': 64.79435260021918,
|
||||
'total': 10570,
|
||||
'HasAns_exact': 46.82119205298013,
|
||||
HasAns_f1': 64.79435260021918,
|
||||
'HasAns_total': 10570,
|
||||
'best_exact': 46.82119205298013,
|
||||
'best_exact_thresh': 0.0,
|
||||
'best_f1': 64.79435260021918,
|
||||
'best_f1_thresh': 0.0
|
||||
}
|
||||
```
|
||||
|
||||
### Model in action 🚀
|
||||
|
||||
Fast usage with **pipelines**:
|
||||
|
||||
```python
|
||||
from transformers import pipeline
|
||||
|
||||
qa_pipeline = pipeline(
|
||||
"question-answering",
|
||||
model="mrm8488/electricidad-small-finetuned-squadv1-es",
|
||||
tokenizer="mrm8488/electricidad-small-finetuned-squadv1-es"
|
||||
)
|
||||
|
||||
context = "Manuel ha creado una versión del modelo Electra small en español que alcanza una puntuación F1 de 65 en el dataset SQUAD-es y sólo pesa 50 MB"
|
||||
|
||||
q1 = "Cuál es su marcador F1?"
|
||||
q2 = "¿Cuál es el tamaño del modelo?"
|
||||
q3 = "¿Quién lo ha creado?"
|
||||
q4 = "¿Que es lo que ha hecho Manuel?"
|
||||
|
||||
|
||||
questions = [q1, q2, q3, q4]
|
||||
|
||||
for question in questions:
|
||||
result = qa_pipeline({
|
||||
'context': context,
|
||||
'question': question})
|
||||
print(result)
|
||||
|
||||
# Output:
|
||||
{'score': 0.14836778166355025, 'start': 98, 'end': 100, 'answer': '65'}
|
||||
{'score': 0.32219420810758237, 'start': 136, 'end': 140, 'answer': '50 MB'}
|
||||
{'score': 0.9672326951118713, 'start': 0, 'end': 6, 'answer': 'Manuel'}
|
||||
{'score': 0.23552458113848118, 'start': 10, 'end': 53, 'answer': 'creado una versión del modelo Electra small'}
|
||||
```
|
||||
|
||||
> Created by [Manuel Romero/@mrm8488](https://twitter.com/mrm8488) | [LinkedIn](https://www.linkedin.com/in/manuel-romero-cs/)
|
||||
|
||||
> Made with <span style="color: #e25555;">♥</span> in Spain
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
license: mit
|
||||
widget:
|
||||
- text: "I like you. </s></s> I love you."
|
||||
---
|
||||
|
||||
|
||||
## roberta-large-mnli
|
||||
|
||||
Trained by Facebook, [original source](https://github.com/pytorch/fairseq/tree/master/examples/roberta)
|
||||
|
||||
```bibtex
|
||||
@article{liu2019roberta,
|
||||
title = {RoBERTa: A Robustly Optimized BERT Pretraining Approach},
|
||||
author = {Yinhan Liu and Myle Ott and Naman Goyal and Jingfei Du and
|
||||
Mandar Joshi and Danqi Chen and Omer Levy and Mike Lewis and
|
||||
Luke Zettlemoyer and Veselin Stoyanov},
|
||||
journal={arXiv preprint arXiv:1907.11692},
|
||||
year = {2019},
|
||||
}
|
||||
```
|
||||
|
||||
@@ -39,3 +39,4 @@ Pull Request so it can be included under the Community notebooks.
|
||||
|[Fine-tune BERT for Multi-label Classification](https://github.com/abhimishra91/transformers-tutorials/blob/master/transformers_multi_label_classification.ipynb)|How to fine-tune BERT for multi-label classification using PyTorch|[Abhishek Kumar Mishra](https://github.com/abhimishra91) |[](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_multi_label_classification.ipynb)|
|
||||
|[Fine-tune T5 for Summarization](https://github.com/abhimishra91/transformers-tutorials/blob/master/transformers_summarization_wandb.ipynb)|How to fine-tune T5 for summarization in PyTorch and track experiments with WandB|[Abhishek Kumar Mishra](https://github.com/abhimishra91) |[](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_summarization_wandb.ipynb)|
|
||||
|[Speed up Fine-Tuning in Transformers with Dynamic Padding / Bucketing](https://github.com/ELS-RD/transformers-notebook/blob/master/Divide_Hugging_Face_Transformers_training_time_by_2_or_more.ipynb)|How to speed up fine-tuning by a factor of 2 using dynamic padding / bucketing|[Michael Benesty](https://github.com/pommedeterresautee) |[](https://colab.research.google.com/drive/1CBfRU1zbfu7-ijiOqAAQUA-RJaxfcJoO?usp=sharing)|
|
||||
|[Pretrain Reformer for Masked Language Modeling](https://github.com/patrickvonplaten/notebooks/blob/master/Reformer_For_Masked_LM.ipynb)| How to train a Reformer model with bi-directional self-attention layers | [Patrick von Platen](https://github.com/patrickvonplaten) | [](https://colab.research.google.com/drive/1tzzh0i8PgDQGV3SMFUGxM7_gGae3K-uW?usp=sharing)|
|
||||
|
||||
@@ -71,11 +71,15 @@ extras["sklearn"] = ["scikit-learn"]
|
||||
# keras2onnx and onnxconverter-common version is specific through a commit until 1.7.0 lands on pypi
|
||||
extras["tf"] = [
|
||||
"tensorflow",
|
||||
# "onnxconverter-common",
|
||||
# "keras2onnx"
|
||||
"onnxconverter-common @ git+git://github.com/microsoft/onnxconverter-common.git@f64ca15989b6dc95a1f3507ff6e4c395ba12dff5#egg=onnxconverter-common",
|
||||
"keras2onnx @ git+git://github.com/onnx/keras-onnx.git@cbdc75cb950b16db7f0a67be96a278f8d2953b48#egg=keras2onnx"
|
||||
]
|
||||
extras["tf-cpu"] = [
|
||||
"tensorflow-cpu",
|
||||
# "onnxconverter-common",
|
||||
# "keras2onnx"
|
||||
"onnxconverter-common @ git+git://github.com/microsoft/onnxconverter-common.git@f64ca15989b6dc95a1f3507ff6e4c395ba12dff5#egg=onnxconverter-common",
|
||||
"keras2onnx @ git+git://github.com/onnx/keras-onnx.git@cbdc75cb950b16db7f0a67be96a278f8d2953b48#egg=keras2onnx"
|
||||
]
|
||||
@@ -89,6 +93,7 @@ extras["testing"] = ["pytest", "pytest-xdist", "timeout-decorator", "psutil"]
|
||||
extras["docs"] = ["recommonmark", "sphinx", "sphinx-markdown-tables", "sphinx-rtd-theme==0.4.3", "sphinx-copybutton"]
|
||||
extras["quality"] = [
|
||||
"black",
|
||||
# "isort",
|
||||
"isort @ git+git://github.com/timothycrosley/isort.git@e63ae06ec7d70b06df9e528357650281a3d3ec22#egg=isort",
|
||||
"flake8",
|
||||
]
|
||||
@@ -96,7 +101,7 @@ extras["dev"] = extras["testing"] + extras["quality"] + ["mecab-python3<1", "sci
|
||||
|
||||
setup(
|
||||
name="transformers",
|
||||
version="3.0.0",
|
||||
version="3.0.1",
|
||||
author="Thomas Wolf, Lysandre Debut, Victor Sanh, Julien Chaumond, Sam Shleifer, Patrick von Platen, Google AI Language Team Authors, Open AI team Authors, Facebook AI Authors, Carnegie Mellon University Authors",
|
||||
author_email="thomas@huggingface.co",
|
||||
description="State-of-the-art Natural Language Processing for TensorFlow 2.0 and PyTorch",
|
||||
@@ -123,7 +128,7 @@ setup(
|
||||
# for OpenAI GPT
|
||||
"regex != 2019.12.17",
|
||||
# for XLNet
|
||||
"sentencepiece",
|
||||
"sentencepiece != 0.1.92",
|
||||
# for XLM
|
||||
"sacremoses",
|
||||
],
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# There's no way to ignore "F401 '...' imported but unused" warnings in this
|
||||
# module, but to preserve other warnings. So, don't check this module at all.
|
||||
|
||||
__version__ = "3.0.0"
|
||||
__version__ = "3.0.1"
|
||||
|
||||
# Work around to update TensorFlow's absl.logging threshold which alters the
|
||||
# default Python logging output behavior when present.
|
||||
@@ -155,7 +155,7 @@ from .tokenization_xlm_roberta import XLMRobertaTokenizer
|
||||
from .tokenization_xlnet import SPIECE_UNDERLINE, XLNetTokenizer
|
||||
|
||||
# Trainer
|
||||
from .trainer_utils import EvalPrediction
|
||||
from .trainer_utils import EvalPrediction, set_seed
|
||||
from .training_args import TrainingArguments
|
||||
from .training_args_tf import TFTrainingArguments
|
||||
|
||||
@@ -366,7 +366,9 @@ if is_torch_available():
|
||||
ReformerAttention,
|
||||
ReformerLayer,
|
||||
ReformerModel,
|
||||
ReformerForMaskedLM,
|
||||
ReformerModelWithLMHead,
|
||||
ReformerForQuestionAnswering,
|
||||
REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
|
||||
)
|
||||
|
||||
@@ -397,7 +399,7 @@ if is_torch_available():
|
||||
)
|
||||
|
||||
# Trainer
|
||||
from .trainer import Trainer, set_seed, torch_distributed_zero_first
|
||||
from .trainer import Trainer, torch_distributed_zero_first
|
||||
from .data.data_collator import default_data_collator, DataCollator, DataCollatorForLanguageModeling
|
||||
from .data.datasets import GlueDataset, TextDataset, LineByLineTextDataset, GlueDataTrainingArguments
|
||||
|
||||
|
||||
@@ -43,7 +43,8 @@ def default_data_collator(features: List[InputDataClass]) -> Dict[str, torch.Ten
|
||||
# Ensure that tensor is created with the correct type
|
||||
# (it should be automatically the case, but let's make sure of it.)
|
||||
if "label" in first and first["label"] is not None:
|
||||
dtype = torch.long if type(first["label"]) is int else torch.float
|
||||
label = first["label"].item() if isinstance(first["label"], torch.Tensor) else first["label"]
|
||||
dtype = torch.long if isinstance(label, int) else torch.float
|
||||
batch["labels"] = torch.tensor([f["label"] for f in features], dtype=dtype)
|
||||
elif "label_ids" in first and first["label_ids"] is not None:
|
||||
if isinstance(first["label_ids"], torch.Tensor):
|
||||
|
||||
@@ -347,6 +347,10 @@ class TFGenerationMixin:
|
||||
encoder_outputs = None
|
||||
cur_len = shape_list(input_ids)[-1]
|
||||
|
||||
assert (
|
||||
cur_len < max_length
|
||||
), f"The context has {cur_len} number of tokens, but `max_length` is only {max_length}. Please make sure that `max_length` is bigger than the number of tokens, by setting either `generate(max_length=...,...)` or `config.max_length = ...`"
|
||||
|
||||
if num_beams > 1:
|
||||
output = self._generate_beam_search(
|
||||
input_ids,
|
||||
|
||||
@@ -428,6 +428,10 @@ class GenerationMixin:
|
||||
encoder_outputs = None
|
||||
cur_len = input_ids.shape[-1]
|
||||
|
||||
assert (
|
||||
cur_len < max_length
|
||||
), f"The context has {cur_len} number of tokens, but `max_length` is only {max_length}. Please make sure that `max_length` is bigger than the number of tokens, by setting either `generate(max_length=...,...)` or `config.max_length = ...`"
|
||||
|
||||
if num_beams > 1:
|
||||
output = self._generate_beam_search(
|
||||
input_ids,
|
||||
|
||||
@@ -122,7 +122,12 @@ from .modeling_mobilebert import (
|
||||
MobileBertModel,
|
||||
)
|
||||
from .modeling_openai import OpenAIGPTLMHeadModel, OpenAIGPTModel
|
||||
from .modeling_reformer import ReformerModel, ReformerModelWithLMHead
|
||||
from .modeling_reformer import (
|
||||
ReformerForMaskedLM,
|
||||
ReformerForQuestionAnswering,
|
||||
ReformerModel,
|
||||
ReformerModelWithLMHead,
|
||||
)
|
||||
from .modeling_retribert import RetriBertModel
|
||||
from .modeling_roberta import (
|
||||
RobertaForMaskedLM,
|
||||
@@ -266,6 +271,7 @@ MODEL_FOR_MASKED_LM_MAPPING = OrderedDict(
|
||||
(FlaubertConfig, FlaubertWithLMHeadModel),
|
||||
(XLMConfig, XLMWithLMHeadModel),
|
||||
(ElectraConfig, ElectraForMaskedLM),
|
||||
(ReformerConfig, ReformerForMaskedLM),
|
||||
]
|
||||
)
|
||||
|
||||
@@ -310,6 +316,7 @@ MODEL_FOR_QUESTION_ANSWERING_MAPPING = OrderedDict(
|
||||
(MobileBertConfig, MobileBertForQuestionAnswering),
|
||||
(XLMConfig, XLMForQuestionAnsweringSimple),
|
||||
(ElectraConfig, ElectraForQuestionAnswering),
|
||||
(ReformerConfig, ReformerForQuestionAnswering),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@@ -133,7 +133,7 @@ class ElectraDiscriminatorPredictions(nn.Module):
|
||||
self.dense_prediction = nn.Linear(config.hidden_size, 1)
|
||||
self.config = config
|
||||
|
||||
def forward(self, discriminator_hidden_states, attention_mask):
|
||||
def forward(self, discriminator_hidden_states):
|
||||
hidden_states = self.dense(discriminator_hidden_states)
|
||||
hidden_states = get_activation(self.config.hidden_act)(hidden_states)
|
||||
logits = self.dense_prediction(hidden_states).squeeze()
|
||||
@@ -518,7 +518,7 @@ class ElectraForPreTraining(ElectraPreTrainedModel):
|
||||
)
|
||||
discriminator_sequence_output = discriminator_hidden_states[0]
|
||||
|
||||
logits = self.discriminator_predictions(discriminator_sequence_output, attention_mask)
|
||||
logits = self.discriminator_predictions(discriminator_sequence_output)
|
||||
|
||||
output = (logits,)
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -373,7 +373,7 @@ class LSHSelfAttention(nn.Module, EfficientAttentionMixin):
|
||||
# use cached buckets for backprop only
|
||||
if buckets is None:
|
||||
# hash query key vectors into buckets
|
||||
buckets = self._hash_vectors(query_key_vectors, num_hashes)
|
||||
buckets = self._hash_vectors(query_key_vectors, num_hashes, attention_mask)
|
||||
|
||||
assert (
|
||||
int(buckets.shape[-1]) == num_hashes * sequence_length
|
||||
@@ -460,7 +460,7 @@ class LSHSelfAttention(nn.Module, EfficientAttentionMixin):
|
||||
|
||||
return LSHSelfAttentionOutput(hidden_states=out_vectors, attention_probs=attention_probs, buckets=buckets)
|
||||
|
||||
def _hash_vectors(self, vectors, num_hashes):
|
||||
def _hash_vectors(self, vectors, num_hashes, attention_mask):
|
||||
batch_size = vectors.shape[0]
|
||||
|
||||
# See https://arxiv.org/pdf/1509.02897.pdf
|
||||
@@ -487,14 +487,20 @@ class LSHSelfAttention(nn.Module, EfficientAttentionMixin):
|
||||
|
||||
if self.hash_seed is not None:
|
||||
# for determinism
|
||||
torch.manual_seed(self.hash_seed)
|
||||
rotations_shape = (vectors.shape[-1], num_hashes, rotation_size // 2)
|
||||
# torch.manual_seed(self.hash_seed)
|
||||
np.random.seed(self.hash_seed)
|
||||
random_rotations = torch.tensor(
|
||||
np.random.normal(size=rotations_shape), dtype=vectors.dtype, device=vectors.device,
|
||||
)
|
||||
rotated_vectors = torch.einsum("bmtd,dhr->bmhtr", vectors, random_rotations)
|
||||
else:
|
||||
rotations_shape = (self.num_attention_heads, vectors.shape[-1], num_hashes, rotation_size // 2)
|
||||
# create a random self.attention_head_size x num_hashes x num_buckets/2
|
||||
random_rotations = torch.randn(rotations_shape, device=vectors.device, dtype=vectors.dtype)
|
||||
|
||||
rotations_shape = (self.num_attention_heads, vectors.shape[-1], num_hashes, rotation_size // 2)
|
||||
# create a random self.attention_head_size x num_hashes x num_buckets/2
|
||||
random_rotations = torch.randn(rotations_shape, device=vectors.device, dtype=vectors.dtype)
|
||||
|
||||
# Output dim: Batch_Size x Num_Attn_Heads x Num_Hashes x Seq_Len x Num_Buckets/2
|
||||
rotated_vectors = torch.einsum("bmtd,mdhr->bmhtr", vectors, random_rotations)
|
||||
# Output dim: Batch_Size x Num_Attn_Heads x Num_Hashes x Seq_Len x Num_Buckets/2
|
||||
rotated_vectors = torch.einsum("bmtd,mdhr->bmhtr", vectors, random_rotations)
|
||||
|
||||
if isinstance(self.num_buckets, int) or len(self.num_buckets) == 1:
|
||||
rotated_vectors = torch.cat([rotated_vectors, -rotated_vectors], dim=-1)
|
||||
@@ -514,6 +520,15 @@ class LSHSelfAttention(nn.Module, EfficientAttentionMixin):
|
||||
|
||||
cur_product = cur_product * bucket_factor
|
||||
|
||||
if attention_mask is not None:
|
||||
# add an extra bucket for padding tokens only
|
||||
num_buckets = num_buckets + 1
|
||||
# assign padding tokens extra bucket
|
||||
buckets_mask = attention_mask.to(torch.uint8)[:, None, None, :].expand(buckets.shape)
|
||||
buckets = torch.where(
|
||||
buckets_mask, buckets, torch.tensor(num_buckets - 1, dtype=torch.long, device=buckets.device)
|
||||
)
|
||||
|
||||
# buckets is now (Batch_size x Num_Attn_Heads x Num_Hashes x Seq_Len).
|
||||
# Next we add offsets so that bucket numbers from different hashing rounds don't overlap.
|
||||
offsets = torch.arange(num_hashes, device=vectors.device)
|
||||
@@ -614,7 +629,9 @@ class LSHSelfAttention(nn.Module, EfficientAttentionMixin):
|
||||
self_mask_value = self.self_mask_value_float32
|
||||
mask_value = self.mask_value_float32
|
||||
|
||||
mask = self._compute_attn_mask(query_bucket_idx, key_value_bucket_idx, attention_mask, sequence_length)
|
||||
mask = self._compute_attn_mask(
|
||||
query_bucket_idx, key_value_bucket_idx, attention_mask, query_key_dots.shape, sequence_length
|
||||
)
|
||||
|
||||
if mask is not None:
|
||||
query_key_dots = torch.where(mask, query_key_dots, mask_value)
|
||||
@@ -669,7 +686,7 @@ class LSHSelfAttention(nn.Module, EfficientAttentionMixin):
|
||||
|
||||
return out_vectors, logits, attention_probs
|
||||
|
||||
def _compute_attn_mask(self, query_indices, key_indices, attention_mask, sequence_length):
|
||||
def _compute_attn_mask(self, query_indices, key_indices, attention_mask, query_key_dot_shape, sequence_length):
|
||||
mask = None
|
||||
|
||||
# Causal mask
|
||||
@@ -680,32 +697,20 @@ class LSHSelfAttention(nn.Module, EfficientAttentionMixin):
|
||||
# IMPORTANT: official trax code does not use a mask for LSH Atttention. Not sure why.
|
||||
if attention_mask is not None:
|
||||
# if chunked attention, the attention mask has to correspond to LSH order
|
||||
attention_mask = attention_mask.to(torch.uint8)[:, None, :]
|
||||
if sequence_length > self.chunk_length:
|
||||
attention_mask = attention_mask.to(torch.uint8)[:, None, None, :]
|
||||
# expand attn_mask to fit with key_value_bucket_idx shape
|
||||
attention_mask = attention_mask[:, None, :]
|
||||
attention_mask = attention_mask.expand(query_indices.shape[:-1] + (-1,))
|
||||
key_attn_mask = torch.gather(attention_mask, -1, key_indices)
|
||||
query_attn_mask = torch.gather(attention_mask, -1, query_indices)
|
||||
# expand to query_key_dots shape: duplicate along query axis since key sorting is the same for each query position in chunk
|
||||
attn_mask = query_attn_mask.unsqueeze(-1) * key_attn_mask.unsqueeze(-2)
|
||||
attention_mask = torch.gather(attention_mask, -1, key_indices)
|
||||
|
||||
# free memory
|
||||
del query_attn_mask, key_attn_mask
|
||||
else:
|
||||
# usual attention mask creation
|
||||
attention_mask = attention_mask.to(torch.uint8)[:, None, :]
|
||||
attn_mask = (attention_mask.unsqueeze(-1) * attention_mask.unsqueeze(-2)).expand(
|
||||
query_indices.shape + attention_mask.shape[-1:]
|
||||
)
|
||||
|
||||
# free memory
|
||||
del attention_mask
|
||||
attention_mask = attention_mask.unsqueeze(-2).expand(query_key_dot_shape)
|
||||
|
||||
# multiply by casaul mask if necessary
|
||||
if mask is not None:
|
||||
mask = mask * attn_mask
|
||||
mask = mask * attention_mask
|
||||
else:
|
||||
mask = attn_mask
|
||||
mask = attention_mask
|
||||
|
||||
return mask
|
||||
|
||||
@@ -931,9 +936,7 @@ class LocalSelfAttention(nn.Module, EfficientAttentionMixin):
|
||||
|
||||
if self.chunk_length < sequence_length:
|
||||
attention_mask = self._split_seq_length_dim_to(attention_mask, -1, self.chunk_length, 1)
|
||||
attention_mask_key = self._look_adjacent(attention_mask, self.num_chunks_before, self.num_chunks_after)
|
||||
else:
|
||||
attention_mask_key = attention_mask
|
||||
attention_mask = self._look_adjacent(attention_mask, self.num_chunks_before, self.num_chunks_after)
|
||||
|
||||
# Causal mask
|
||||
if self.is_decoder is True:
|
||||
@@ -942,12 +945,12 @@ class LocalSelfAttention(nn.Module, EfficientAttentionMixin):
|
||||
# Attention mask
|
||||
if attention_mask is not None:
|
||||
# create attn_mask
|
||||
attn_mask = (attention_mask.unsqueeze(-1) * attention_mask_key.unsqueeze(-2)).expand(query_key_dots_shape)
|
||||
attention_mask = attention_mask.unsqueeze(-2).expand(query_key_dots_shape)
|
||||
# multiply by casaul mask if necessary
|
||||
if mask is not None:
|
||||
mask = mask * attn_mask
|
||||
mask = mask * attention_mask
|
||||
else:
|
||||
mask = attn_mask
|
||||
mask = attention_mask
|
||||
return mask
|
||||
|
||||
|
||||
@@ -1704,6 +1707,7 @@ class ReformerModel(ReformerPreTrainedModel):
|
||||
class ReformerModelWithLMHead(ReformerPreTrainedModel):
|
||||
def __init__(self, config):
|
||||
super().__init__(config)
|
||||
assert config.is_decoder, "If you want to use `ReformerLMHeadModel` make sure that `is_decoder=True`."
|
||||
self.reformer = ReformerModel(config)
|
||||
self.lm_head = ReformerOnlyLMHead(config)
|
||||
|
||||
@@ -1789,3 +1793,190 @@ class ReformerModelWithLMHead(ReformerPreTrainedModel):
|
||||
inputs_dict["num_hashes"] = kwargs["num_hashes"]
|
||||
|
||||
return inputs_dict
|
||||
|
||||
|
||||
@add_start_docstrings("""Reformer Model with a `language modeling` head on top. """, REFORMER_START_DOCSTRING)
|
||||
class ReformerForMaskedLM(ReformerPreTrainedModel):
|
||||
def __init__(self, config):
|
||||
super().__init__(config)
|
||||
# assert (
|
||||
# not config.is_decoder
|
||||
# ), "If you want to use `ReformerForMaskedLM` make sure `config.is_decoder=False` for bi-directional self-attention."
|
||||
self.reformer = ReformerModel(config)
|
||||
self.lm_head = ReformerOnlyLMHead(config)
|
||||
|
||||
self.init_weights()
|
||||
|
||||
def get_output_embeddings(self):
|
||||
return self.lm_head.decoder
|
||||
|
||||
def tie_weights(self):
|
||||
# word embeddings are not tied in Reformer
|
||||
pass
|
||||
|
||||
@add_start_docstrings_to_callable(REFORMER_INPUTS_DOCSTRING)
|
||||
@add_code_sample_docstrings(tokenizer_class=_TOKENIZER_FOR_DOC, checkpoint="google/reformer-crime-and-punishment")
|
||||
def forward(
|
||||
self,
|
||||
input_ids=None,
|
||||
position_ids=None,
|
||||
attention_mask=None,
|
||||
head_mask=None,
|
||||
inputs_embeds=None,
|
||||
num_hashes=None,
|
||||
labels=None,
|
||||
output_hidden_states=None,
|
||||
output_attentions=None,
|
||||
):
|
||||
r"""
|
||||
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
|
||||
Labels for computing the masked language modeling loss.
|
||||
Indices should be in ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)
|
||||
Tokens with indices set to ``-100`` are ignored (masked), the loss is only computed for the tokens with labels
|
||||
|
||||
Return:
|
||||
:obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.BertConfig`) and inputs:
|
||||
loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`labels` is provided):
|
||||
Classification loss (cross entropy).
|
||||
prediction_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`)
|
||||
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
||||
all_hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
|
||||
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
|
||||
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
|
||||
|
||||
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
||||
all_attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
|
||||
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
|
||||
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
|
||||
|
||||
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
||||
heads.
|
||||
"""
|
||||
|
||||
reformer_outputs = self.reformer(
|
||||
input_ids,
|
||||
position_ids=position_ids,
|
||||
attention_mask=attention_mask,
|
||||
head_mask=head_mask,
|
||||
inputs_embeds=inputs_embeds,
|
||||
num_hashes=num_hashes,
|
||||
output_hidden_states=output_hidden_states,
|
||||
output_attentions=output_attentions,
|
||||
)
|
||||
|
||||
sequence_output = reformer_outputs[0]
|
||||
logits = self.lm_head(sequence_output)
|
||||
outputs = (logits,) + reformer_outputs[1:]
|
||||
|
||||
if labels is not None:
|
||||
loss_fct = CrossEntropyLoss() # -100 index = padding token
|
||||
masked_lm_loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
|
||||
outputs = (masked_lm_loss,) + outputs
|
||||
|
||||
return outputs # (mlm_loss), lm_logits, (hidden_states), (attentions)
|
||||
|
||||
|
||||
@add_start_docstrings(
|
||||
"""Reformer Model with a span classification head on top for
|
||||
extractive question-answering tasks like SQuAD / TriviaQA ( a linear layer on
|
||||
top of hidden-states output to compute `span start logits` and `span end logits`. """,
|
||||
REFORMER_START_DOCSTRING,
|
||||
)
|
||||
class ReformerForQuestionAnswering(ReformerPreTrainedModel):
|
||||
def __init__(self, config):
|
||||
super().__init__(config)
|
||||
self.num_labels = config.num_labels
|
||||
|
||||
self.reformer = ReformerModel(config)
|
||||
# 2 * config.hidden_size because we use reversible residual layers
|
||||
self.qa_outputs = nn.Linear(2 * config.hidden_size, config.num_labels)
|
||||
|
||||
self.init_weights()
|
||||
|
||||
def tie_weights(self):
|
||||
# word embeddings are not tied in Reformer
|
||||
pass
|
||||
|
||||
@add_start_docstrings_to_callable(REFORMER_INPUTS_DOCSTRING)
|
||||
@add_code_sample_docstrings(tokenizer_class=_TOKENIZER_FOR_DOC, checkpoint="google/reformer-crime-and-punishment")
|
||||
def forward(
|
||||
self,
|
||||
input_ids=None,
|
||||
position_ids=None,
|
||||
attention_mask=None,
|
||||
head_mask=None,
|
||||
inputs_embeds=None,
|
||||
num_hashes=None,
|
||||
start_positions=None,
|
||||
end_positions=None,
|
||||
output_hidden_states=None,
|
||||
output_attentions=None,
|
||||
):
|
||||
r"""
|
||||
start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
|
||||
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
||||
Positions are clamped to the length of the sequence (`sequence_length`).
|
||||
Position outside of the sequence are not taken into account for computing the loss.
|
||||
end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):
|
||||
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
||||
Positions are clamped to the length of the sequence (`sequence_length`).
|
||||
Position outside of the sequence are not taken into account for computing the loss.
|
||||
Return:
|
||||
:obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.ReformerConfig`) and inputs:
|
||||
loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`labels` is provided):
|
||||
Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
|
||||
start_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length,)`):
|
||||
Span-start scores (before SoftMax).
|
||||
end_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length,)`):
|
||||
Span-end scores (before SoftMax).
|
||||
all_hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
|
||||
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
|
||||
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
|
||||
|
||||
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
||||
all_attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
|
||||
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
|
||||
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
|
||||
|
||||
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
||||
heads.
|
||||
"""
|
||||
|
||||
reformer_outputs = self.reformer(
|
||||
input_ids,
|
||||
position_ids=position_ids,
|
||||
attention_mask=attention_mask,
|
||||
head_mask=head_mask,
|
||||
inputs_embeds=inputs_embeds,
|
||||
num_hashes=num_hashes,
|
||||
output_hidden_states=output_hidden_states,
|
||||
output_attentions=output_attentions,
|
||||
)
|
||||
|
||||
sequence_output = reformer_outputs[0]
|
||||
|
||||
logits = self.qa_outputs(sequence_output)
|
||||
start_logits, end_logits = logits.split(1, dim=-1)
|
||||
start_logits = start_logits.squeeze(-1)
|
||||
end_logits = end_logits.squeeze(-1)
|
||||
|
||||
outputs = (start_logits, end_logits,) + reformer_outputs[1:]
|
||||
|
||||
if start_positions is not None and end_positions is not None:
|
||||
# If we are on multi-GPU, split add a dimension
|
||||
if len(start_positions.size()) > 1:
|
||||
start_positions = start_positions.squeeze(-1)
|
||||
if len(end_positions.size()) > 1:
|
||||
end_positions = end_positions.squeeze(-1)
|
||||
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
||||
ignored_index = start_logits.size(1)
|
||||
start_positions.clamp_(0, ignored_index)
|
||||
end_positions.clamp_(0, ignored_index)
|
||||
|
||||
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
||||
start_loss = loss_fct(start_logits, start_positions)
|
||||
end_loss = loss_fct(end_logits, end_positions)
|
||||
total_loss = (start_loss + end_loss) / 2
|
||||
outputs = (total_loss,) + outputs
|
||||
|
||||
return outputs # (loss), start_logits, end_logits, (hidden_states), (attentions)
|
||||
|
||||
@@ -141,7 +141,6 @@ logger = logging.getLogger(__name__)
|
||||
TF_MODEL_MAPPING = OrderedDict(
|
||||
[
|
||||
(AlbertConfig, TFAlbertModel),
|
||||
(BertConfig, TFBertModel),
|
||||
(CamembertConfig, TFCamembertModel),
|
||||
(CTRLConfig, TFCTRLModel),
|
||||
(DistilBertConfig, TFDistilBertModel),
|
||||
@@ -151,6 +150,7 @@ TF_MODEL_MAPPING = OrderedDict(
|
||||
(MobileBertConfig, TFMobileBertModel),
|
||||
(OpenAIGPTConfig, TFOpenAIGPTModel),
|
||||
(RobertaConfig, TFRobertaModel),
|
||||
(BertConfig, TFBertModel),
|
||||
(T5Config, TFT5Model),
|
||||
(TransfoXLConfig, TFTransfoXLModel),
|
||||
(XLMConfig, TFXLMModel),
|
||||
@@ -162,7 +162,6 @@ TF_MODEL_MAPPING = OrderedDict(
|
||||
TF_MODEL_FOR_PRETRAINING_MAPPING = OrderedDict(
|
||||
[
|
||||
(AlbertConfig, TFAlbertForPreTraining),
|
||||
(BertConfig, TFBertForPreTraining),
|
||||
(CamembertConfig, TFCamembertForMaskedLM),
|
||||
(CTRLConfig, TFCTRLLMHeadModel),
|
||||
(DistilBertConfig, TFDistilBertForMaskedLM),
|
||||
@@ -172,6 +171,7 @@ TF_MODEL_FOR_PRETRAINING_MAPPING = OrderedDict(
|
||||
(MobileBertConfig, TFMobileBertForPreTraining),
|
||||
(OpenAIGPTConfig, TFOpenAIGPTLMHeadModel),
|
||||
(RobertaConfig, TFRobertaForMaskedLM),
|
||||
(BertConfig, TFBertForPreTraining),
|
||||
(T5Config, TFT5ForConditionalGeneration),
|
||||
(TransfoXLConfig, TFTransfoXLLMHeadModel),
|
||||
(XLMConfig, TFXLMWithLMHeadModel),
|
||||
@@ -183,7 +183,6 @@ TF_MODEL_FOR_PRETRAINING_MAPPING = OrderedDict(
|
||||
TF_MODEL_WITH_LM_HEAD_MAPPING = OrderedDict(
|
||||
[
|
||||
(AlbertConfig, TFAlbertForMaskedLM),
|
||||
(BertConfig, TFBertForMaskedLM),
|
||||
(CamembertConfig, TFCamembertForMaskedLM),
|
||||
(CTRLConfig, TFCTRLLMHeadModel),
|
||||
(DistilBertConfig, TFDistilBertForMaskedLM),
|
||||
@@ -193,6 +192,7 @@ TF_MODEL_WITH_LM_HEAD_MAPPING = OrderedDict(
|
||||
(MobileBertConfig, TFMobileBertForMaskedLM),
|
||||
(OpenAIGPTConfig, TFOpenAIGPTLMHeadModel),
|
||||
(RobertaConfig, TFRobertaForMaskedLM),
|
||||
(BertConfig, TFBertForMaskedLM),
|
||||
(T5Config, TFT5ForConditionalGeneration),
|
||||
(TransfoXLConfig, TFTransfoXLLMHeadModel),
|
||||
(XLMConfig, TFXLMWithLMHeadModel),
|
||||
@@ -204,12 +204,12 @@ TF_MODEL_WITH_LM_HEAD_MAPPING = OrderedDict(
|
||||
TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING = OrderedDict(
|
||||
[
|
||||
(AlbertConfig, TFAlbertForMultipleChoice),
|
||||
(BertConfig, TFBertForMultipleChoice),
|
||||
(CamembertConfig, TFCamembertForMultipleChoice),
|
||||
(DistilBertConfig, TFDistilBertForMultipleChoice),
|
||||
(FlaubertConfig, TFFlaubertForMultipleChoice),
|
||||
(MobileBertConfig, TFMobileBertForMultipleChoice),
|
||||
(RobertaConfig, TFRobertaForMultipleChoice),
|
||||
(BertConfig, TFBertForMultipleChoice),
|
||||
(XLMConfig, TFXLMForMultipleChoice),
|
||||
(XLMRobertaConfig, TFXLMRobertaForMultipleChoice),
|
||||
(XLNetConfig, TFXLNetForMultipleChoice),
|
||||
@@ -219,13 +219,13 @@ TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING = OrderedDict(
|
||||
TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING = OrderedDict(
|
||||
[
|
||||
(AlbertConfig, TFAlbertForQuestionAnswering),
|
||||
(BertConfig, TFBertForQuestionAnswering),
|
||||
(CamembertConfig, TFCamembertForQuestionAnswering),
|
||||
(DistilBertConfig, TFDistilBertForQuestionAnswering),
|
||||
(ElectraConfig, TFElectraForQuestionAnswering),
|
||||
(FlaubertConfig, TFFlaubertForQuestionAnsweringSimple),
|
||||
(MobileBertConfig, TFMobileBertForQuestionAnswering),
|
||||
(RobertaConfig, TFRobertaForQuestionAnswering),
|
||||
(BertConfig, TFBertForQuestionAnswering),
|
||||
(XLMConfig, TFXLMForQuestionAnsweringSimple),
|
||||
(XLMRobertaConfig, TFXLMRobertaForQuestionAnswering),
|
||||
(XLNetConfig, TFXLNetForQuestionAnsweringSimple),
|
||||
@@ -235,12 +235,12 @@ TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING = OrderedDict(
|
||||
TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING = OrderedDict(
|
||||
[
|
||||
(AlbertConfig, TFAlbertForSequenceClassification),
|
||||
(BertConfig, TFBertForSequenceClassification),
|
||||
(CamembertConfig, TFCamembertForSequenceClassification),
|
||||
(DistilBertConfig, TFDistilBertForSequenceClassification),
|
||||
(FlaubertConfig, TFFlaubertForSequenceClassification),
|
||||
(MobileBertConfig, TFMobileBertForSequenceClassification),
|
||||
(RobertaConfig, TFRobertaForSequenceClassification),
|
||||
(BertConfig, TFBertForSequenceClassification),
|
||||
(XLMConfig, TFXLMForSequenceClassification),
|
||||
(XLMRobertaConfig, TFXLMRobertaForSequenceClassification),
|
||||
(XLNetConfig, TFXLNetForSequenceClassification),
|
||||
@@ -250,13 +250,13 @@ TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING = OrderedDict(
|
||||
TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING = OrderedDict(
|
||||
[
|
||||
(AlbertConfig, TFAlbertForTokenClassification),
|
||||
(BertConfig, TFBertForTokenClassification),
|
||||
(CamembertConfig, TFCamembertForTokenClassification),
|
||||
(DistilBertConfig, TFDistilBertForTokenClassification),
|
||||
(ElectraConfig, TFElectraForTokenClassification),
|
||||
(FlaubertConfig, TFFlaubertForTokenClassification),
|
||||
(MobileBertConfig, TFMobileBertForTokenClassification),
|
||||
(RobertaConfig, TFRobertaForTokenClassification),
|
||||
(BertConfig, TFBertForTokenClassification),
|
||||
(XLMConfig, TFXLMForTokenClassification),
|
||||
(XLMRobertaConfig, TFXLMRobertaForTokenClassification),
|
||||
(XLNetConfig, TFXLNetForTokenClassification),
|
||||
|
||||
@@ -478,7 +478,7 @@ class TFT5Block(tf.keras.layers.Layer):
|
||||
return outputs # hidden-states, present_key_value_states, (self-attention weights), (self-attention position bias), (cross-attention weights), (cross-attention position bias)
|
||||
|
||||
|
||||
class _NoLayerEmbedTokens(object):
|
||||
class _NoLayerEmbedTokens:
|
||||
"""
|
||||
this class wraps a the TFSharedEmbeddingTokens layer into a python 'no-keras-layer'
|
||||
class to avoid problem with weight restoring. Also it makes sure that the layer is
|
||||
@@ -655,7 +655,7 @@ class TFT5MainLayer(tf.keras.layers.Layer):
|
||||
# Since we are adding it to the raw scores before the softmax, this is
|
||||
# effectively the same as removing these entirely.
|
||||
|
||||
# T5 has a mask that can compare sequence ids, we can simulate this here with this transposistion
|
||||
# T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
|
||||
# Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow/transformer/transformer_layers.py#L270
|
||||
# extended_attention_mask = tf.math.equal(extended_attention_mask,
|
||||
# tf.transpose(extended_attention_mask, perm=(-1, -2)))
|
||||
@@ -682,16 +682,8 @@ class TFT5MainLayer(tf.keras.layers.Layer):
|
||||
else:
|
||||
encoder_extended_attention_mask = None
|
||||
|
||||
# Prepare head mask if needed
|
||||
# 1.0 in head_mask indicate we keep the head
|
||||
# attention_probs has shape bsz x n_heads x N x N
|
||||
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
||||
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
||||
if head_mask is not None:
|
||||
raise NotImplementedError
|
||||
else:
|
||||
head_mask = [None] * self.num_hidden_layers
|
||||
# head_mask = tf.constant([0] * self.num_hidden_layers)
|
||||
assert head_mask is None, "Head mask not supported"
|
||||
head_mask = [None] * self.num_hidden_layers
|
||||
|
||||
present_key_value_states = ()
|
||||
all_hidden_states = ()
|
||||
@@ -1054,8 +1046,6 @@ class TFT5ForConditionalGeneration(TFT5PreTrainedModel):
|
||||
r"""
|
||||
Returns:
|
||||
:obj:`tuple(tf.Tensor)` comprising various elements depending on the configuration (:class:`~transformers.T5Config`) and inputs:
|
||||
loss (:obj:`tf.Tensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`lm_label` is provided):
|
||||
Classification loss (cross entropy).
|
||||
prediction_scores (:obj:`tf.Tensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`)
|
||||
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
||||
decoder_past_key_value_states (:obj:`tuple(tuple(tf.Tensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`, `optional`, returned when ``use_cache=True``):
|
||||
|
||||
@@ -1016,11 +1016,14 @@ class TransfoXLLMHeadModel(TransfoXLPreTrainedModel):
|
||||
return self.crit.out_layers[-1]
|
||||
|
||||
def prepare_inputs_for_generation(self, input_ids, past, **model_kwargs):
|
||||
inputs = {"input_ids": input_ids}
|
||||
inputs = {}
|
||||
|
||||
# if past is defined in model kwargs then use it for faster decoding
|
||||
if past:
|
||||
inputs["mems"] = past
|
||||
inputs["input_ids"] = input_ids[:, -1].unsqueeze(-1)
|
||||
else:
|
||||
inputs["input_ids"] = input_ids
|
||||
|
||||
return inputs
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
import logging
|
||||
import math
|
||||
from typing import Callable, Iterable, Tuple
|
||||
|
||||
import torch
|
||||
from torch.optim import Optimizer
|
||||
@@ -25,18 +26,40 @@ from torch.optim.lr_scheduler import LambdaLR
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def get_constant_schedule(optimizer, last_epoch=-1):
|
||||
""" Create a schedule with a constant learning rate.
|
||||
def get_constant_schedule(optimizer: Optimizer, last_epoch: int = -1):
|
||||
"""
|
||||
Create a schedule with a constant learning rate, using the learning rate set in optimizer.
|
||||
|
||||
Args:
|
||||
optimizer (:class:`~torch.optim.Optimizer`):
|
||||
The optimizer for which to schedule the learning rate.
|
||||
last_epoch (:obj:`int`, `optional`, defaults to -1):
|
||||
The index of the last epoch when resuming training.
|
||||
|
||||
Return:
|
||||
:obj:`torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
|
||||
"""
|
||||
return LambdaLR(optimizer, lambda _: 1, last_epoch=last_epoch)
|
||||
|
||||
|
||||
def get_constant_schedule_with_warmup(optimizer, num_warmup_steps, last_epoch=-1):
|
||||
""" Create a schedule with a constant learning rate preceded by a warmup
|
||||
period during which the learning rate increases linearly between 0 and 1.
|
||||
def get_constant_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, last_epoch: int = -1):
|
||||
"""
|
||||
Create a schedule with a constant learning rate preceded by a warmup period during which the learning rate
|
||||
increases linearly between 0 and the initial lr set in the optimizer.
|
||||
|
||||
Args:
|
||||
optimizer (:class:`~torch.optim.Optimizer`):
|
||||
The optimizer for which to schedule the learning rate.
|
||||
num_warmup_steps (:obj:`int`):
|
||||
The number of steps for the warmup phase.
|
||||
last_epoch (:obj:`int`, `optional`, defaults to -1):
|
||||
The index of the last epoch when resuming training.
|
||||
|
||||
Return:
|
||||
:obj:`torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
|
||||
"""
|
||||
|
||||
def lr_lambda(current_step):
|
||||
def lr_lambda(current_step: int):
|
||||
if current_step < num_warmup_steps:
|
||||
return float(current_step) / float(max(1.0, num_warmup_steps))
|
||||
return 1.0
|
||||
@@ -45,11 +68,25 @@ def get_constant_schedule_with_warmup(optimizer, num_warmup_steps, last_epoch=-1
|
||||
|
||||
|
||||
def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=-1):
|
||||
""" Create a schedule with a learning rate that decreases linearly after
|
||||
linearly increasing during a warmup period.
|
||||
"""
|
||||
Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0,
|
||||
after a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer.
|
||||
|
||||
Args:
|
||||
optimizer (:class:`~torch.optim.Optimizer`):
|
||||
The optimizer for which to schedule the learning rate.
|
||||
num_warmup_steps (:obj:`int`):
|
||||
The number of steps for the warmup phase.
|
||||
num_training_steps (:obj:`int`):
|
||||
The totale number of training steps.
|
||||
last_epoch (:obj:`int`, `optional`, defaults to -1):
|
||||
The index of the last epoch when resuming training.
|
||||
|
||||
Return:
|
||||
:obj:`torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
|
||||
"""
|
||||
|
||||
def lr_lambda(current_step):
|
||||
def lr_lambda(current_step: int):
|
||||
if current_step < num_warmup_steps:
|
||||
return float(current_step) / float(max(1, num_warmup_steps))
|
||||
return max(
|
||||
@@ -59,10 +96,29 @@ def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_st
|
||||
return LambdaLR(optimizer, lr_lambda, last_epoch)
|
||||
|
||||
|
||||
def get_cosine_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, num_cycles=0.5, last_epoch=-1):
|
||||
""" Create a schedule with a learning rate that decreases following the
|
||||
values of the cosine function between 0 and `pi * cycles` after a warmup
|
||||
period during which it increases linearly between 0 and 1.
|
||||
def get_cosine_schedule_with_warmup(
|
||||
optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: float = 0.5, last_epoch: int = -1
|
||||
):
|
||||
"""
|
||||
Create a schedule with a learning rate that decreases following the values of the cosine function between the
|
||||
initial lr set in the optimizer to 0, after a warmup period during which it increases linearly between 0 and the
|
||||
initial lr set in the optimizer.
|
||||
|
||||
Args:
|
||||
optimizer (:class:`~torch.optim.Optimizer`):
|
||||
The optimizer for which to schedule the learning rate.
|
||||
num_warmup_steps (:obj:`int`):
|
||||
The number of steps for the warmup phase.
|
||||
num_training_steps (:obj:`int`):
|
||||
The total number of training steps.
|
||||
num_cycles (:obj:`float`, `optional`, defaults to 0.5):
|
||||
The number of waves in the cosine schedule (the defaults is to just decrease from the max value to 0
|
||||
following a half-cosine).
|
||||
last_epoch (:obj:`int`, `optional`, defaults to -1):
|
||||
The index of the last epoch when resuming training.
|
||||
|
||||
Return:
|
||||
:obj:`torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
|
||||
"""
|
||||
|
||||
def lr_lambda(current_step):
|
||||
@@ -75,11 +131,27 @@ def get_cosine_schedule_with_warmup(optimizer, num_warmup_steps, num_training_st
|
||||
|
||||
|
||||
def get_cosine_with_hard_restarts_schedule_with_warmup(
|
||||
optimizer, num_warmup_steps, num_training_steps, num_cycles=1.0, last_epoch=-1
|
||||
optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: int = 1, last_epoch: int = -1
|
||||
):
|
||||
""" Create a schedule with a learning rate that decreases following the
|
||||
values of the cosine function with several hard restarts, after a warmup
|
||||
period during which it increases linearly between 0 and 1.
|
||||
"""
|
||||
Create a schedule with a learning rate that decreases following the values of the cosine function between the
|
||||
initial lr set in the optimizer to 0, with several hard restarts, after a warmup period during which it increases
|
||||
linearly between 0 and the initial lr set in the optimizer.
|
||||
|
||||
Args:
|
||||
optimizer (:class:`~torch.optim.Optimizer`):
|
||||
The optimizer for which to schedule the learning rate.
|
||||
num_warmup_steps (:obj:`int`):
|
||||
The number of steps for the warmup phase.
|
||||
num_training_steps (:obj:`int`):
|
||||
The total number of training steps.
|
||||
num_cycles (:obj:`int`, `optional`, defaults to 1):
|
||||
The number of hard restarts to use.
|
||||
last_epoch (:obj:`int`, `optional`, defaults to -1):
|
||||
The index of the last epoch when resuming training.
|
||||
|
||||
Return:
|
||||
:obj:`torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.
|
||||
"""
|
||||
|
||||
def lr_lambda(current_step):
|
||||
@@ -94,17 +166,34 @@ def get_cosine_with_hard_restarts_schedule_with_warmup(
|
||||
|
||||
|
||||
class AdamW(Optimizer):
|
||||
""" Implements Adam algorithm with weight decay fix.
|
||||
"""
|
||||
Implements Adam algorithm with weight decay fix as introduced in
|
||||
`Decoupled Weight Decay Regularization <https://arxiv.org/abs/1711.05101>`__.
|
||||
|
||||
Parameters:
|
||||
lr (float): learning rate. Default 1e-3.
|
||||
betas (tuple of 2 floats): Adams beta parameters (b1, b2). Default: (0.9, 0.999)
|
||||
eps (float): Adams epsilon. Default: 1e-6
|
||||
weight_decay (float): Weight decay. Default: 0.0
|
||||
correct_bias (bool): can be set to False to avoid correcting bias in Adam (e.g. like in Bert TF repository). Default True.
|
||||
params (:obj:`Iterable[torch.nn.parameter.Parameter]`):
|
||||
Iterable of parameters to optimize or dictionaries defining parameter groups.
|
||||
lr (:obj:`float`, `optional`, defaults to 1e-3):
|
||||
The learning rate to use.
|
||||
betas (:obj:`Tuple[float,float]`, `optional`, defaults to (0.9, 0.999)):
|
||||
Adam's betas parameters (b1, b2).
|
||||
eps (:obj:`float`, `optional`, defaults to 1e-6):
|
||||
Adam's epsilon for numerical stability.
|
||||
weight_decay (:obj:`float`, `optional`, defaults to 0):
|
||||
Decoupled weight decay to apply.
|
||||
correct_bias (:obj:`bool`, `optional`, defaults to `True`):
|
||||
Whether ot not to correct bias in Adam (for instance, in Bert TF repository they use :obj:`False`).
|
||||
"""
|
||||
|
||||
def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-6, weight_decay=0.0, correct_bias=True):
|
||||
def __init__(
|
||||
self,
|
||||
params: Iterable[torch.nn.parameter.Parameter],
|
||||
lr: float = 1e-3,
|
||||
betas: Tuple[float, float] = (0.9, 0.999),
|
||||
eps: float = 1e-6,
|
||||
weight_decay: float = 0.0,
|
||||
correct_bias: bool = True,
|
||||
):
|
||||
if lr < 0.0:
|
||||
raise ValueError("Invalid learning rate: {} - should be >= 0.0".format(lr))
|
||||
if not 0.0 <= betas[0] < 1.0:
|
||||
@@ -116,12 +205,12 @@ class AdamW(Optimizer):
|
||||
defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, correct_bias=correct_bias)
|
||||
super().__init__(params, defaults)
|
||||
|
||||
def step(self, closure=None):
|
||||
"""Performs a single optimization step.
|
||||
def step(self, closure: Callable = None):
|
||||
"""
|
||||
Performs a single optimization step.
|
||||
|
||||
Arguments:
|
||||
closure (callable, optional): A closure that reevaluates the model
|
||||
and returns the loss.
|
||||
closure (:obj:`Callable`, `optional`): A closure that reevaluates the model and returns the loss.
|
||||
"""
|
||||
loss = None
|
||||
if closure is not None:
|
||||
|
||||
@@ -16,15 +16,36 @@
|
||||
|
||||
|
||||
import re
|
||||
from typing import Callable, List, Optional, Union
|
||||
|
||||
import tensorflow as tf
|
||||
|
||||
|
||||
class WarmUp(tf.keras.optimizers.schedules.LearningRateSchedule):
|
||||
"""Applies a warmup schedule on a given learning rate decay schedule."""
|
||||
"""
|
||||
Applies a warmup schedule on a given learning rate decay schedule.
|
||||
|
||||
Args:
|
||||
initial_learning_rate (:obj:`float`):
|
||||
The initial learning rate for the schedule after the warmup (so this will be the learning rate at the end
|
||||
of the warmup).
|
||||
decay_schedule_fn (:obj:`Callable`):
|
||||
The schedule function to apply after the warmup for the rest of training.
|
||||
warmup_steps (:obj:`int`):
|
||||
The number of steps for the warmup part of training.
|
||||
power (:obj:`float`, `optional`, defaults to 1):
|
||||
The power to use for the polynomial warmup (defaults is a linear warmup).
|
||||
name (:obj:`str`, `optional`):
|
||||
Optional name prefix for the returned tensors during the schedule.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, initial_learning_rate, decay_schedule_fn, warmup_steps, power=1.0, name=None,
|
||||
self,
|
||||
initial_learning_rate: float,
|
||||
decay_schedule_fn: Callable,
|
||||
warmup_steps: int,
|
||||
power: float = 1.0,
|
||||
name: str = None,
|
||||
):
|
||||
super().__init__()
|
||||
self.initial_learning_rate = initial_learning_rate
|
||||
@@ -59,15 +80,34 @@ class WarmUp(tf.keras.optimizers.schedules.LearningRateSchedule):
|
||||
|
||||
|
||||
def create_optimizer(
|
||||
init_lr,
|
||||
num_train_steps,
|
||||
num_warmup_steps,
|
||||
min_lr_ratio=0.0,
|
||||
adam_epsilon=1e-8,
|
||||
weight_decay_rate=0.0,
|
||||
include_in_weight_decay=None,
|
||||
init_lr: float,
|
||||
num_train_steps: int,
|
||||
num_warmup_steps: int,
|
||||
min_lr_ratio: float = 0.0,
|
||||
adam_epsilon: float = 1e-8,
|
||||
weight_decay_rate: float = 0.0,
|
||||
include_in_weight_decay: Optional[List[str]] = None,
|
||||
):
|
||||
"""Creates an optimizer with learning rate schedule."""
|
||||
"""
|
||||
Creates an optimizer with a learning rate schedule using a warmup phase followed by a linear decay.
|
||||
|
||||
Args:
|
||||
init_lr (:obj:`float`):
|
||||
The desired learning rate at the end of the warmup phase.
|
||||
num_train_step (:obj:`int`):
|
||||
The total number of training steps.
|
||||
num_warmup_steps (:obj:`int`):
|
||||
The number of warmup steps.
|
||||
min_lr_ratio (:obj:`float`, `optional`, defaults to 0):
|
||||
The final learning rate at the end of the linear decay will be :obj:`init_lr * min_lr_ratio`.
|
||||
adam_epsilon (:obj:`float`, `optional`, defaults to 1e-8):
|
||||
The epsilon to use in Adam.
|
||||
weight_decay_rate (:obj:`float`, `optional`, defaults to 0):
|
||||
The weight decay to use.
|
||||
include_in_weight_decay (:obj:`List[str]`, `optional`):
|
||||
List of the parameter names (or re patterns) to apply weight decay to. If none is passed, weight decay is
|
||||
applied to all parameters except bias and layer norm parameters.
|
||||
"""
|
||||
# Implements linear decay of the learning rate.
|
||||
lr_schedule = tf.keras.optimizers.schedules.PolynomialDecay(
|
||||
initial_learning_rate=init_lr,
|
||||
@@ -96,26 +136,55 @@ def create_optimizer(
|
||||
|
||||
|
||||
class AdamWeightDecay(tf.keras.optimizers.Adam):
|
||||
"""Adam enables L2 weight decay and clip_by_global_norm on gradients.
|
||||
Just adding the square of the weights to the loss function is *not* the
|
||||
correct way of using L2 regularization/weight decay with Adam, since that will
|
||||
interact with the m and v parameters in strange ways.
|
||||
Instead we want ot decay the weights in a manner that doesn't interact with
|
||||
the m/v parameters. This is equivalent to adding the square of the weights to
|
||||
the loss with plain (non-momentum) SGD.
|
||||
"""
|
||||
Adam enables L2 weight decay and clip_by_global_norm on gradients. Just adding the square of the weights to the
|
||||
loss function is *not* the correct way of using L2 regularization/weight decay with Adam, since that will interact
|
||||
with the m and v parameters in strange ways as shown in
|
||||
`Decoupled Weight Decay Regularization <https://arxiv.org/abs/1711.05101>`__.
|
||||
|
||||
Instead we want ot decay the weights in a manner that doesn't interact with the m/v parameters. This is equivalent
|
||||
to adding the square of the weights to the loss with plain (non-momentum) SGD.
|
||||
|
||||
Args:
|
||||
learning_rate (:obj:`Union[float, tf.keras.optimizers.schedules.LearningRateSchedule]`, `optional`, defaults to 1e-3):
|
||||
The learning rate to use or a schedule.
|
||||
beta_1 (:obj:`float`, `optional`, defaults to 0.9):
|
||||
The beta1 parameter in Adam, which is the exponential decay rate for the 1st momentum estimates.
|
||||
beta_2 (:obj:`float`, `optional`, defaults to 0.999):
|
||||
The beta2 parameter in Adam, which is the exponential decay rate for the 2nd momentum estimates.
|
||||
epsilon (:obj:`float`, `optional`, defaults to 1e-7):
|
||||
The epsilon paramenter in Adam, which is a small constant for numerical stability.
|
||||
amsgrad (:obj:`bool`, `optional`, default to `False`):
|
||||
Wheter to apply AMSGrad varient of this algorithm or not, see
|
||||
`On the Convergence of Adam and Beyond <https://arxiv.org/abs/1904.09237>`__.
|
||||
weight_decay_rate (:obj:`float`, `optional`, defaults to 0):
|
||||
The weight decay to apply.
|
||||
include_in_weight_decay (:obj:`List[str]`, `optional`):
|
||||
List of the parameter names (or re patterns) to apply weight decay to. If none is passed, weight decay is
|
||||
applied to all parameters by default (unless they are in :obj:`exclude_from_weight_decay`).
|
||||
exclude_from_weight_decay (:obj:`List[str]`, `optional`):
|
||||
List of the parameter names (or re patterns) to exclude from applying weight decay to. If a
|
||||
:obj:`include_in_weight_decay` is passed, the names in it will supersede this list.
|
||||
name (:obj:`str`, `optional`, defaults to 'AdamWeightDecay'):
|
||||
Optional name for the operations created when applying gradients.
|
||||
kwargs:
|
||||
Keyward arguments. Allowed to be {``clipnorm``, ``clipvalue``, ``lr``, ``decay``}. ``clipnorm`` is clip
|
||||
gradients by norm; ``clipvalue`` is clip gradients by value, ``decay`` is included for backward
|
||||
compatibility to allow time inverse decay of learning rate. ``lr`` is included for backward compatibility,
|
||||
recommended to use ``learning_rate`` instead.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
learning_rate=0.001,
|
||||
beta_1=0.9,
|
||||
beta_2=0.999,
|
||||
epsilon=1e-7,
|
||||
amsgrad=False,
|
||||
weight_decay_rate=0.0,
|
||||
include_in_weight_decay=None,
|
||||
exclude_from_weight_decay=None,
|
||||
name="AdamWeightDecay",
|
||||
learning_rate: Union[float, tf.keras.optimizers.schedules.LearningRateSchedule] = 0.001,
|
||||
beta_1: float = 0.9,
|
||||
beta_2: float = 0.999,
|
||||
epsilon: float = 1e-7,
|
||||
amsgrad: bool = False,
|
||||
weight_decay_rate: float = 0.0,
|
||||
include_in_weight_decay: Optional[List[str]] = None,
|
||||
exclude_from_weight_decay: Optional[List[str]] = None,
|
||||
name: str = "AdamWeightDecay",
|
||||
**kwargs
|
||||
):
|
||||
super().__init__(learning_rate, beta_1, beta_2, epsilon, amsgrad, name, **kwargs)
|
||||
|
||||
@@ -87,6 +87,18 @@ def get_framework(model=None):
|
||||
return framework
|
||||
|
||||
|
||||
class PipelineException(Exception):
|
||||
"""
|
||||
Raised by pipelines when handling __call__
|
||||
"""
|
||||
|
||||
def __init__(self, task: str, model: str, reason: str):
|
||||
super().__init__(reason)
|
||||
|
||||
self.task = task
|
||||
self.model = model
|
||||
|
||||
|
||||
class ArgumentHandler(ABC):
|
||||
"""
|
||||
Base interface for handling varargs for each Pipeline
|
||||
@@ -603,6 +615,28 @@ class TextGenerationPipeline(Pipeline):
|
||||
"TFCTRLLMHeadModel",
|
||||
]
|
||||
|
||||
# overriding _parse_and_tokenize to allow for unusual language-modeling tokenizer arguments
|
||||
|
||||
def _parse_and_tokenize(self, *args, padding=True, add_special_tokens=True, **kwargs):
|
||||
"""
|
||||
Parse arguments and tokenize
|
||||
"""
|
||||
# Parse arguments
|
||||
if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
|
||||
tokenizer_kwargs = {"add_space_before_punct_symbol": True}
|
||||
else:
|
||||
tokenizer_kwargs = {}
|
||||
inputs = self._args_parser(*args, **kwargs)
|
||||
inputs = self.tokenizer(
|
||||
inputs,
|
||||
add_special_tokens=add_special_tokens,
|
||||
return_tensors=self.framework,
|
||||
padding=padding,
|
||||
**tokenizer_kwargs,
|
||||
)
|
||||
|
||||
return inputs
|
||||
|
||||
def __call__(
|
||||
self, *args, return_tensors=False, return_text=True, clean_up_tokenization_spaces=False, **generate_kwargs
|
||||
):
|
||||
@@ -808,6 +842,21 @@ class FillMaskPipeline(Pipeline):
|
||||
|
||||
self.topk = topk
|
||||
|
||||
def ensure_exactly_one_mask_token(self, masked_index: np.ndarray):
|
||||
numel = np.prod(masked_index.shape)
|
||||
if numel > 1:
|
||||
raise PipelineException(
|
||||
"fill-mask",
|
||||
self.model.base_model_prefix,
|
||||
f"More than one mask_token ({self.tokenizer.mask_token}) is not supported",
|
||||
)
|
||||
elif numel < 1:
|
||||
raise PipelineException(
|
||||
"fill-mask",
|
||||
self.model.base_model_prefix,
|
||||
f"No mask_token ({self.tokenizer.mask_token}) found on the input",
|
||||
)
|
||||
|
||||
def __call__(self, *args, **kwargs):
|
||||
inputs = self._parse_and_tokenize(*args, **kwargs)
|
||||
outputs = self._forward(inputs, return_tensors=True)
|
||||
@@ -820,15 +869,22 @@ class FillMaskPipeline(Pipeline):
|
||||
result = []
|
||||
|
||||
if self.framework == "tf":
|
||||
masked_index = tf.where(input_ids == self.tokenizer.mask_token_id).numpy().item()
|
||||
logits = outputs[i, masked_index, :]
|
||||
masked_index = tf.where(input_ids == self.tokenizer.mask_token_id).numpy()
|
||||
|
||||
# Fill mask pipeline supports only one ${mask_token} per sample
|
||||
self.ensure_exactly_one_mask_token(masked_index)
|
||||
|
||||
logits = outputs[i, masked_index.item(), :]
|
||||
probs = tf.nn.softmax(logits)
|
||||
topk = tf.math.top_k(probs, k=self.topk)
|
||||
values, predictions = topk.values.numpy(), topk.indices.numpy()
|
||||
else:
|
||||
masked_index = (input_ids == self.tokenizer.mask_token_id).nonzero().item()
|
||||
masked_index = (input_ids == self.tokenizer.mask_token_id).nonzero()
|
||||
|
||||
logits = outputs[i, masked_index, :]
|
||||
# Fill mask pipeline supports only one ${mask_token} per sample
|
||||
self.ensure_exactly_one_mask_token(masked_index.numpy())
|
||||
|
||||
logits = outputs[i, masked_index.item(), :]
|
||||
probs = logits.softmax(dim=0)
|
||||
values, predictions = probs.topk(self.topk)
|
||||
|
||||
@@ -988,6 +1044,10 @@ class TokenClassificationPipeline(Pipeline):
|
||||
|
||||
entities += [entity]
|
||||
|
||||
# Ensure if an entity is the latest one in the sequence it gets appended to the output
|
||||
if len(entity_group_disagg) > 0:
|
||||
entity_groups.append(self.group_entities(entity_group_disagg))
|
||||
|
||||
# Append
|
||||
if self.grouped_entities:
|
||||
answers += [entity_groups]
|
||||
@@ -1212,33 +1272,34 @@ class QuestionAnsweringPipeline(Pipeline):
|
||||
with self.device_placement():
|
||||
if self.framework == "tf":
|
||||
fw_args = {k: tf.constant(v) for (k, v) in fw_args.items()}
|
||||
start, end = self.model(fw_args)
|
||||
start, end = self.model(fw_args)[:2]
|
||||
start, end = start.numpy(), end.numpy()
|
||||
else:
|
||||
with torch.no_grad():
|
||||
# Retrieve the score for the context tokens only (removing question tokens)
|
||||
fw_args = {k: torch.tensor(v, device=self.device) for (k, v) in fw_args.items()}
|
||||
start, end = self.model(**fw_args)
|
||||
start, end = self.model(**fw_args)[:2]
|
||||
start, end = start.cpu().numpy(), end.cpu().numpy()
|
||||
|
||||
min_null_score = 1000000 # large and positive
|
||||
answers = []
|
||||
for (feature, start_, end_) in zip(features, start, end):
|
||||
# Normalize logits and spans to retrieve the answer
|
||||
start_ = np.exp(start_) / np.sum(np.exp(start_))
|
||||
end_ = np.exp(end_) / np.sum(np.exp(end_))
|
||||
|
||||
# Mask padding and question
|
||||
start_, end_ = (
|
||||
start_ * np.abs(np.array(feature.p_mask) - 1),
|
||||
end_ * np.abs(np.array(feature.p_mask) - 1),
|
||||
)
|
||||
|
||||
# Mask CLS
|
||||
start_[0] = end_[0] = 0
|
||||
|
||||
# Normalize logits and spans to retrieve the answer
|
||||
start_ = np.exp(start_ - np.log(np.sum(np.exp(start_), axis=-1, keepdims=True)))
|
||||
end_ = np.exp(end_ - np.log(np.sum(np.exp(end_), axis=-1, keepdims=True)))
|
||||
|
||||
if kwargs["handle_impossible_answer"]:
|
||||
min_null_score = min(min_null_score, (start_[0] * end_[0]).item())
|
||||
|
||||
start_[0] = end_[0] = 0
|
||||
|
||||
starts, ends, scores = self.decode(start_, end_, kwargs["topk"], kwargs["max_answer_len"])
|
||||
char_to_word = np.array(example.char_to_word_offset)
|
||||
|
||||
|
||||
@@ -129,6 +129,8 @@ class MarianTokenizer(PreTrainedTokenizer):
|
||||
max_length: Optional[int] = None,
|
||||
pad_to_max_length: bool = True,
|
||||
return_tensors: str = "pt",
|
||||
truncation_strategy="only_first",
|
||||
padding="longest",
|
||||
) -> BatchEncoding:
|
||||
"""Prepare model inputs for translation. For best performance, translate one sentence at a time.
|
||||
Arguments:
|
||||
@@ -147,24 +149,21 @@ class MarianTokenizer(PreTrainedTokenizer):
|
||||
raise ValueError(f"found empty string in src_texts: {src_texts}")
|
||||
self.current_spm = self.spm_source
|
||||
src_texts = [self.normalize(t) for t in src_texts] # this does not appear to do much
|
||||
model_inputs: BatchEncoding = self.batch_encode_plus(
|
||||
src_texts,
|
||||
tokenizer_kwargs = dict(
|
||||
add_special_tokens=True,
|
||||
return_tensors=return_tensors,
|
||||
max_length=max_length,
|
||||
pad_to_max_length=pad_to_max_length,
|
||||
truncation_strategy=truncation_strategy,
|
||||
padding=padding,
|
||||
)
|
||||
model_inputs: BatchEncoding = self(src_texts, **tokenizer_kwargs)
|
||||
|
||||
if tgt_texts is None:
|
||||
return model_inputs
|
||||
|
||||
self.current_spm = self.spm_target
|
||||
decoder_inputs: BatchEncoding = self.batch_encode_plus(
|
||||
tgt_texts,
|
||||
add_special_tokens=True,
|
||||
return_tensors=return_tensors,
|
||||
max_length=max_length,
|
||||
pad_to_max_length=pad_to_max_length,
|
||||
)
|
||||
decoder_inputs: BatchEncoding = self(tgt_texts, **tokenizer_kwargs)
|
||||
for k, v in decoder_inputs.items():
|
||||
model_inputs[f"decoder_{k}"] = v
|
||||
self.current_spm = self.spm_source
|
||||
|
||||
@@ -454,12 +454,12 @@ class PreTrainedTokenizer(PreTrainedTokenizerBase):
|
||||
first_ids = get_input_ids(text)
|
||||
second_ids = get_input_ids(text_pair) if text_pair is not None else None
|
||||
|
||||
return self._prepare_for_model(
|
||||
return self.prepare_for_model(
|
||||
first_ids,
|
||||
pair_ids=second_ids,
|
||||
add_special_tokens=add_special_tokens,
|
||||
padding_strategy=padding_strategy,
|
||||
truncation_strategy=truncation_strategy,
|
||||
padding=padding_strategy.value,
|
||||
truncation=truncation_strategy.value,
|
||||
max_length=max_length,
|
||||
stride=stride,
|
||||
pad_to_multiple_of=pad_to_multiple_of,
|
||||
@@ -584,7 +584,7 @@ class PreTrainedTokenizer(PreTrainedTokenizerBase):
|
||||
|
||||
batch_outputs = {}
|
||||
for first_ids, second_ids in batch_ids_pairs:
|
||||
outputs = self._prepare_for_model(
|
||||
outputs = self.prepare_for_model(
|
||||
first_ids,
|
||||
second_ids,
|
||||
add_special_tokens=add_special_tokens,
|
||||
@@ -620,109 +620,6 @@ class PreTrainedTokenizer(PreTrainedTokenizerBase):
|
||||
|
||||
return batch_outputs
|
||||
|
||||
@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
|
||||
def _prepare_for_model(
|
||||
self,
|
||||
ids: List[int],
|
||||
pair_ids: Optional[List[int]] = None,
|
||||
add_special_tokens: bool = True,
|
||||
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
||||
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
|
||||
max_length: Optional[int] = None,
|
||||
stride: int = 0,
|
||||
pad_to_multiple_of: Optional[int] = None,
|
||||
return_tensors: Optional[str] = None,
|
||||
prepend_batch_axis: bool = False,
|
||||
return_token_type_ids: Optional[bool] = None,
|
||||
return_attention_mask: Optional[bool] = None,
|
||||
return_overflowing_tokens: bool = False,
|
||||
return_special_tokens_mask: bool = False,
|
||||
return_length: bool = False,
|
||||
verbose: bool = True,
|
||||
) -> BatchEncoding:
|
||||
""" Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model.
|
||||
It adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
|
||||
manages a moving window (with user defined stride) for overflowing tokens
|
||||
|
||||
Args:
|
||||
ids: list of tokenized input ids. Can be obtained from a string by chaining the
|
||||
`tokenize` and `convert_tokens_to_ids` methods.
|
||||
pair_ids: Optional second list of input ids. Can be obtained from a string by chaining the
|
||||
`tokenize` and `convert_tokens_to_ids` methods.
|
||||
"""
|
||||
pair = bool(pair_ids is not None)
|
||||
len_ids = len(ids)
|
||||
len_pair_ids = len(pair_ids) if pair else 0
|
||||
|
||||
# Load from model defaults
|
||||
if return_token_type_ids is None:
|
||||
return_token_type_ids = "token_type_ids" in self.model_input_names
|
||||
if return_attention_mask is None:
|
||||
return_attention_mask = "attention_mask" in self.model_input_names
|
||||
|
||||
encoded_inputs = {}
|
||||
|
||||
# Compute the total size of the returned encodings
|
||||
total_len = len_ids + len_pair_ids + (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)
|
||||
|
||||
# Truncation: Handle max sequence length
|
||||
if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and max_length and total_len > max_length:
|
||||
ids, pair_ids, overflowing_tokens = self.truncate_sequences(
|
||||
ids,
|
||||
pair_ids=pair_ids,
|
||||
num_tokens_to_remove=total_len - max_length,
|
||||
truncation_strategy=truncation_strategy,
|
||||
stride=stride,
|
||||
)
|
||||
if return_overflowing_tokens:
|
||||
encoded_inputs["overflowing_tokens"] = overflowing_tokens
|
||||
encoded_inputs["num_truncated_tokens"] = total_len - max_length
|
||||
|
||||
# Add special tokens
|
||||
if add_special_tokens:
|
||||
sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
|
||||
token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)
|
||||
else:
|
||||
sequence = ids + pair_ids if pair else ids
|
||||
token_type_ids = [0] * len(ids) + ([1] * len(pair_ids) if pair else [])
|
||||
|
||||
# Build output dictionnary
|
||||
encoded_inputs["input_ids"] = sequence
|
||||
if return_token_type_ids:
|
||||
encoded_inputs["token_type_ids"] = token_type_ids
|
||||
if return_special_tokens_mask:
|
||||
if add_special_tokens:
|
||||
encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(ids, pair_ids)
|
||||
else:
|
||||
encoded_inputs["special_tokens_mask"] = [0] * len(sequence)
|
||||
|
||||
# Check lengths
|
||||
if max_length is None and len(encoded_inputs["input_ids"]) > self.model_max_length and verbose:
|
||||
logger.warning(
|
||||
"Token indices sequence length is longer than the specified maximum sequence length "
|
||||
"for this model ({} > {}). Running this sequence through the model will result in "
|
||||
"indexing errors".format(len(ids), self.model_max_length)
|
||||
)
|
||||
|
||||
# Padding
|
||||
if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask:
|
||||
encoded_inputs = self.pad(
|
||||
encoded_inputs,
|
||||
max_length=max_length,
|
||||
padding=padding_strategy.value,
|
||||
pad_to_multiple_of=pad_to_multiple_of,
|
||||
return_attention_mask=return_attention_mask,
|
||||
)
|
||||
|
||||
if return_length:
|
||||
encoded_inputs["length"] = len(encoded_inputs["input_ids"])
|
||||
|
||||
batch_outputs = BatchEncoding(
|
||||
encoded_inputs, tensor_type=return_tensors, prepend_batch_axis=prepend_batch_axis
|
||||
)
|
||||
|
||||
return batch_outputs
|
||||
|
||||
def prepare_for_tokenization(self, text: str, is_pretokenized=False, **kwargs) -> (str, dict):
|
||||
""" Performs any necessary transformations before tokenization.
|
||||
|
||||
@@ -731,90 +628,6 @@ class PreTrainedTokenizer(PreTrainedTokenizerBase):
|
||||
"""
|
||||
return (text, kwargs)
|
||||
|
||||
def truncate_sequences(
|
||||
self,
|
||||
ids: List[int],
|
||||
pair_ids: Optional[List[int]] = None,
|
||||
num_tokens_to_remove: int = 0,
|
||||
truncation_strategy: Union[str, TruncationStrategy] = "only_first",
|
||||
stride: int = 0,
|
||||
) -> Tuple[List[int], List[int], List[int]]:
|
||||
""" Truncates a sequence pair in place to the maximum length.
|
||||
|
||||
Args:
|
||||
ids: list of tokenized input ids. Can be obtained from a string by chaining the
|
||||
`tokenize` and `convert_tokens_to_ids` methods.
|
||||
pair_ids: Optional second list of input ids. Can be obtained from a string by chaining the
|
||||
`tokenize` and `convert_tokens_to_ids` methods.
|
||||
num_tokens_to_remove (:obj:`int`, `optional`, defaults to ``0``):
|
||||
number of tokens to remove using the truncation strategy
|
||||
truncation_strategy (:obj:`string`, `optional`, defaults to "only_first"):
|
||||
String selected in the following options:
|
||||
|
||||
- 'only_first' (default): Only truncate the first sequence. raise an error if the first sequence is shorter or equal to than num_tokens_to_remove.
|
||||
- 'only_second': Only truncate the second sequence
|
||||
- 'longest_first': Iteratively reduce the inputs sequence until the input is under max_length
|
||||
starting from the longest one at each token (when there is a pair of input sequences).
|
||||
Overflowing tokens only contains overflow from the first sequence.
|
||||
- 'do_not_truncate'
|
||||
stride (:obj:`int`, `optional`, defaults to ``0``):
|
||||
If set to a number along with max_length, the overflowing tokens returned will contain some tokens
|
||||
from the main sequence returned. The value of this argument defines the number of additional tokens.
|
||||
"""
|
||||
if num_tokens_to_remove <= 0:
|
||||
return ids, pair_ids, []
|
||||
|
||||
if not isinstance(truncation_strategy, TruncationStrategy):
|
||||
truncation_strategy = TruncationStrategy(truncation_strategy)
|
||||
|
||||
overflowing_tokens = []
|
||||
if truncation_strategy == TruncationStrategy.LONGEST_FIRST:
|
||||
for _ in range(num_tokens_to_remove):
|
||||
if pair_ids is None or len(ids) > len(pair_ids):
|
||||
ids = ids[:-1]
|
||||
else:
|
||||
pair_ids = pair_ids[:-1]
|
||||
elif truncation_strategy == TruncationStrategy.ONLY_FIRST:
|
||||
if len(ids) > num_tokens_to_remove:
|
||||
window_len = min(len(ids), stride + num_tokens_to_remove)
|
||||
overflowing_tokens = ids[-window_len:]
|
||||
ids = ids[:-num_tokens_to_remove]
|
||||
else:
|
||||
logger.error(
|
||||
f"We need to remove {num_tokens_to_remove} to truncate the input"
|
||||
f"but the first sequence has a length {len(ids)}. "
|
||||
f"Please select another truncation strategy than {truncation_strategy}, "
|
||||
f"for instance 'longest_first' or 'only_second'."
|
||||
)
|
||||
elif truncation_strategy == TruncationStrategy.ONLY_SECOND and pair_ids is not None:
|
||||
if len(pair_ids) > num_tokens_to_remove:
|
||||
window_len = min(len(pair_ids), stride + num_tokens_to_remove)
|
||||
overflowing_tokens = pair_ids[-window_len:]
|
||||
pair_ids = pair_ids[:-num_tokens_to_remove]
|
||||
else:
|
||||
logger.error(
|
||||
f"We need to remove {num_tokens_to_remove} to truncate the input"
|
||||
f"but the second sequence has a length {len(pair_ids)}. "
|
||||
f"Please select another truncation strategy than {truncation_strategy}, "
|
||||
f"for instance 'longest_first' or 'only_first'."
|
||||
)
|
||||
|
||||
return (ids, pair_ids, overflowing_tokens)
|
||||
|
||||
def create_token_type_ids_from_sequences(self, token_ids_0: List, token_ids_1: Optional[List] = None) -> List[int]:
|
||||
if token_ids_1 is None:
|
||||
return len(token_ids_0) * [0]
|
||||
return [0] * len(token_ids_0) + [1] * len(token_ids_1)
|
||||
|
||||
def build_inputs_with_special_tokens(self, token_ids_0: List, token_ids_1: Optional[List] = None) -> List:
|
||||
"""
|
||||
Build model inputs from a sequence or a pair of sequence for sequence classification tasks
|
||||
by concatenating and adding special tokens. This implementation does not add special tokens.
|
||||
"""
|
||||
if token_ids_1 is None:
|
||||
return token_ids_0
|
||||
return token_ids_0 + token_ids_1
|
||||
|
||||
def get_special_tokens_mask(
|
||||
self, token_ids_0: List, token_ids_1: Optional[List] = None, already_has_special_tokens: bool = False
|
||||
) -> List[int]:
|
||||
|
||||
@@ -945,9 +945,9 @@ ENCODE_KWARGS_DOCSTRING = r"""
|
||||
`truncation` (:obj:`Union[bool, str]`, `optional`, defaults to :obj:`False`):
|
||||
Activate and control truncation. Accepts the following values:
|
||||
|
||||
* `True` or `'only_first'`: truncate to a max length specified in `max_length` or to the max acceptable input length for the model if no length is provided (`max_length=None`). This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided,
|
||||
* `True` or `'longest_first'`: truncate to a max length specified in `max_length` or to the max acceptable input length for the model if no length is provided (`max_length=None`). This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided,
|
||||
* `'only_first'`: truncate to a max length specified in `max_length` or to the max acceptable input length for the model if no length is provided (`max_length=None`). This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided,
|
||||
* `'only_second'`: truncate to a max length specified in `max_length` or to the max acceptable input length for the model if no length is provided (`max_length=None`). This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided,
|
||||
* `'longest_first'`: truncate to a max length specified in `max_length` or to the max acceptable input length for the model if no length is provided (`max_length=None`). This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided,
|
||||
* `False` or `'do_not_truncate'` (default): No truncation (i.e. can output batch with sequences length greater than the model max admissible input size)
|
||||
`max_length` (:obj:`Union[int, None]`, `optional`, defaults to :obj:`None`):
|
||||
Control the length for padding/truncation. Accepts the following values
|
||||
@@ -1446,10 +1446,11 @@ class PreTrainedTokenizerBase(SpecialTokensMixin):
|
||||
logger.warning(
|
||||
"Truncation was not explicitely activated but `max_length` is provided a specific value, "
|
||||
"please use `truncation=True` to explicitely truncate examples to max length. "
|
||||
"Defaulting to 'only_first' truncation strategy. "
|
||||
"If you encode pairs of sequences (GLUE-style) with the tokenizer you may want to check this is the right behavior."
|
||||
"Defaulting to 'longest_first' truncation strategy. "
|
||||
"If you encode pairs of sequences (GLUE-style) with the tokenizer you can select this strategy "
|
||||
"more precisely by providing a specific strategy to `truncation`."
|
||||
)
|
||||
truncation = "only_first"
|
||||
truncation = "longest_first"
|
||||
|
||||
# Get padding strategy
|
||||
if padding is False and old_pad_to_max_length:
|
||||
@@ -1469,7 +1470,7 @@ class PreTrainedTokenizerBase(SpecialTokensMixin):
|
||||
elif padding is not False:
|
||||
if padding is True:
|
||||
padding_strategy = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch
|
||||
else:
|
||||
elif not isinstance(padding, PaddingStrategy):
|
||||
padding_strategy = PaddingStrategy(padding)
|
||||
else:
|
||||
padding_strategy = PaddingStrategy.DO_NOT_PAD
|
||||
@@ -1492,9 +1493,9 @@ class PreTrainedTokenizerBase(SpecialTokensMixin):
|
||||
elif truncation is not False:
|
||||
if truncation is True:
|
||||
truncation_strategy = (
|
||||
TruncationStrategy.ONLY_FIRST
|
||||
) # Default to truncate the first sequences in pairs of inputs
|
||||
else:
|
||||
TruncationStrategy.LONGEST_FIRST
|
||||
) # Default to truncate the longest sequences in pairs of inputs
|
||||
elif not isinstance(truncation, TruncationStrategy):
|
||||
truncation_strategy = TruncationStrategy(truncation)
|
||||
else:
|
||||
truncation_strategy = TruncationStrategy.DO_NOT_TRUNCATE
|
||||
@@ -1960,6 +1961,225 @@ class PreTrainedTokenizerBase(SpecialTokensMixin):
|
||||
|
||||
return BatchEncoding(batch_outputs, tensor_type=return_tensors)
|
||||
|
||||
def create_token_type_ids_from_sequences(self, token_ids_0: List, token_ids_1: Optional[List] = None) -> List[int]:
|
||||
if token_ids_1 is None:
|
||||
return len(token_ids_0) * [0]
|
||||
return [0] * len(token_ids_0) + [1] * len(token_ids_1)
|
||||
|
||||
def build_inputs_with_special_tokens(self, token_ids_0: List, token_ids_1: Optional[List] = None) -> List:
|
||||
"""
|
||||
Build model inputs from a sequence or a pair of sequence for sequence classification tasks
|
||||
by concatenating and adding special tokens. This implementation does not add special tokens.
|
||||
"""
|
||||
if token_ids_1 is None:
|
||||
return token_ids_0
|
||||
return token_ids_0 + token_ids_1
|
||||
|
||||
@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
|
||||
def prepare_for_model(
|
||||
self,
|
||||
ids: List[int],
|
||||
pair_ids: Optional[List[int]] = None,
|
||||
add_special_tokens: bool = True,
|
||||
padding: Union[bool, str] = False,
|
||||
truncation: Union[bool, str] = False,
|
||||
max_length: Optional[int] = None,
|
||||
stride: int = 0,
|
||||
pad_to_multiple_of: Optional[int] = None,
|
||||
return_tensors: Optional[Union[str, TensorType]] = None,
|
||||
return_token_type_ids: Optional[bool] = None,
|
||||
return_attention_mask: Optional[bool] = None,
|
||||
return_overflowing_tokens: bool = False,
|
||||
return_special_tokens_mask: bool = False,
|
||||
return_offsets_mapping: bool = False,
|
||||
return_length: bool = False,
|
||||
verbose: bool = True,
|
||||
prepend_batch_axis: bool = False,
|
||||
**kwargs
|
||||
) -> BatchEncoding:
|
||||
""" Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model.
|
||||
It adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
|
||||
manages a moving window (with user defined stride) for overflowing tokens
|
||||
|
||||
Args:
|
||||
ids: list of tokenized input ids. Can be obtained from a string by chaining the
|
||||
`tokenize` and `convert_tokens_to_ids` methods.
|
||||
pair_ids: Optional second list of input ids. Can be obtained from a string by chaining the
|
||||
`tokenize` and `convert_tokens_to_ids` methods.
|
||||
"""
|
||||
|
||||
if "return_lengths" in kwargs:
|
||||
if verbose:
|
||||
warnings.warn(
|
||||
"The PreTrainedTokenizerBase.prepare_for_model `return_lengths` parameter is deprecated. "
|
||||
"Please use `return_length` instead.",
|
||||
FutureWarning,
|
||||
)
|
||||
return_length = kwargs["return_lengths"]
|
||||
|
||||
# Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
|
||||
padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
|
||||
padding=padding,
|
||||
truncation=truncation,
|
||||
max_length=max_length,
|
||||
pad_to_multiple_of=pad_to_multiple_of,
|
||||
verbose=verbose,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
pair = bool(pair_ids is not None)
|
||||
len_ids = len(ids)
|
||||
len_pair_ids = len(pair_ids) if pair else 0
|
||||
|
||||
# Load from model defaults
|
||||
if return_token_type_ids is None:
|
||||
return_token_type_ids = "token_type_ids" in self.model_input_names
|
||||
if return_attention_mask is None:
|
||||
return_attention_mask = "attention_mask" in self.model_input_names
|
||||
|
||||
encoded_inputs = {}
|
||||
|
||||
# Compute the total size of the returned encodings
|
||||
total_len = len_ids + len_pair_ids + (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)
|
||||
|
||||
# Truncation: Handle max sequence length
|
||||
if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and max_length and total_len > max_length:
|
||||
ids, pair_ids, overflowing_tokens = self.truncate_sequences(
|
||||
ids,
|
||||
pair_ids=pair_ids,
|
||||
num_tokens_to_remove=total_len - max_length,
|
||||
truncation_strategy=truncation_strategy,
|
||||
stride=stride,
|
||||
)
|
||||
if return_overflowing_tokens:
|
||||
encoded_inputs["overflowing_tokens"] = overflowing_tokens
|
||||
encoded_inputs["num_truncated_tokens"] = total_len - max_length
|
||||
|
||||
# Add special tokens
|
||||
if add_special_tokens:
|
||||
sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
|
||||
token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)
|
||||
else:
|
||||
sequence = ids + pair_ids if pair else ids
|
||||
token_type_ids = [0] * len(ids) + ([1] * len(pair_ids) if pair else [])
|
||||
|
||||
# Build output dictionnary
|
||||
encoded_inputs["input_ids"] = sequence
|
||||
if return_token_type_ids:
|
||||
encoded_inputs["token_type_ids"] = token_type_ids
|
||||
if return_special_tokens_mask:
|
||||
if add_special_tokens:
|
||||
encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(ids, pair_ids)
|
||||
else:
|
||||
encoded_inputs["special_tokens_mask"] = [0] * len(sequence)
|
||||
|
||||
# Check lengths
|
||||
if max_length is None and len(encoded_inputs["input_ids"]) > self.model_max_length and verbose:
|
||||
logger.warning(
|
||||
"Token indices sequence length is longer than the specified maximum sequence length "
|
||||
"for this model ({} > {}). Running this sequence through the model will result in "
|
||||
"indexing errors".format(len(ids), self.model_max_length)
|
||||
)
|
||||
|
||||
# Padding
|
||||
if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask:
|
||||
encoded_inputs = self.pad(
|
||||
encoded_inputs,
|
||||
max_length=max_length,
|
||||
padding=padding_strategy.value,
|
||||
pad_to_multiple_of=pad_to_multiple_of,
|
||||
return_attention_mask=return_attention_mask,
|
||||
)
|
||||
|
||||
if return_length:
|
||||
encoded_inputs["length"] = len(encoded_inputs["input_ids"])
|
||||
|
||||
batch_outputs = BatchEncoding(
|
||||
encoded_inputs, tensor_type=return_tensors, prepend_batch_axis=prepend_batch_axis
|
||||
)
|
||||
|
||||
return batch_outputs
|
||||
|
||||
def truncate_sequences(
|
||||
self,
|
||||
ids: List[int],
|
||||
pair_ids: Optional[List[int]] = None,
|
||||
num_tokens_to_remove: int = 0,
|
||||
truncation_strategy: Union[str, TruncationStrategy] = "longest_first",
|
||||
stride: int = 0,
|
||||
) -> Tuple[List[int], List[int], List[int]]:
|
||||
""" Truncates a sequence pair in place to the maximum length.
|
||||
|
||||
Args:
|
||||
ids: list of tokenized input ids. Can be obtained from a string by chaining the
|
||||
`tokenize` and `convert_tokens_to_ids` methods.
|
||||
pair_ids: Optional second list of input ids. Can be obtained from a string by chaining the
|
||||
`tokenize` and `convert_tokens_to_ids` methods.
|
||||
num_tokens_to_remove (:obj:`int`, `optional`, defaults to ``0``):
|
||||
number of tokens to remove using the truncation strategy
|
||||
truncation_strategy (:obj:`string`, `optional`, defaults to "longest_first"):
|
||||
String selected in the following options:
|
||||
|
||||
- 'longest_first' (default): Iteratively reduce the inputs sequence until the input is under max_length
|
||||
starting from the longest one at each token (when there is a pair of input sequences).
|
||||
Overflowing tokens only contains overflow from the first sequence.
|
||||
- 'only_first': Only truncate the first sequence. raise an error if the first sequence is shorter or equal to than num_tokens_to_remove.
|
||||
- 'only_second': Only truncate the second sequence
|
||||
- 'do_not_truncate'
|
||||
stride (:obj:`int`, `optional`, defaults to ``0``):
|
||||
If set to a number along with max_length, the overflowing tokens returned will contain some tokens
|
||||
from the main sequence returned. The value of this argument defines the number of additional tokens.
|
||||
"""
|
||||
if num_tokens_to_remove <= 0:
|
||||
return ids, pair_ids, []
|
||||
|
||||
if not isinstance(truncation_strategy, TruncationStrategy):
|
||||
truncation_strategy = TruncationStrategy(truncation_strategy)
|
||||
|
||||
overflowing_tokens = []
|
||||
if truncation_strategy == TruncationStrategy.LONGEST_FIRST:
|
||||
for _ in range(num_tokens_to_remove):
|
||||
if pair_ids is None or len(ids) > len(pair_ids):
|
||||
if not overflowing_tokens:
|
||||
window_len = min(len(ids), stride + 1)
|
||||
else:
|
||||
window_len = 1
|
||||
overflowing_tokens.extend(ids[-window_len:])
|
||||
ids = ids[:-1]
|
||||
else:
|
||||
if not overflowing_tokens:
|
||||
window_len = min(len(pair_ids), stride + 1)
|
||||
else:
|
||||
window_len = 1
|
||||
overflowing_tokens.extend(pair_ids[-window_len:])
|
||||
pair_ids = pair_ids[:-1]
|
||||
elif truncation_strategy == TruncationStrategy.ONLY_FIRST:
|
||||
if len(ids) > num_tokens_to_remove:
|
||||
window_len = min(len(ids), stride + num_tokens_to_remove)
|
||||
overflowing_tokens = ids[-window_len:]
|
||||
ids = ids[:-num_tokens_to_remove]
|
||||
else:
|
||||
logger.error(
|
||||
f"We need to remove {num_tokens_to_remove} to truncate the input"
|
||||
f"but the first sequence has a length {len(ids)}. "
|
||||
f"Please select another truncation strategy than {truncation_strategy}, "
|
||||
f"for instance 'longest_first' or 'only_second'."
|
||||
)
|
||||
elif truncation_strategy == TruncationStrategy.ONLY_SECOND and pair_ids is not None:
|
||||
if len(pair_ids) > num_tokens_to_remove:
|
||||
window_len = min(len(pair_ids), stride + num_tokens_to_remove)
|
||||
overflowing_tokens = pair_ids[-window_len:]
|
||||
pair_ids = pair_ids[:-num_tokens_to_remove]
|
||||
else:
|
||||
logger.error(
|
||||
f"We need to remove {num_tokens_to_remove} to truncate the input"
|
||||
f"but the second sequence has a length {len(pair_ids)}. "
|
||||
f"Please select another truncation strategy than {truncation_strategy}, "
|
||||
f"for instance 'longest_first' or 'only_first'."
|
||||
)
|
||||
|
||||
return (ids, pair_ids, overflowing_tokens)
|
||||
|
||||
def _pad(
|
||||
self,
|
||||
encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
|
||||
|
||||
+32
-20
@@ -1,7 +1,6 @@
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import shutil
|
||||
import warnings
|
||||
@@ -23,7 +22,14 @@ from .data.data_collator import DataCollator, default_data_collator
|
||||
from .file_utils import is_apex_available, is_torch_tpu_available
|
||||
from .modeling_utils import PreTrainedModel
|
||||
from .optimization import AdamW, get_linear_schedule_with_warmup
|
||||
from .trainer_utils import PREFIX_CHECKPOINT_DIR, EvalPrediction, PredictionOutput, TrainOutput, is_wandb_available
|
||||
from .trainer_utils import (
|
||||
PREFIX_CHECKPOINT_DIR,
|
||||
EvalPrediction,
|
||||
PredictionOutput,
|
||||
TrainOutput,
|
||||
is_wandb_available,
|
||||
set_seed,
|
||||
)
|
||||
from .training_args import TrainingArguments
|
||||
|
||||
|
||||
@@ -60,20 +66,6 @@ if is_wandb_available():
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def set_seed(seed: int):
|
||||
"""
|
||||
Helper function for reproducible behavior to set the seed in ``random``, ``numpy`` and ``torch``.
|
||||
|
||||
Args:
|
||||
seed (:obj:`int`): The seed to set.
|
||||
"""
|
||||
random.seed(seed)
|
||||
np.random.seed(seed)
|
||||
torch.manual_seed(seed)
|
||||
torch.cuda.manual_seed_all(seed)
|
||||
# ^^ safe to call this function even if cuda is not available
|
||||
|
||||
|
||||
@contextmanager
|
||||
def torch_distributed_zero_first(local_rank: int):
|
||||
"""
|
||||
@@ -493,6 +485,10 @@ class Trainer:
|
||||
else:
|
||||
epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=not self.is_local_master())
|
||||
|
||||
# Reset the past mems state at the beginning of each epoch if necessary.
|
||||
if self.args.past_index >= 0:
|
||||
self._past = None
|
||||
|
||||
for step, inputs in enumerate(epoch_iterator):
|
||||
|
||||
# Skip past any already trained steps if resuming training
|
||||
@@ -537,8 +533,8 @@ class Trainer:
|
||||
|
||||
self._log(logs)
|
||||
|
||||
if self.args.evaluate_during_training:
|
||||
self.evaluate()
|
||||
if self.args.evaluate_during_training and self.global_step % self.args.eval_steps == 0:
|
||||
self.evaluate()
|
||||
|
||||
if self.args.save_steps > 0 and self.global_step % self.args.save_steps == 0:
|
||||
# In all cases (even distributed/parallel), self.model is always a reference
|
||||
@@ -569,12 +565,15 @@ class Trainer:
|
||||
if self.args.max_steps > 0 and self.global_step > self.args.max_steps:
|
||||
train_iterator.close()
|
||||
break
|
||||
if self.args.tpu_metrics_debug:
|
||||
if self.args.tpu_metrics_debug or self.args.debug:
|
||||
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
|
||||
xm.master_print(met.metrics_report())
|
||||
|
||||
if self.tb_writer:
|
||||
self.tb_writer.close()
|
||||
if self.args.past_index and hasattr(self, "_past"):
|
||||
# Clean the state at the end of training
|
||||
delattr(self, "_past")
|
||||
|
||||
logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n")
|
||||
return TrainOutput(self.global_step, tr_loss / self.global_step)
|
||||
@@ -617,9 +616,15 @@ class Trainer:
|
||||
if isinstance(v, torch.Tensor):
|
||||
inputs[k] = v.to(self.args.device)
|
||||
|
||||
if self.args.past_index >= 0 and self._past is not None:
|
||||
inputs["mems"] = self._past
|
||||
|
||||
outputs = model(**inputs)
|
||||
loss = outputs[0] # model outputs are always tuple in transformers (see doc)
|
||||
|
||||
if self.args.past_index >= 0:
|
||||
self._past = outputs[self.args.past_index]
|
||||
|
||||
if self.args.n_gpu > 1:
|
||||
loss = loss.mean() # mean() to average on multi-gpu parallel training
|
||||
if self.args.gradient_accumulation_steps > 1:
|
||||
@@ -741,7 +746,7 @@ class Trainer:
|
||||
|
||||
self._log(output.metrics)
|
||||
|
||||
if self.args.tpu_metrics_debug:
|
||||
if self.args.tpu_metrics_debug or self.args.debug:
|
||||
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
|
||||
xm.master_print(met.metrics_report())
|
||||
|
||||
@@ -802,12 +807,17 @@ class Trainer:
|
||||
if is_torch_tpu_available():
|
||||
dataloader = pl.ParallelLoader(dataloader, [self.args.device]).per_device_loader(self.args.device)
|
||||
|
||||
if self.args.past_index >= 0:
|
||||
past = None
|
||||
|
||||
for inputs in tqdm(dataloader, desc=description):
|
||||
has_labels = any(inputs.get(k) is not None for k in ["labels", "lm_labels", "masked_lm_labels"])
|
||||
|
||||
for k, v in inputs.items():
|
||||
if isinstance(v, torch.Tensor):
|
||||
inputs[k] = v.to(self.args.device)
|
||||
if self.args.past_index >= 0:
|
||||
inputs["mems"] = past
|
||||
|
||||
with torch.no_grad():
|
||||
outputs = model(**inputs)
|
||||
@@ -816,6 +826,8 @@ class Trainer:
|
||||
eval_losses += [step_eval_loss.mean().item()]
|
||||
else:
|
||||
logits = outputs[0]
|
||||
if self.args.past_index >= 0:
|
||||
past = outputs[self.args.past_index if has_labels else self.args.past_index - 1]
|
||||
|
||||
if not prediction_loss_only:
|
||||
if preds is None:
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
from typing import Callable, Dict, Optional, Tuple
|
||||
|
||||
import numpy as np
|
||||
@@ -11,7 +10,7 @@ import tensorflow as tf
|
||||
|
||||
from .modeling_tf_utils import TFPreTrainedModel
|
||||
from .optimization_tf import GradientAccumulator, create_optimizer
|
||||
from .trainer_utils import PREFIX_CHECKPOINT_DIR, EvalPrediction, PredictionOutput, is_wandb_available
|
||||
from .trainer_utils import PREFIX_CHECKPOINT_DIR, EvalPrediction, PredictionOutput, is_wandb_available, set_seed
|
||||
from .training_args_tf import TFTrainingArguments
|
||||
|
||||
|
||||
@@ -22,12 +21,6 @@ if is_wandb_available():
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def set_seed(seed: int):
|
||||
random.seed(seed)
|
||||
np.random.seed(seed)
|
||||
tf.random.set_seed(seed)
|
||||
|
||||
|
||||
class TFTrainer:
|
||||
"""
|
||||
TFTrainer is a simple but feature-complete training and eval loop for TensorFlow,
|
||||
@@ -240,6 +233,10 @@ class TFTrainer:
|
||||
|
||||
step: int = 1
|
||||
|
||||
# Reset the past mems state at the beginning of the evaluation if necessary.
|
||||
if self.args.past_index >= 0:
|
||||
self._past = None
|
||||
|
||||
for features, labels in dataset:
|
||||
step = tf.convert_to_tensor(step, dtype=tf.int64)
|
||||
loss, logits = self._evaluate_steps(features, labels)
|
||||
@@ -252,7 +249,7 @@ class TFTrainer:
|
||||
if isinstance(labels, tuple):
|
||||
labels = labels[0]
|
||||
|
||||
if self.args.n_gpu > 1:
|
||||
if self.args.n_replicas > 1:
|
||||
for val in logits.values:
|
||||
if preds is None:
|
||||
preds = val.numpy()
|
||||
@@ -288,6 +285,10 @@ class TFTrainer:
|
||||
if not key.startswith("eval_"):
|
||||
metrics[f"eval_{key}"] = metrics.pop(key)
|
||||
|
||||
if self.args.past_index and hasattr(self, "_past"):
|
||||
# Clean the state at the end of training
|
||||
delattr(self, "_past")
|
||||
|
||||
return PredictionOutput(predictions=preds, label_ids=label_ids, metrics=metrics)
|
||||
|
||||
def _log(self, logs: Dict[str, float]) -> None:
|
||||
@@ -405,6 +406,9 @@ class TFTrainer:
|
||||
logger.info(" Total optimization steps = %d", t_total)
|
||||
|
||||
for epoch_iter in range(epochs_trained, int(epochs + 1)):
|
||||
# Reset the past mems state at the beginning of each epoch if necessary.
|
||||
if self.args.past_index >= 0:
|
||||
self._past = None
|
||||
for step, training_loss in enumerate(self._training_steps(train_ds, optimizer)):
|
||||
self.global_step = iterations.numpy()
|
||||
self.epoch_logging = epoch_iter - 1 + (step + 1) / steps_per_epoch
|
||||
@@ -444,6 +448,10 @@ class TFTrainer:
|
||||
if self.args.max_steps > 0 and self.global_step % self.args.max_steps == 0:
|
||||
break
|
||||
|
||||
if self.args.past_index and hasattr(self, "_past"):
|
||||
# Clean the state at the end of training
|
||||
delattr(self, "_past")
|
||||
|
||||
def _training_steps(self, ds, optimizer):
|
||||
"""
|
||||
Returns a generator over training steps (i.e. parameters update).
|
||||
@@ -518,11 +526,16 @@ class TFTrainer:
|
||||
labels: the batched labels.
|
||||
training: run the model in training mode or not
|
||||
"""
|
||||
if self.args.past_index >= 0 and getattr(self, "_past", None) is not None:
|
||||
features["mems"] = self._past
|
||||
if isinstance(labels, (dict)):
|
||||
loss, logits = self.model(features, training=training, **labels)[:2]
|
||||
outputs = self.model(features, training=training, **labels)[:2]
|
||||
else:
|
||||
loss, logits = self.model(features, labels=labels, training=training)[:2]
|
||||
loss += sum(self.model.losses) * (1.0 / self.args.n_gpu)
|
||||
outputs = self.model(features, labels=labels, training=training)[:2]
|
||||
loss, logits = outputs[:2]
|
||||
if self.args.past_index >= 0:
|
||||
self._past = outputs[self.args.past_index]
|
||||
loss += sum(self.model.losses) * (1.0 / self.args.n_replicas)
|
||||
|
||||
return loss, logits
|
||||
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import os
|
||||
import random
|
||||
from typing import Dict, NamedTuple, Optional
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .file_utils import is_tf_available, is_torch_available
|
||||
|
||||
|
||||
try:
|
||||
import wandb
|
||||
@@ -21,6 +24,28 @@ def is_wandb_available():
|
||||
return _has_wandb
|
||||
|
||||
|
||||
def set_seed(seed: int):
|
||||
"""
|
||||
Helper function for reproducible behavior to set the seed in ``random``, ``numpy``, ``torch`` and/or ``tf``
|
||||
(if installed).
|
||||
|
||||
Args:
|
||||
seed (:obj:`int`): The seed to set.
|
||||
"""
|
||||
random.seed(seed)
|
||||
np.random.seed(seed)
|
||||
if is_torch_available():
|
||||
import torch
|
||||
|
||||
torch.manual_seed(seed)
|
||||
torch.cuda.manual_seed_all(seed)
|
||||
# ^^ safe to call this function even if cuda is not available
|
||||
if is_tf_available():
|
||||
import tensorflow as tf
|
||||
|
||||
tf.random.set_seed(seed)
|
||||
|
||||
|
||||
class EvalPrediction(NamedTuple):
|
||||
"""
|
||||
Evaluation output (always contains labels), to be used to compute metrics.
|
||||
|
||||
@@ -97,11 +97,18 @@ class TrainingArguments:
|
||||
During distributed training, the rank of the process.
|
||||
tpu_num_cores (:obj:`int`, `optional`):
|
||||
When training on TPU, the mumber of TPU cores (automatically passed by launcher script).
|
||||
tpu_metrics_debug (:obj:`bool`, `optional`, defaults to :obj:`False`):
|
||||
debug (:obj:`bool`, `optional`, defaults to :obj:`False`):
|
||||
When training on TPU, whether to print debug metrics or not.
|
||||
dataloader_drop_last (:obj:`bool`, `optional`, defaults to :obj:`False`):
|
||||
Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size)
|
||||
or not.
|
||||
eval_steps (:obj:`int`, `optional`, defaults to 1000):
|
||||
Number of update steps between two evaluations.
|
||||
past_index (:obj:`int`, `optional`, defaults to -1):
|
||||
Some models like :doc:`TransformerXL <../model_doc/transformerxl>` or :doc`XLNet <../model_doc/xlnet>` can
|
||||
make use of the past hidden states for their predictions. If this argument is set to a positive int, the
|
||||
``Trainer`` will use the corresponding output (usually index 2) as the past state and feed it to the model
|
||||
at the next training step under the keyword argument ``mems``.
|
||||
"""
|
||||
|
||||
output_dir: str = field(
|
||||
@@ -197,11 +204,21 @@ class TrainingArguments:
|
||||
tpu_num_cores: Optional[int] = field(
|
||||
default=None, metadata={"help": "TPU: Number of TPU cores (automatically passed by launcher script)"}
|
||||
)
|
||||
tpu_metrics_debug: bool = field(default=False, metadata={"help": "TPU: Whether to print debug metrics"})
|
||||
tpu_metrics_debug: bool = field(
|
||||
default=False,
|
||||
metadata={"help": "Deprecated, the use of `--debug` is preferred. TPU: Whether to print debug metrics"},
|
||||
)
|
||||
debug: bool = field(default=False, metadata={"help": "Whether to print debug metrics on TPU"})
|
||||
|
||||
dataloader_drop_last: bool = field(
|
||||
default=False, metadata={"help": "Drop the last incomplete batch if it is not divisible by the batch size."}
|
||||
)
|
||||
eval_steps: int = field(default=1000, metadata={"help": "Run an evaluation every X steps."})
|
||||
|
||||
past_index: int = field(
|
||||
default=-1,
|
||||
metadata={"help": "If >=0, uses the corresponding part of the output as the past state for next step."},
|
||||
)
|
||||
|
||||
@property
|
||||
def train_batch_size(self) -> int:
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import logging
|
||||
import warnings
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Tuple
|
||||
|
||||
@@ -80,26 +81,25 @@ class TFTrainingArguments(TrainingArguments):
|
||||
During distributed training, the rank of the process.
|
||||
tpu_num_cores (:obj:`int`, `optional`):
|
||||
When training on TPU, the mumber of TPU cores (automatically passed by launcher script).
|
||||
tpu_metrics_debug (:obj:`bool`, `optional`, defaults to :obj:`False`):
|
||||
When training on TPU, whether to print debug metrics or not.
|
||||
debug (:obj:`bool`, `optional`, defaults to :obj:`False`):
|
||||
Wheter to activate the trace to record computation graphs and profiling information or not.
|
||||
dataloader_drop_last (:obj:`bool`, `optional`, defaults to :obj:`False`):
|
||||
Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size)
|
||||
or not.
|
||||
tpu_name (:obj:`str`, `optional`):
|
||||
The name of the TPU the process is running on.
|
||||
eval_steps (:obj:`int`, `optional`, defaults to 1000):
|
||||
Number of update steps before two evaluations.
|
||||
debug (:obj:`bool`, `optional`, defaults to :obj:`False`):
|
||||
Wheter to activate the trace to record computation graphs and profiling information or not.
|
||||
past_index (:obj:`int`, `optional`, defaults to -1):
|
||||
Some models like :doc:`TransformerXL <../model_doc/transformerxl>` or :doc`XLNet <../model_doc/xlnet>` can
|
||||
make use of the past hidden states for their predictions. If this argument is set to a positive int, the
|
||||
``Trainer`` will use the corresponding output (usually index 2) as the past state and feed it to the model
|
||||
at the next training step under the keyword argument ``mems``.
|
||||
tpu_name (:obj:`str`, `optional`):
|
||||
The name of the TPU the process is running on.
|
||||
"""
|
||||
|
||||
tpu_name: str = field(
|
||||
default=None, metadata={"help": "Name of TPU"},
|
||||
)
|
||||
eval_steps: int = field(default=1000, metadata={"help": "Run an evaluation every X steps."})
|
||||
debug: bool = field(
|
||||
default=False, metadata={"help": "Activate the trace to record computation graphs and profiling information"}
|
||||
)
|
||||
|
||||
@cached_property
|
||||
@tf_required
|
||||
@@ -145,8 +145,46 @@ class TFTrainingArguments(TrainingArguments):
|
||||
|
||||
@property
|
||||
@tf_required
|
||||
def n_gpu(self) -> int:
|
||||
def n_replicas(self) -> int:
|
||||
"""
|
||||
The number of replicas (GPUs or TPU cores) used in this training.
|
||||
The number of replicas (CPUs, GPUs or TPU cores) used in this training.
|
||||
"""
|
||||
return self._setup_strategy.num_replicas_in_sync
|
||||
|
||||
@property
|
||||
def train_batch_size(self) -> int:
|
||||
"""
|
||||
The actual batch size for training (may differ from :obj:`per_gpu_train_batch_size` in distributed training).
|
||||
"""
|
||||
if self.per_gpu_train_batch_size:
|
||||
logger.warning(
|
||||
"Using deprecated `--per_gpu_train_batch_size` argument which will be removed in a future "
|
||||
"version. Using `--per_device_train_batch_size` is preferred."
|
||||
)
|
||||
per_device_batch_size = self.per_gpu_train_batch_size or self.per_device_train_batch_size
|
||||
return per_device_batch_size * max(1, self.n_replicas)
|
||||
|
||||
@property
|
||||
def eval_batch_size(self) -> int:
|
||||
"""
|
||||
The actual batch size for evaluation (may differ from :obj:`per_gpu_eval_batch_size` in distributed training).
|
||||
"""
|
||||
if self.per_gpu_eval_batch_size:
|
||||
logger.warning(
|
||||
"Using deprecated `--per_gpu_eval_batch_size` argument which will be removed in a future "
|
||||
"version. Using `--per_device_eval_batch_size` is preferred."
|
||||
)
|
||||
per_device_batch_size = self.per_gpu_eval_batch_size or self.per_device_eval_batch_size
|
||||
return per_device_batch_size * max(1, self.n_replicas)
|
||||
|
||||
@property
|
||||
@tf_required
|
||||
def n_gpu(self) -> int:
|
||||
"""
|
||||
The number of replicas (CPUs, GPUs or TPU cores) used in this training.
|
||||
"""
|
||||
warnings.warn(
|
||||
"The n_gpu argument is deprecated and will be removed in a future version, use n_replicas instead.",
|
||||
FutureWarning,
|
||||
)
|
||||
return self._setup_strategy.num_replicas_in_sync
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_torch_available
|
||||
|
||||
from .utils import require_torch
|
||||
from transformers.testing_utils import require_torch
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
@@ -4,8 +4,7 @@ import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from transformers import AutoConfig, is_torch_available
|
||||
|
||||
from .utils import require_torch, torch_device
|
||||
from transformers.testing_utils import require_torch, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
@@ -4,8 +4,7 @@ import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from transformers import AutoConfig, is_tf_available
|
||||
|
||||
from .utils import require_tf
|
||||
from transformers.testing_utils import require_tf
|
||||
|
||||
|
||||
if is_tf_available():
|
||||
|
||||
@@ -19,8 +19,7 @@ import unittest
|
||||
from transformers.configuration_auto import CONFIG_MAPPING, AutoConfig
|
||||
from transformers.configuration_bert import BertConfig
|
||||
from transformers.configuration_roberta import RobertaConfig
|
||||
|
||||
from .utils import DUMMY_UNKWOWN_IDENTIFIER
|
||||
from transformers.testing_utils import DUMMY_UNKWOWN_IDENTIFIER
|
||||
|
||||
|
||||
SAMPLE_ROBERTA_CONFIG = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures/dummy-config.json")
|
||||
|
||||
@@ -21,8 +21,7 @@ from pathlib import Path
|
||||
from typing import List, Union
|
||||
|
||||
import transformers
|
||||
|
||||
from .utils import require_tf, require_torch, slow
|
||||
from transformers.testing_utils import require_tf, require_torch, slow
|
||||
|
||||
|
||||
logger = logging.getLogger()
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_torch_available
|
||||
from transformers.testing_utils import require_torch, slow, torch_device
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_common import ModelTesterMixin, ids_tensor
|
||||
from .utils import require_torch, slow, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
@@ -17,8 +17,7 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_torch_available
|
||||
|
||||
from .utils import DUMMY_UNKWOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, require_torch, slow
|
||||
from transformers.testing_utils import DUMMY_UNKWOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, require_torch, slow
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
@@ -20,10 +20,10 @@ import timeout_decorator # noqa
|
||||
|
||||
from transformers import is_torch_available
|
||||
from transformers.file_utils import cached_property
|
||||
from transformers.testing_utils import require_torch, slow, torch_device
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_common import ModelTesterMixin, ids_tensor
|
||||
from .utils import require_torch, slow, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_torch_available
|
||||
from transformers.testing_utils import require_torch, slow, torch_device
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
|
||||
from .utils import require_torch, slow, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
@@ -16,8 +16,7 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_torch_available
|
||||
|
||||
from .utils import require_torch, slow, torch_device
|
||||
from transformers.testing_utils import require_torch, slow, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
@@ -21,8 +21,7 @@ import unittest
|
||||
from typing import List
|
||||
|
||||
from transformers import is_torch_available
|
||||
|
||||
from .utils import require_multigpu, require_torch, slow, torch_device
|
||||
from transformers.testing_utils import require_multigpu, require_torch, slow, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
@@ -812,7 +811,7 @@ class ModelTesterMixin:
|
||||
# Wrap model in nn.DataParallel
|
||||
model = torch.nn.DataParallel(model)
|
||||
with torch.no_grad():
|
||||
_ = model(**inputs_dict)
|
||||
_ = model(**self._prepare_for_class(inputs_dict, model_class))
|
||||
|
||||
|
||||
global_rng = random.Random()
|
||||
|
||||
@@ -16,10 +16,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_torch_available
|
||||
from transformers.testing_utils import require_torch, slow, torch_device
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_common import ModelTesterMixin, ids_tensor
|
||||
from .utils import require_torch, slow, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_torch_available
|
||||
from transformers.testing_utils import require_torch, torch_device
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_common import ModelTesterMixin, ids_tensor
|
||||
from .utils import require_torch, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_torch_available
|
||||
from transformers.testing_utils import require_torch, slow, torch_device
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_common import ModelTesterMixin, ids_tensor
|
||||
from .utils import require_torch, slow, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
@@ -18,12 +18,12 @@ import tempfile
|
||||
import unittest
|
||||
|
||||
from transformers import is_torch_available
|
||||
from transformers.testing_utils import require_torch, slow, torch_device
|
||||
|
||||
# TODO(PVP): this line reruns all the tests in BertModelTest; not sure whether this can be prevented
|
||||
# for now only run module with pytest tests/test_modeling_encoder_decoder.py::EncoderDecoderModelTest
|
||||
from .test_modeling_bert import BertModelTester
|
||||
from .test_modeling_common import ids_tensor
|
||||
from .utils import require_torch, slow, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_torch_available
|
||||
from transformers.testing_utils import require_torch, slow, torch_device
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_common import ModelTesterMixin, ids_tensor
|
||||
from .utils import require_torch, slow, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_torch_available
|
||||
from transformers.testing_utils import require_torch, slow, torch_device
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_common import ModelTesterMixin, ids_tensor
|
||||
from .utils import require_torch, slow, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_torch_available
|
||||
from transformers.testing_utils import require_torch, slow, torch_device
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_common import ModelTesterMixin, ids_tensor
|
||||
from .utils import require_torch, slow, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
@@ -115,6 +115,18 @@ class LongformerModelTester:
|
||||
def check_loss_output(self, result):
|
||||
self.parent.assertListEqual(list(result["loss"].size()), [])
|
||||
|
||||
def create_and_check_attention_mask_determinism(
|
||||
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
||||
):
|
||||
model = LongformerModel(config=config)
|
||||
model.to(torch_device)
|
||||
model.eval()
|
||||
|
||||
attention_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
|
||||
output_with_mask = model(input_ids, attention_mask=attention_mask)[0]
|
||||
output_without_mask = model(input_ids)[0]
|
||||
self.parent.assertTrue(torch.allclose(output_with_mask[0, 0, :5], output_without_mask[0, 0, :5], atol=1e-4))
|
||||
|
||||
def create_and_check_longformer_model(
|
||||
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
||||
):
|
||||
@@ -134,6 +146,36 @@ class LongformerModelTester:
|
||||
)
|
||||
self.parent.assertListEqual(list(result["pooled_output"].size()), [self.batch_size, self.hidden_size])
|
||||
|
||||
def create_and_check_longformer_model_with_global_attention_mask(
|
||||
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
||||
):
|
||||
model = LongformerModel(config=config)
|
||||
model.to(torch_device)
|
||||
model.eval()
|
||||
global_attention_mask = input_mask.clone()
|
||||
global_attention_mask[:, input_mask.shape[-1] // 2] = 0
|
||||
global_attention_mask = global_attention_mask.to(torch_device)
|
||||
|
||||
sequence_output, pooled_output = model(
|
||||
input_ids,
|
||||
attention_mask=input_mask,
|
||||
global_attention_mask=global_attention_mask,
|
||||
token_type_ids=token_type_ids,
|
||||
)
|
||||
sequence_output, pooled_output = model(
|
||||
input_ids, token_type_ids=token_type_ids, global_attention_mask=global_attention_mask
|
||||
)
|
||||
sequence_output, pooled_output = model(input_ids, global_attention_mask=global_attention_mask)
|
||||
|
||||
result = {
|
||||
"sequence_output": sequence_output,
|
||||
"pooled_output": pooled_output,
|
||||
}
|
||||
self.parent.assertListEqual(
|
||||
list(result["sequence_output"].size()), [self.batch_size, self.seq_length, self.hidden_size]
|
||||
)
|
||||
self.parent.assertListEqual(list(result["pooled_output"].size()), [self.batch_size, self.hidden_size])
|
||||
|
||||
def create_and_check_longformer_for_masked_lm(
|
||||
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
||||
):
|
||||
@@ -243,7 +285,13 @@ class LongformerModelTester:
|
||||
token_labels,
|
||||
choice_labels,
|
||||
) = config_and_inputs
|
||||
inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
|
||||
global_attention_mask = torch.zeros_like(input_ids)
|
||||
inputs_dict = {
|
||||
"input_ids": input_ids,
|
||||
"token_type_ids": token_type_ids,
|
||||
"attention_mask": input_mask,
|
||||
"global_attention_mask": global_attention_mask,
|
||||
}
|
||||
return config, inputs_dict
|
||||
|
||||
def prepare_config_and_inputs_for_question_answering(self):
|
||||
@@ -277,11 +325,10 @@ class LongformerModelTest(ModelTesterMixin, unittest.TestCase):
|
||||
(
|
||||
LongformerModel,
|
||||
LongformerForMaskedLM,
|
||||
# TODO: make tests pass for those models
|
||||
# LongformerForSequenceClassification,
|
||||
# LongformerForQuestionAnswering,
|
||||
# LongformerForTokenClassification,
|
||||
# LongformerForMultipleChoice,
|
||||
LongformerForSequenceClassification,
|
||||
LongformerForQuestionAnswering,
|
||||
LongformerForTokenClassification,
|
||||
LongformerForMultipleChoice,
|
||||
)
|
||||
if is_torch_available()
|
||||
else ()
|
||||
@@ -298,6 +345,14 @@ class LongformerModelTest(ModelTesterMixin, unittest.TestCase):
|
||||
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
||||
self.model_tester.create_and_check_longformer_model(*config_and_inputs)
|
||||
|
||||
def test_longformer_model_attention_mask_determinism(self):
|
||||
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
||||
self.model_tester.create_and_check_attention_mask_determinism(*config_and_inputs)
|
||||
|
||||
def test_longformer_model_global_attention_mask(self):
|
||||
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
||||
self.model_tester.create_and_check_longformer_model_with_global_attention_mask(*config_and_inputs)
|
||||
|
||||
def test_longformer_for_masked_lm(self):
|
||||
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
||||
self.model_tester.create_and_check_longformer_for_masked_lm(*config_and_inputs)
|
||||
@@ -325,15 +380,31 @@ class LongformerModelIntegrationTest(unittest.TestCase):
|
||||
model = LongformerModel.from_pretrained("allenai/longformer-base-4096")
|
||||
model.to(torch_device)
|
||||
|
||||
# 'Hello world!'
|
||||
input_ids = torch.tensor([[0, 20920, 232, 328, 1437, 2]], dtype=torch.long, device=torch_device)
|
||||
attention_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
|
||||
output = model(input_ids, attention_mask=attention_mask)[0]
|
||||
output_without_mask = model(input_ids)[0]
|
||||
|
||||
expected_output_slice = torch.tensor([0.0549, 0.1087, -0.1119, -0.0368, 0.0250], device=torch_device)
|
||||
self.assertTrue(torch.allclose(output[0, 0, -5:], expected_output_slice, atol=1e-4))
|
||||
self.assertTrue(torch.allclose(output_without_mask[0, 0, -5:], expected_output_slice, atol=1e-4))
|
||||
|
||||
@slow
|
||||
def test_inference_no_head_long(self):
|
||||
model = LongformerModel.from_pretrained("allenai/longformer-base-4096")
|
||||
model.to(torch_device)
|
||||
|
||||
# 'Hello world! ' repeated 1000 times
|
||||
input_ids = torch.tensor(
|
||||
[[0] + [20920, 232, 328, 1437] * 1000 + [2]], dtype=torch.long, device=torch_device
|
||||
) # long input
|
||||
|
||||
attention_mask = torch.ones(input_ids.shape, dtype=torch.long, device=input_ids.device)
|
||||
attention_mask[:, [1, 4, 21]] = 2 # Set global attention on a few random positions
|
||||
global_attention_mask = torch.zeros(input_ids.shape, dtype=torch.long, device=input_ids.device)
|
||||
global_attention_mask[:, [1, 4, 21]] = 1 # Set global attention on a few random positions
|
||||
|
||||
output = model(input_ids, attention_mask=attention_mask)[0]
|
||||
output = model(input_ids, attention_mask=attention_mask, global_attention_mask=global_attention_mask)[0]
|
||||
|
||||
expected_output_sum = torch.tensor(74585.8594, device=torch_device)
|
||||
expected_output_mean = torch.tensor(0.0243, device=torch_device)
|
||||
@@ -341,7 +412,7 @@ class LongformerModelIntegrationTest(unittest.TestCase):
|
||||
self.assertTrue(torch.allclose(output.mean(), expected_output_mean, atol=1e-4))
|
||||
|
||||
@slow
|
||||
def test_inference_masked_lm(self):
|
||||
def test_inference_masked_lm_long(self):
|
||||
model = LongformerForMaskedLM.from_pretrained("allenai/longformer-base-4096")
|
||||
model.to(torch_device)
|
||||
|
||||
@@ -352,9 +423,9 @@ class LongformerModelIntegrationTest(unittest.TestCase):
|
||||
|
||||
loss, prediction_scores = model(input_ids, labels=input_ids)
|
||||
|
||||
expected_loss = torch.tensor(0.0620, device=torch_device)
|
||||
expected_prediction_scores_sum = torch.tensor(-6.1599e08, device=torch_device)
|
||||
expected_prediction_scores_mean = torch.tensor(-3.0622, device=torch_device)
|
||||
expected_loss = torch.tensor(0.0074, device=torch_device)
|
||||
expected_prediction_scores_sum = torch.tensor(-6.1048e08, device=torch_device)
|
||||
expected_prediction_scores_mean = torch.tensor(-3.0348, device=torch_device)
|
||||
input_ids = input_ids.to(torch_device)
|
||||
|
||||
self.assertTrue(torch.allclose(loss, expected_loss, atol=1e-4))
|
||||
|
||||
@@ -19,8 +19,7 @@ import unittest
|
||||
from transformers import is_torch_available
|
||||
from transformers.file_utils import cached_property
|
||||
from transformers.hf_api import HfApi
|
||||
|
||||
from .utils import require_torch, slow, torch_device
|
||||
from transformers.testing_utils import require_torch, slow, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_torch_available
|
||||
from transformers.testing_utils import require_torch, slow, torch_device
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
|
||||
from .utils import require_torch, slow, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_torch_available
|
||||
from transformers.testing_utils import require_torch, slow, torch_device
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_common import ModelTesterMixin, ids_tensor
|
||||
from .utils import require_torch, slow, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
+782
-28
@@ -15,11 +15,19 @@
|
||||
|
||||
import unittest
|
||||
|
||||
import gin
|
||||
import jax
|
||||
import numpy as np
|
||||
|
||||
# trax imports - to be deleted later
|
||||
import trax
|
||||
from transformers import is_torch_available
|
||||
from transformers.testing_utils import require_torch, slow, torch_device
|
||||
from trax import shapes
|
||||
from trax.shapes import ShapeDtype as trax_ShapeDtype
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
|
||||
from .utils import require_multigpu, require_torch, slow, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
@@ -27,8 +35,10 @@ if is_torch_available():
|
||||
ReformerConfig,
|
||||
ReformerModel,
|
||||
ReformerModelWithLMHead,
|
||||
ReformerForMaskedLM,
|
||||
ReformerTokenizer,
|
||||
ReformerLayer,
|
||||
ReformerAttention,
|
||||
REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
|
||||
)
|
||||
import torch
|
||||
@@ -388,16 +398,6 @@ class ReformerModelTester:
|
||||
output = model.generate(input_ids, attention_mask=input_mask, do_sample=False)
|
||||
self.parent.assertFalse(torch.isnan(output).any().item())
|
||||
|
||||
def create_and_check_reformer_no_chunking(self, config, input_ids, input_mask):
|
||||
# force chunk length to be bigger than input_ids
|
||||
config.lsh_attn_chunk_length = 2 * input_ids.shape[-1]
|
||||
config.local_attn_chunk_length = 2 * input_ids.shape[-1]
|
||||
model = ReformerModelWithLMHead(config=config)
|
||||
model.to(torch_device)
|
||||
model.eval()
|
||||
output_logits = model(input_ids, attention_mask=input_mask)[0]
|
||||
self.parent.assertTrue(output_logits.shape[1] == input_ids.shape[-1])
|
||||
|
||||
def prepare_config_and_inputs_for_common(self):
|
||||
config_and_inputs = self.prepare_config_and_inputs()
|
||||
(config, input_ids, input_mask,) = config_and_inputs
|
||||
@@ -443,10 +443,6 @@ class ReformerTesterMixin:
|
||||
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
||||
self.model_tester.create_and_check_reformer_feed_backward_chunking(*config_and_inputs)
|
||||
|
||||
def test_reformer_no_chunking(self):
|
||||
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
||||
self.model_tester.create_and_check_reformer_no_chunking(*config_and_inputs)
|
||||
|
||||
@slow
|
||||
def test_dropout_random_seed_is_changing(self):
|
||||
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
||||
@@ -462,14 +458,9 @@ class ReformerTesterMixin:
|
||||
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
||||
self.model_tester.create_and_check_reformer_model_fp16_generate(*config_and_inputs)
|
||||
|
||||
@require_multigpu
|
||||
def test_multigpu_data_parallel_forward(self):
|
||||
# Opt-out of this test.
|
||||
pass
|
||||
|
||||
|
||||
@require_torch
|
||||
class ReformerLocalAttnModelTest(ReformerTesterMixin, ModelTesterMixin, unittest.TestCase):
|
||||
class ReformerLocalAttnModelTest(ModelTesterMixin, ReformerTesterMixin, unittest.TestCase):
|
||||
all_model_classes = (ReformerModel, ReformerModelWithLMHead) if is_torch_available() else ()
|
||||
all_generative_model_classes = (ReformerModelWithLMHead,) if is_torch_available() else ()
|
||||
test_pruning = False
|
||||
@@ -517,13 +508,13 @@ class ReformerLocalAttnModelTest(ReformerTesterMixin, ModelTesterMixin, unittest
|
||||
|
||||
@slow
|
||||
def test_model_from_pretrained(self):
|
||||
for model_name in REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
|
||||
for model_name in list(REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST)[:1]:
|
||||
model = ReformerModelWithLMHead.from_pretrained(model_name)
|
||||
self.assertIsNotNone(model)
|
||||
|
||||
|
||||
@require_torch
|
||||
class ReformerLSHAttnModelTest(ReformerTesterMixin, ModelTesterMixin, unittest.TestCase):
|
||||
class ReformerLSHAttnModelTest(ModelTesterMixin, unittest.TestCase, ReformerTesterMixin):
|
||||
all_model_classes = (ReformerModel, ReformerModelWithLMHead) if is_torch_available() else ()
|
||||
all_generative_model_classes = (ReformerModelWithLMHead,) if is_torch_available() else ()
|
||||
test_pruning = False
|
||||
@@ -786,7 +777,6 @@ class ReformerIntegrationTests(unittest.TestCase):
|
||||
|
||||
def test_lsh_layer_forward(self):
|
||||
config = self._get_basic_config_and_input()
|
||||
config["lsh_num_chunks_before"] = 0
|
||||
config["attn_layers"] = ["lsh"]
|
||||
config["is_decoder"] = False
|
||||
hidden_states = self._get_hidden_states()
|
||||
@@ -802,7 +792,6 @@ class ReformerIntegrationTests(unittest.TestCase):
|
||||
|
||||
def test_lsh_layer_forward_complex(self):
|
||||
config = self._get_basic_config_and_input()
|
||||
config["lsh_num_chunks_before"] = 0
|
||||
config["attn_layers"] = ["lsh"]
|
||||
config["num_buckets"] = [2, 4]
|
||||
attn_mask = self._get_attn_mask()
|
||||
@@ -821,7 +810,6 @@ class ReformerIntegrationTests(unittest.TestCase):
|
||||
|
||||
def test_local_layer_forward(self):
|
||||
config = self._get_basic_config_and_input()
|
||||
config["local_num_chunks_before"] = 0
|
||||
config["attn_layers"] = ["local"]
|
||||
config["is_decoder"] = False
|
||||
hidden_states = self._get_hidden_states()
|
||||
@@ -837,7 +825,6 @@ class ReformerIntegrationTests(unittest.TestCase):
|
||||
|
||||
def test_local_layer_forward_complex(self):
|
||||
config = self._get_basic_config_and_input()
|
||||
config["local_num_chunks_before"] = 0
|
||||
config["attn_layers"] = ["local"]
|
||||
attn_mask = self._get_attn_mask()
|
||||
hidden_states = self._get_hidden_states()
|
||||
@@ -847,7 +834,7 @@ class ReformerIntegrationTests(unittest.TestCase):
|
||||
reformer_output = layer(prev_attn_output=hidden_states, hidden_states=hidden_states, attention_mask=attn_mask,)
|
||||
output_slice = reformer_output.hidden_states[0, 0, :5]
|
||||
expected_output_slice = torch.tensor(
|
||||
[1.4750, -2.0235, -0.9743, 1.4463, -0.1269], dtype=torch.float, device=torch_device,
|
||||
[1.5476, -1.9020, -0.9902, 1.5013, -0.1950], dtype=torch.float, device=torch_device,
|
||||
)
|
||||
self.assertTrue(torch.allclose(output_slice, expected_output_slice, atol=1e-3))
|
||||
|
||||
@@ -976,3 +963,770 @@ class ReformerIntegrationTests(unittest.TestCase):
|
||||
output_text,
|
||||
"A few months later state expression in his ideas, at the first entrance. He was positively for an inst",
|
||||
)
|
||||
|
||||
|
||||
@require_torch
|
||||
class ReformerIntegrationTestsDynamic(unittest.TestCase):
|
||||
# This code has to be used with patrickvonplaten's fork of trax to work
|
||||
def test_lsh_layer(self):
|
||||
config = ReformerConfig(hash_seed=0)
|
||||
config.is_decoder = False
|
||||
config.num_buckets = 32
|
||||
config.lsh_attn_chunk_length = 128
|
||||
config.num_attention_heads = 2
|
||||
shape = (3, 256, config.hidden_size) # Batch x SeqLen x hiddenSize
|
||||
np_input = np.random.rand(*shape)
|
||||
|
||||
mask = np.ones(shape[:-1], dtype=np.int32)
|
||||
mask[:, -10:] = 0
|
||||
hf_mask = torch.tensor(mask)
|
||||
|
||||
trax_layer = self.load_lsh_layer(config, "eval")
|
||||
input_signature = shapes.signature([np_input, mask])
|
||||
trax_weights, trax_state = trax_layer.init(input_signature)
|
||||
|
||||
trax_output = trax_layer([np_input, mask], weights=trax_weights, state=trax_state)
|
||||
|
||||
trax_torch_output = torch.tensor(np.asarray(trax_output))
|
||||
|
||||
hf_input = torch.tensor(np_input, dtype=torch.float)
|
||||
config.attn_layers = ["lsh"]
|
||||
hf_layer = ReformerAttention(config)
|
||||
self._set_layer_weights_in_torch_lsh(trax_weights, hf_layer, config.hidden_size)
|
||||
hf_layer.eval()
|
||||
|
||||
hf_attention_all_heads = hf_layer.self_attention(hf_input, attention_mask=hf_mask)[0]
|
||||
hf_output = hf_layer.output(hf_attention_all_heads)
|
||||
|
||||
self.assertTrue(torch.allclose(hf_output, trax_torch_output, atol=1e-3))
|
||||
|
||||
def test_local_layer(self):
|
||||
config = ReformerConfig(hash_seed=0)
|
||||
config.is_decoder = False
|
||||
shape = (1, 128, config.hidden_size) # Batch x SeqLen x hiddenSize
|
||||
np_input = np.random.rand(*shape)
|
||||
|
||||
trax_layer = self.load_local_layer(config)
|
||||
mask = np.ones(shape[:-1], dtype=np.int32)
|
||||
mask[:, -10:] = 0
|
||||
|
||||
hf_mask = torch.tensor(mask)
|
||||
|
||||
input_signature = shapes.signature([np_input, mask])
|
||||
trax_weights, trax_state = trax_layer.init(input_signature)
|
||||
|
||||
trax_output = trax_layer([np_input, mask], weights=trax_weights, state=trax_state)
|
||||
|
||||
hf_input = torch.tensor(np_input, dtype=torch.float)
|
||||
config.attn_layers = ["local"]
|
||||
hf_layer = ReformerAttention(config)
|
||||
self._set_layer_weights_in_torch_local(trax_weights, hf_layer, config.hidden_size)
|
||||
hf_layer.eval()
|
||||
|
||||
hf_attention_all_heads = hf_layer.self_attention(hf_input, attention_mask=hf_mask)[0]
|
||||
hf_output = hf_layer.output(hf_attention_all_heads)
|
||||
|
||||
trax_torch_output = torch.tensor(np.asarray(trax_output))
|
||||
self.assertTrue(torch.allclose(hf_output, trax_torch_output, atol=1e-3))
|
||||
|
||||
def test_reformer_lm_model(self):
|
||||
config = ReformerConfig(
|
||||
axial_pos_embds=True,
|
||||
hash_seed=0,
|
||||
is_decoder=False,
|
||||
axial_pos_shape=[32, 16],
|
||||
axial_pos_embds_dim=[64, 192],
|
||||
attn_layers=["local", "local", "local", "local"],
|
||||
# attn_layers=["lsh", "lsh", "lsh", "lsh"],
|
||||
local_attention_probs_dropout_prob=0.0,
|
||||
lsh_attention_probs_dropout_prob=0.0,
|
||||
hidden_dropout_prob=0.0,
|
||||
num_buckets=8,
|
||||
num_attention_heads=1,
|
||||
)
|
||||
|
||||
shape = (1, 512) # Batch x SeqLen x ModelDimPerHead
|
||||
|
||||
np_input = np.random.randint(0, config.vocab_size, size=shape)
|
||||
mask = np.ones_like(np_input, dtype=np.float32)
|
||||
mask[:, -10:] = 0
|
||||
np_zeros = np.zeros((shape[0], 1), dtype=np.int)
|
||||
attention_mask = torch.tensor(mask)
|
||||
|
||||
# choose one of the following two. "train" tests gradients. "test" tests forward only.
|
||||
mode = "train"
|
||||
# mode = "eval"
|
||||
|
||||
trax_model = self.load_reformer_lm_model(config, mode=mode)
|
||||
|
||||
if mode == "train":
|
||||
np_input_2 = np.asarray(np_input, np.float32)
|
||||
trax_model = trax.layers.Serial(trax_model, trax.layers.CrossEntropyLoss())
|
||||
input_signature = shapes.signature([np_input, np_input_2, mask])
|
||||
trax_weights, trax_state = trax_model.init(input_signature)
|
||||
trax_input = [np_input, np_input_2, mask]
|
||||
torch_trax_weights = trax_weights[0]
|
||||
else:
|
||||
input_signature = shapes.signature([np_input, mask])
|
||||
trax_weights, trax_state = trax_model.init(input_signature)
|
||||
trax_input = np_input
|
||||
trax_output = trax_model([np_input, mask], weights=trax_weights, state=trax_state)
|
||||
trax_torch_output = torch.tensor(np.asarray(trax_output[0]))
|
||||
torch_trax_weights = trax_weights
|
||||
|
||||
hf_input = torch.cat([torch.tensor(np_zeros), torch.tensor(np_input[:, :-1])], dim=-1)
|
||||
if mode == "train":
|
||||
hf_labels = (-100 * (1 - attention_mask) + torch.tensor(np_input) * attention_mask).to(dtype=torch.long)
|
||||
|
||||
hf_model = ReformerForMaskedLM(config)
|
||||
self._set_model_weights_in_torch(torch_trax_weights, hf_model, config.hidden_size)
|
||||
|
||||
if mode == "train":
|
||||
# uncomment line to fix hf_input_shifting in ReformerWithLMHead
|
||||
hf_model.train()
|
||||
# Trax does not really use attention masks in their layers in this setup. The just
|
||||
# mask the final loss
|
||||
loss = hf_model(hf_input, labels=hf_labels)[0]
|
||||
else:
|
||||
hf_output = hf_model(hf_input, attention_mask=attention_mask)
|
||||
hf_output = torch.nn.functional.log_softmax(hf_output[0], dim=-1)
|
||||
self.assertTrue(torch.allclose(hf_output, trax_torch_output, atol=1e-4))
|
||||
|
||||
if mode == "train":
|
||||
hf_model.zero_grad()
|
||||
loss.backward()
|
||||
|
||||
def model_and_loss_call(weights, batch, state):
|
||||
res = trax_model(batch, weights=weights, state=state)
|
||||
return res, trax_model.state
|
||||
|
||||
grad_fn = jax.grad(model_and_loss_call, has_aux=True)
|
||||
grads, state = grad_fn(trax_weights, trax_input, trax_state)
|
||||
|
||||
all_test_correct = self._set_model_weights_in_torch(
|
||||
grads[0], hf_model, config.hidden_size, set_params=False
|
||||
)
|
||||
self.assertTrue(all_test_correct)
|
||||
|
||||
def test_backprop_lm_model(self):
|
||||
config = ReformerConfig()
|
||||
|
||||
shape = (1, 192) # Batch x SeqLen x ModelDimPerHead
|
||||
input_ids = torch.tensor(
|
||||
np.random.randint(0, config.vocab_size, size=shape), dtype=torch.long, device=torch_device,
|
||||
)
|
||||
|
||||
model = ReformerModelWithLMHead(config)
|
||||
loss = model(input_ids, labels=input_ids)[0]
|
||||
loss.backward()
|
||||
|
||||
# NEED OLD TRAX VERSION FOR THIS TEST => DEPRECATED
|
||||
def test_pretrained_crime_and_punishment_lm_model(self):
|
||||
hf_config = ReformerConfig.from_pretrained("google/reformer-crime-and-punishment")
|
||||
hf_config.hash_seed = 0
|
||||
hf_model = ReformerModelWithLMHead.from_pretrained("google/reformer-crime-and-punishment", config=hf_config)
|
||||
config = hf_model.config
|
||||
|
||||
trax_model_path = "/home/patrick/hugging_face/models/trained_reformer_colab/model.pkl"
|
||||
|
||||
shape = (1, 512)
|
||||
np_input = np.random.randint(0, config.vocab_size, size=shape)
|
||||
|
||||
hf_input = torch.tensor(np_input)
|
||||
|
||||
input_signature = trax_ShapeDtype(shape, np.int32)
|
||||
trax_model = self.load_crime_and_punishment_model(trax_model_path, input_signature)
|
||||
|
||||
hf_output = hf_model(hf_input)
|
||||
log_softmax_output = torch.nn.functional.log_softmax(hf_output[0], dim=-1)
|
||||
|
||||
trax_output = trax_model(np_input)
|
||||
trax_torch_output = torch.tensor(np.asarray(trax_output[0]))
|
||||
|
||||
self.assertTrue(torch.allclose(log_softmax_output, trax_torch_output, atol=1e-3))
|
||||
|
||||
def test_pretrained_enwiki8_lm_model(self):
|
||||
hf_config = ReformerConfig.from_pretrained("google/reformer-enwik8")
|
||||
hf_config.hash_seed = 0
|
||||
hf_model = ReformerModelWithLMHead.from_pretrained("google/reformer-enwik8", config=hf_config)
|
||||
config = hf_model.config
|
||||
|
||||
trax_model_path = "/home/patrick/hugging_face/reformer/enwik8_model/reformer_enwik8_model.pkl"
|
||||
|
||||
shape = (1, 512)
|
||||
np_input = np.random.randint(0, config.vocab_size, size=shape)
|
||||
|
||||
hf_input = torch.tensor(np_input)
|
||||
|
||||
input_signature = trax_ShapeDtype(shape, np.int32)
|
||||
trax_model = self.load_enwik8_model(trax_model_path, input_signature)
|
||||
|
||||
hf_output = hf_model(hf_input)
|
||||
log_softmax_output = torch.nn.functional.log_softmax(hf_output[0], dim=-1)
|
||||
|
||||
trax_output = trax_model(np_input)
|
||||
trax_torch_output = torch.tensor(np.asarray(trax_output))
|
||||
|
||||
self.assertTrue(torch.allclose(log_softmax_output, trax_torch_output, atol=1e-3))
|
||||
|
||||
def load_lsh_layer(self, config, mode="eval"):
|
||||
gin_config = """
|
||||
import trax.layers
|
||||
# Parameters for LSHSelfAttention:
|
||||
# ==============================================================================
|
||||
trax.layers.LSHSelfAttention.n_heads = {}
|
||||
trax.layers.LSHSelfAttention.d_qk = {}
|
||||
trax.layers.LSHSelfAttention.d_v = {}
|
||||
trax.layers.LSHSelfAttention.chunk_len = {}
|
||||
trax.layers.LSHSelfAttention.n_chunks_before = {}
|
||||
trax.layers.LSHSelfAttention.n_chunks_after = {}
|
||||
trax.layers.LSHSelfAttention.n_hashes = {}
|
||||
trax.layers.LSHSelfAttention.n_buckets = {}
|
||||
trax.layers.LSHSelfAttention.attention_dropout = {}
|
||||
trax.layers.LSHSelfAttention.output_dropout = {}
|
||||
trax.layers.LSHSelfAttention.lsh_seed = {}
|
||||
trax.layers.LSHSelfAttention.causal= {}
|
||||
trax.layers.LSHSelfAttention.use_reference_code = True
|
||||
trax.layers.LSHSelfAttention.masked = True
|
||||
""".format(
|
||||
config.num_attention_heads,
|
||||
config.attention_head_size,
|
||||
config.attention_head_size,
|
||||
config.lsh_attn_chunk_length,
|
||||
config.lsh_num_chunks_before,
|
||||
config.lsh_num_chunks_after,
|
||||
config.num_hashes,
|
||||
config.num_buckets,
|
||||
config.lsh_attention_probs_dropout_prob,
|
||||
config.hidden_dropout_prob,
|
||||
config.hash_seed,
|
||||
config.is_decoder,
|
||||
)
|
||||
gin.parse_config(gin_config)
|
||||
layer = trax.layers.LSHSelfAttention(mode=mode)
|
||||
return layer
|
||||
|
||||
def load_local_layer(self, config, mode="eval"):
|
||||
gin_config = """
|
||||
import trax.layers
|
||||
# Parameters for SelfAttention:
|
||||
# ==============================================================================
|
||||
trax.layers.SelfAttention.n_heads = {}
|
||||
trax.layers.SelfAttention.d_qk = {}
|
||||
trax.layers.SelfAttention.d_v = {}
|
||||
trax.layers.SelfAttention.chunk_len = {}
|
||||
trax.layers.SelfAttention.n_chunks_before = {}
|
||||
trax.layers.SelfAttention.n_chunks_after = {}
|
||||
trax.layers.SelfAttention.attention_dropout = {}
|
||||
trax.layers.SelfAttention.output_dropout = {}
|
||||
trax.layers.SelfAttention.causal = {}
|
||||
trax.layers.SelfAttention.masked= True
|
||||
trax.layers.SelfAttention.use_reference_code = True
|
||||
""".format(
|
||||
config.num_attention_heads,
|
||||
config.attention_head_size,
|
||||
config.attention_head_size,
|
||||
config.local_attn_chunk_length,
|
||||
config.local_num_chunks_before,
|
||||
config.local_num_chunks_after,
|
||||
config.local_attention_probs_dropout_prob,
|
||||
config.hidden_dropout_prob,
|
||||
config.is_decoder,
|
||||
)
|
||||
gin.parse_config(gin_config)
|
||||
layer = trax.layers.SelfAttention(mode=mode)
|
||||
return layer
|
||||
|
||||
def load_reformer_lm_model(self, config, mode="eval"):
|
||||
if config.hidden_act == "gelu":
|
||||
hidden_act = "Gelu"
|
||||
elif config.hidden_act == "relu":
|
||||
hidden_act = "Relu"
|
||||
else:
|
||||
raise ValueError()
|
||||
attn_type = config.attn_layers[0]
|
||||
if attn_type == "lsh":
|
||||
attn_type = "LSHSelfAttention"
|
||||
elif attn_type == "local":
|
||||
attn_type = "SelfAttention"
|
||||
else:
|
||||
raise ValueError()
|
||||
|
||||
axial_pos_shape = config.axial_pos_shape
|
||||
d_axial_pos_embs = config.axial_pos_embds_dim
|
||||
|
||||
gin_config = """
|
||||
import trax.layers
|
||||
import trax.models
|
||||
# Parameters for LSHSelfAttention:
|
||||
# ==============================================================================
|
||||
trax.layers.LSHSelfAttention.chunk_len = {}
|
||||
trax.layers.LSHSelfAttention.predict_mem_len = {}
|
||||
trax.layers.LSHSelfAttention.predict_drop_len = {}
|
||||
trax.layers.LSHSelfAttention.n_chunks_before = {}
|
||||
trax.layers.LSHSelfAttention.n_chunks_after = {}
|
||||
trax.layers.LSHSelfAttention.n_hashes = {}
|
||||
trax.layers.LSHSelfAttention.n_buckets = {}
|
||||
trax.layers.LSHSelfAttention.lsh_seed = {}
|
||||
trax.layers.LSHSelfAttention.causal= {}
|
||||
trax.layers.LSHSelfAttention.use_reference_code = True
|
||||
# Parameters for SelfAttention:
|
||||
# ==============================================================================
|
||||
trax.layers.SelfAttention.chunk_len = {}
|
||||
trax.layers.SelfAttention.n_chunks_before = {}
|
||||
trax.layers.SelfAttention.n_chunks_after = {}
|
||||
trax.layers.SelfAttention.causal= {}
|
||||
trax.layers.SelfAttention.use_reference_code = True
|
||||
trax.layers.SelfAttention.share_qk = False
|
||||
# Parameters for ReformerLM:
|
||||
# ==============================================================================
|
||||
trax.models.ReformerLM.vocab_size = {}
|
||||
trax.models.ReformerLM.d_model = {}
|
||||
trax.models.ReformerLM.d_ff = {}
|
||||
trax.models.ReformerLM.d_attention_key = {}
|
||||
trax.models.ReformerLM.d_attention_value = {}
|
||||
trax.models.ReformerLM.n_layers = {}
|
||||
trax.models.ReformerLM.n_heads = {}
|
||||
trax.models.ReformerLM.max_len = {}
|
||||
trax.models.ReformerLM.axial_pos_shape = {}
|
||||
trax.models.ReformerLM.d_axial_pos_embs = {}
|
||||
trax.models.ReformerLM.ff_chunk_size = {}
|
||||
trax.models.ReformerLM.ff_activation = @trax.layers.{}
|
||||
trax.models.ReformerLM.attention_type = @trax.layers.{}
|
||||
trax.models.ReformerLM.is_decoder = {}
|
||||
trax.models.ReformerLM.dropout = 0.0
|
||||
trax.models.ReformerLM.ff_use_sru = 0
|
||||
""".format(
|
||||
config.lsh_attn_chunk_length,
|
||||
config.lsh_attn_chunk_length,
|
||||
config.lsh_attn_chunk_length // 2,
|
||||
config.lsh_num_chunks_before,
|
||||
config.lsh_num_chunks_after,
|
||||
config.num_hashes,
|
||||
config.num_buckets,
|
||||
config.hash_seed,
|
||||
config.is_decoder,
|
||||
config.local_attn_chunk_length,
|
||||
config.local_num_chunks_before,
|
||||
config.local_num_chunks_after,
|
||||
config.is_decoder,
|
||||
config.vocab_size,
|
||||
config.hidden_size,
|
||||
config.feed_forward_size,
|
||||
config.attention_head_size,
|
||||
config.attention_head_size,
|
||||
config.num_hidden_layers,
|
||||
config.num_attention_heads,
|
||||
config.max_position_embeddings,
|
||||
axial_pos_shape,
|
||||
d_axial_pos_embs,
|
||||
config.chunk_size_feed_forward,
|
||||
hidden_act,
|
||||
attn_type,
|
||||
config.is_decoder,
|
||||
)
|
||||
gin.parse_config(gin_config)
|
||||
model = trax.models.ReformerLM(mode=mode)
|
||||
return model
|
||||
|
||||
# (PVP) - delete when enwiki works
|
||||
def load_crime_and_punishment_model(self, trax_model_path, input_signature, mode="predict"):
|
||||
gin.parse_config(
|
||||
"""
|
||||
import trax.layers
|
||||
import trax.models
|
||||
import trax.optimizers
|
||||
import trax.supervised.inputs
|
||||
import trax.supervised.trainer_lib
|
||||
# Parameters that will vary between experiments:
|
||||
# ==============================================================================
|
||||
train.model = @trax.models.ReformerLM
|
||||
# Our model will have 6 layers, alternating between the LSH attention proposed
|
||||
# in the Reformer paper and local attention within a certain context window.
|
||||
n_layers = 6
|
||||
attn_type = [
|
||||
@SelfAttention,
|
||||
@LSHSelfAttention,
|
||||
@SelfAttention,
|
||||
@LSHSelfAttention,
|
||||
@SelfAttention,
|
||||
@LSHSelfAttention,
|
||||
]
|
||||
n_heads = 2
|
||||
attn_kv = 64
|
||||
dropout = 0.05
|
||||
n_tokens = 524288
|
||||
# Parameters for SelfAttention:
|
||||
# ==============================================================================
|
||||
SelfAttention.chunk_len = 64
|
||||
SelfAttention.n_chunks_before = 1
|
||||
SelfAttention.n_parallel_heads = 1
|
||||
SelfAttention.share_qk = False
|
||||
# Parameters for LSHSelfAttention:
|
||||
# ==============================================================================
|
||||
LSHSelfAttention.chunk_len = 64
|
||||
LSHSelfAttention.n_buckets = [64, 128]
|
||||
LSHSelfAttention.n_chunks_after = 0
|
||||
LSHSelfAttention.n_chunks_before = 1
|
||||
LSHSelfAttention.n_hashes = 1
|
||||
LSHSelfAttention.n_parallel_heads = 1
|
||||
LSHSelfAttention.predict_drop_len = 32 # different from original to make code equal
|
||||
LSHSelfAttention.predict_mem_len = 64 # different from original to make code equal
|
||||
LSHSelfAttention.lsh_seed = 0
|
||||
# Parameters for ReformerLM:
|
||||
# ==============================================================================
|
||||
ReformerLM.attention_type = %attn_type
|
||||
ReformerLM.d_attention_key = %attn_kv
|
||||
ReformerLM.d_attention_value = %attn_kv
|
||||
ReformerLM.d_model = 256
|
||||
ReformerLM.d_ff = 512
|
||||
ReformerLM.dropout = %dropout
|
||||
ReformerLM.ff_activation = @trax.layers.Relu
|
||||
ReformerLM.max_len = %n_tokens
|
||||
ReformerLM.mode = 'train'
|
||||
ReformerLM.n_heads = %n_heads
|
||||
ReformerLM.n_layers = %n_layers
|
||||
ReformerLM.vocab_size = 320
|
||||
ReformerLM.axial_pos_shape = (512, 1024)
|
||||
ReformerLM.d_axial_pos_embs= (64, 192)
|
||||
"""
|
||||
)
|
||||
trax_model = trax.models.ReformerLM(mode=mode)
|
||||
trax_model.init(input_signature)
|
||||
trax_model.init_from_file(trax_model_path, weights_only=True)
|
||||
return trax_model
|
||||
|
||||
def load_enwik8_model(self, trax_model_path, input_signature, mode="predict"):
|
||||
gin.parse_config(
|
||||
"""
|
||||
import trax.layers
|
||||
import trax.models
|
||||
import trax.optimizers
|
||||
import trax.supervised.inputs
|
||||
import trax.supervised.trainer_lib
|
||||
|
||||
# Macros:
|
||||
# ==============================================================================
|
||||
attn_kv = 128
|
||||
attn_type = \
|
||||
[@SelfAttention,
|
||||
@SelfAttention,
|
||||
@LSHSelfAttention,
|
||||
@SelfAttention]
|
||||
dropout = 0.2
|
||||
n_layers = 12
|
||||
|
||||
# SelfAttention: attend to nearby items
|
||||
# Specifying chunk_len restricts an item to attend within its own chunk, as well
|
||||
# as the previous `n_chunks_before` chunks.
|
||||
SelfAttention.chunk_len = 128
|
||||
SelfAttention.n_chunks_before = 1
|
||||
|
||||
# LSHSelfAttention: locality-sensitive hashing (LSH) attention
|
||||
LSHSelfAttention.chunk_len = 256
|
||||
LSHSelfAttention.n_buckets = 512
|
||||
LSHSelfAttention.n_chunks_before = 1
|
||||
LSHSelfAttention.n_hashes = 4
|
||||
|
||||
|
||||
# Parameters for SelfAttention:
|
||||
# ==============================================================================
|
||||
SelfAttention.attention_dropout = 0.2
|
||||
# SelfAttention.chunk_len: see top
|
||||
SelfAttention.n_chunks_after = 0
|
||||
# SelfAttention.n_chunks_before: see top
|
||||
|
||||
# Parameters for LSHSelfAttention:
|
||||
# ==============================================================================
|
||||
LSHSelfAttention.attention_dropout = 0.1
|
||||
# LSHSelfAttention.chunk_len: see top
|
||||
# LSHSelfAttention.n_buckets: see top
|
||||
LSHSelfAttention.n_chunks_after = 0
|
||||
# LSHSelfAttention.n_chunks_before: see top
|
||||
# LSHSelfAttention.n_hashes: see top
|
||||
LSHSelfAttention.n_parallel_heads = 1
|
||||
LSHSelfAttention.predict_drop_len = 64 # different from original to make code equal
|
||||
LSHSelfAttention.predict_mem_len = 128 # different from original to make code equal
|
||||
LSHSelfAttention.lsh_seed = 0
|
||||
|
||||
# Parameters for ReformerLM:
|
||||
# ==============================================================================
|
||||
ReformerLM.attention_type = %attn_type
|
||||
ReformerLM.d_attention_key = %attn_kv
|
||||
ReformerLM.d_attention_value = %attn_kv
|
||||
ReformerLM.d_model = 1024
|
||||
ReformerLM.d_ff = 4096
|
||||
ReformerLM.dropout = %dropout
|
||||
ReformerLM.ff_activation = @trax.layers.Relu
|
||||
ReformerLM.max_len = 65536
|
||||
ReformerLM.mode = 'train'
|
||||
ReformerLM.n_heads = 8
|
||||
ReformerLM.n_layers = %n_layers
|
||||
ReformerLM.vocab_size = 258 # Includes pad token and unused EOS token
|
||||
ReformerLM.axial_pos_shape = (128, 512)
|
||||
ReformerLM.d_axial_pos_embs= (256, 768)
|
||||
"""
|
||||
)
|
||||
trax_model = trax.models.ReformerLM(mode=mode)
|
||||
trax_model.init(input_signature)
|
||||
trax_model.init_from_file(trax_model_path, weights_only=True)
|
||||
return trax_model
|
||||
|
||||
def _set_param(self, torch_layer, weight, bias=None, name=None):
|
||||
with torch.no_grad():
|
||||
assert torch_layer.weight.shape == weight.shape, "{} layer.weight does not match".format(torch_layer)
|
||||
torch_layer.weight = torch.nn.Parameter(weight)
|
||||
if bias is not None:
|
||||
assert torch_layer.bias.shape == bias.shape, "{} layer.bias does not match".format(torch_layer)
|
||||
torch_layer.bias = torch.nn.Parameter(bias)
|
||||
return True
|
||||
|
||||
def _test_param(self, torch_layer, grad, bias_grad=None, name=""):
|
||||
assert torch_layer.weight.grad.shape == grad.shape, "{} layer.grad does not match".format(torch_layer)
|
||||
if torch.allclose(torch_layer.weight.grad, grad, atol=1e-3):
|
||||
print("{}-{} layer.grad is good!".format(name, torch_layer))
|
||||
else:
|
||||
print("ERROR {}-{} layer.grad is not good!".format(name, torch_layer))
|
||||
return False
|
||||
if bias_grad is not None:
|
||||
assert torch_layer.bias.grad.shape == bias_grad.shape, "{} layer.bias does not match".format(torch_layer)
|
||||
if torch.allclose(torch_layer.bias.grad, bias_grad, atol=1e-3):
|
||||
print("{}-{} layer.grad bias is good!".format(name, torch_layer))
|
||||
else:
|
||||
print("ERROR {}-{} layer.grad bias is not good!".format(name, torch_layer))
|
||||
return False
|
||||
return True
|
||||
|
||||
def _set_layer_weights_in_torch_lsh(self, weights, torch_layer, hidden_size, exec_fn=None):
|
||||
all_test_true = True
|
||||
if exec_fn is None:
|
||||
exec_fn = self._set_param
|
||||
|
||||
# set torch weights for 1-to-1 comparison
|
||||
np_query_key = np.asarray(weights[0])
|
||||
np_value = np.asarray(weights[1])
|
||||
np_dense = np.asarray(weights[2])
|
||||
|
||||
all_test_true = (
|
||||
exec_fn(
|
||||
torch_layer.self_attention.query_key,
|
||||
torch.tensor(np_query_key).transpose(1, 2).contiguous().view(-1, hidden_size),
|
||||
name="attn_query_key",
|
||||
)
|
||||
and all_test_true
|
||||
)
|
||||
|
||||
all_test_true = (
|
||||
exec_fn(
|
||||
torch_layer.self_attention.value,
|
||||
torch.tensor(np_value).transpose(1, 2).contiguous().view(-1, hidden_size),
|
||||
name="attn_value",
|
||||
)
|
||||
and all_test_true
|
||||
)
|
||||
|
||||
all_test_true = (
|
||||
exec_fn(
|
||||
torch_layer.output.dense,
|
||||
torch.tensor(np_dense).view(-1, hidden_size).contiguous().transpose(0, 1),
|
||||
name="attn_dense",
|
||||
)
|
||||
and all_test_true
|
||||
)
|
||||
return all_test_true
|
||||
|
||||
def _set_layer_weights_in_torch_local(self, weights, torch_layer, hidden_size, exec_fn=None):
|
||||
all_test_true = True
|
||||
|
||||
if exec_fn is None:
|
||||
exec_fn = self._set_param
|
||||
|
||||
# set torch weights for 1-to-1 comparison
|
||||
np_query = np.asarray(weights[0])
|
||||
np_key = np.asarray(weights[1])
|
||||
np_value = np.asarray(weights[2])
|
||||
np_dense = np.asarray(weights[3])
|
||||
|
||||
all_test_true = (
|
||||
exec_fn(
|
||||
torch_layer.self_attention.query,
|
||||
torch.tensor(np_query).transpose(1, 2).contiguous().view(-1, hidden_size),
|
||||
)
|
||||
and all_test_true
|
||||
)
|
||||
all_test_true = (
|
||||
exec_fn(
|
||||
torch_layer.self_attention.key,
|
||||
torch.tensor(np_key).transpose(1, 2).contiguous().view(-1, hidden_size),
|
||||
)
|
||||
and all_test_true
|
||||
)
|
||||
all_test_true = (
|
||||
exec_fn(
|
||||
torch_layer.self_attention.value,
|
||||
torch.tensor(np_value).transpose(1, 2).contiguous().view(-1, hidden_size),
|
||||
)
|
||||
and all_test_true
|
||||
)
|
||||
all_test_true = (
|
||||
exec_fn(
|
||||
torch_layer.output.dense, torch.tensor(np_dense).view(-1, hidden_size).contiguous().transpose(0, 1),
|
||||
)
|
||||
and all_test_true
|
||||
)
|
||||
return all_test_true
|
||||
|
||||
def _set_block_weights_in_torch(self, weights, torch_block, hidden_size, exec_fn=None):
|
||||
all_test_true = True
|
||||
|
||||
if exec_fn is None:
|
||||
exec_fn = self._set_param
|
||||
|
||||
# intermediate weighs
|
||||
intermediate_weights = weights[2][0]
|
||||
|
||||
# Chunked Feed Forward
|
||||
if len(intermediate_weights) == 4:
|
||||
intermediate_weights = intermediate_weights[2]
|
||||
|
||||
# intermediate out
|
||||
out_dense_weight = np.asarray(intermediate_weights[4][0])
|
||||
out_dense_bias = np.asarray(intermediate_weights[4][1])
|
||||
all_test_true = (
|
||||
exec_fn(
|
||||
torch_block.feed_forward.output.dense,
|
||||
torch.tensor(out_dense_weight).transpose(0, 1).contiguous(),
|
||||
torch.tensor(out_dense_bias),
|
||||
name="res_feed_forward_2",
|
||||
)
|
||||
and all_test_true
|
||||
)
|
||||
|
||||
# intermediate dense
|
||||
inter_dense_weight = np.asarray(intermediate_weights[1][0])
|
||||
inter_dense_bias = np.asarray(intermediate_weights[1][1])
|
||||
all_test_true = (
|
||||
exec_fn(
|
||||
torch_block.feed_forward.dense.dense,
|
||||
torch.tensor(inter_dense_weight).transpose(0, 1).contiguous(),
|
||||
torch.tensor(inter_dense_bias),
|
||||
name="res_feed_forward_1",
|
||||
)
|
||||
and all_test_true
|
||||
)
|
||||
|
||||
# layernorm 2
|
||||
layer_norm_2_weight = np.asarray(intermediate_weights[0][0])
|
||||
layer_norm_2_bias = np.asarray(intermediate_weights[0][1])
|
||||
all_test_true = (
|
||||
exec_fn(
|
||||
torch_block.feed_forward.layer_norm,
|
||||
torch.tensor(layer_norm_2_weight),
|
||||
torch.tensor(layer_norm_2_bias),
|
||||
name="layer_norm_2",
|
||||
)
|
||||
and all_test_true
|
||||
)
|
||||
|
||||
# lsh weights + output
|
||||
attn_weights = weights[0][1]
|
||||
if len(attn_weights) < 4:
|
||||
all_test_true = (
|
||||
self._set_layer_weights_in_torch_lsh(attn_weights, torch_block.attention, hidden_size, exec_fn=exec_fn)
|
||||
and all_test_true
|
||||
)
|
||||
else:
|
||||
all_test_true = (
|
||||
self._set_layer_weights_in_torch_local(
|
||||
attn_weights, torch_block.attention, hidden_size, exec_fn=exec_fn
|
||||
)
|
||||
and all_test_true
|
||||
)
|
||||
|
||||
# layernorm 1
|
||||
layer_norm_1 = weights[0][0][0]
|
||||
layer_norm_1_weight = np.asarray(layer_norm_1[0])
|
||||
layer_norm_1_bias = np.asarray(layer_norm_1[1])
|
||||
all_test_true = (
|
||||
exec_fn(
|
||||
torch_block.attention.layer_norm,
|
||||
torch.tensor(layer_norm_1_weight),
|
||||
torch.tensor(layer_norm_1_bias),
|
||||
name="layer_norm",
|
||||
)
|
||||
and all_test_true
|
||||
)
|
||||
|
||||
return all_test_true
|
||||
|
||||
def _set_model_weights_in_torch(self, weights, torch_model, hidden_size, set_params=True):
|
||||
# reformer model
|
||||
torch_model_reformer = torch_model.reformer
|
||||
|
||||
all_test_true = True
|
||||
if set_params is True:
|
||||
exec_fn = self._set_param
|
||||
else:
|
||||
exec_fn = self._test_param
|
||||
|
||||
# output embeddings
|
||||
output_embed_weights = np.asarray(weights[9][0])
|
||||
output_embed_bias = np.asarray(weights[9][1])
|
||||
all_test_true = (
|
||||
exec_fn(
|
||||
torch_model.lm_head.decoder,
|
||||
torch.tensor(output_embed_weights).transpose(0, 1).contiguous(),
|
||||
torch.tensor(output_embed_bias),
|
||||
name="lm_head",
|
||||
)
|
||||
and all_test_true
|
||||
)
|
||||
|
||||
# output layer norm
|
||||
layer_norm_out_weight = np.asarray(weights[7][0])
|
||||
layer_norm_out_bias = np.asarray(weights[7][1])
|
||||
all_test_true = (
|
||||
exec_fn(
|
||||
torch_model_reformer.encoder.layer_norm,
|
||||
torch.tensor(layer_norm_out_weight),
|
||||
torch.tensor(layer_norm_out_bias),
|
||||
name="last layer norm",
|
||||
)
|
||||
and all_test_true
|
||||
)
|
||||
|
||||
trax_layer_weights = weights[5]
|
||||
assert len(torch_model_reformer.encoder.layers) * 4 == len(
|
||||
trax_layer_weights
|
||||
), "HF and trax model do not have the same number of layers"
|
||||
for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers[::-1]):
|
||||
block_weights = trax_layer_weights[::-1][4 * layer_idx : 4 * (layer_idx + 1)][::-1]
|
||||
all_test_true = (
|
||||
self._set_block_weights_in_torch(block_weights, layer, hidden_size, exec_fn=exec_fn) and all_test_true
|
||||
)
|
||||
|
||||
if isinstance(weights[3], tuple):
|
||||
position_embeddings = torch_model_reformer.embeddings.position_embeddings
|
||||
for emb_idx in range(len(position_embeddings.weights)):
|
||||
emb_weights = np.asarray(weights[3][emb_idx][0])
|
||||
assert position_embeddings.weights[emb_idx].shape == emb_weights.shape, "{} emb does not match".format(
|
||||
position_embeddings[emb_idx]
|
||||
)
|
||||
if set_params is True:
|
||||
position_embeddings.weights[emb_idx] = torch.nn.Parameter(torch.tensor(emb_weights))
|
||||
else:
|
||||
if torch.allclose(
|
||||
position_embeddings.weights[emb_idx].grad, torch.tensor(emb_weights), atol=1e-3,
|
||||
):
|
||||
print("{} layer.grad is good!".format(position_embeddings))
|
||||
else:
|
||||
print("ERROR: {}-{} layer.grad is not good".format(position_embeddings, "axs_pos_embeds"))
|
||||
|
||||
# word embeds
|
||||
word_embeddings = np.asarray(weights[1])
|
||||
all_test_true = (
|
||||
exec_fn(torch_model_reformer.embeddings.word_embeddings, torch.tensor(word_embeddings), name="word_embed",)
|
||||
and all_test_true
|
||||
)
|
||||
|
||||
return all_test_true
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_torch_available
|
||||
from transformers.testing_utils import require_torch, slow, torch_device
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_common import ModelTesterMixin, ids_tensor
|
||||
from .utils import require_torch, slow, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_torch_available
|
||||
from transformers.testing_utils import require_torch, slow, torch_device
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_common import ModelTesterMixin, ids_tensor
|
||||
from .utils import require_torch, slow, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import AlbertConfig, is_tf_available
|
||||
from transformers.testing_utils import require_tf, slow
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_tf_common import TFModelTesterMixin, ids_tensor
|
||||
from .utils import require_tf, slow
|
||||
|
||||
|
||||
if is_tf_available():
|
||||
|
||||
@@ -17,8 +17,7 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_tf_available
|
||||
|
||||
from .utils import DUMMY_UNKWOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, require_tf, slow
|
||||
from transformers.testing_utils import DUMMY_UNKWOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, require_tf, slow
|
||||
|
||||
|
||||
if is_tf_available():
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import BertConfig, is_tf_available
|
||||
from transformers.testing_utils import require_tf, slow
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_tf_common import TFModelTesterMixin, ids_tensor
|
||||
from .utils import require_tf, slow
|
||||
|
||||
|
||||
if is_tf_available():
|
||||
|
||||
@@ -16,8 +16,7 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_tf_available
|
||||
|
||||
from .utils import require_tf, slow
|
||||
from transformers.testing_utils import require_tf, slow
|
||||
|
||||
|
||||
if is_tf_available():
|
||||
|
||||
@@ -23,8 +23,7 @@ import unittest
|
||||
from importlib import import_module
|
||||
|
||||
from transformers import is_tf_available, is_torch_available
|
||||
|
||||
from .utils import _tf_gpu_memory_limit, require_tf
|
||||
from transformers.testing_utils import _tf_gpu_memory_limit, require_tf
|
||||
|
||||
|
||||
if is_tf_available():
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import CTRLConfig, is_tf_available
|
||||
from transformers.testing_utils import require_tf, slow
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_tf_common import TFModelTesterMixin, ids_tensor
|
||||
from .utils import require_tf, slow
|
||||
|
||||
|
||||
if is_tf_available():
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import DistilBertConfig, is_tf_available
|
||||
from transformers.testing_utils import require_tf
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_tf_common import TFModelTesterMixin, ids_tensor
|
||||
from .utils import require_tf
|
||||
|
||||
|
||||
if is_tf_available():
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import ElectraConfig, is_tf_available
|
||||
from transformers.testing_utils import require_tf, slow
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_tf_common import TFModelTesterMixin, ids_tensor
|
||||
from .utils import require_tf, slow
|
||||
|
||||
|
||||
if is_tf_available():
|
||||
|
||||
@@ -16,8 +16,7 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_tf_available
|
||||
|
||||
from .utils import require_tf, slow
|
||||
from transformers.testing_utils import require_tf, slow
|
||||
|
||||
|
||||
if is_tf_available():
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import GPT2Config, is_tf_available
|
||||
from transformers.testing_utils import require_tf, slow
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_tf_common import TFModelTesterMixin, ids_tensor
|
||||
from .utils import require_tf, slow
|
||||
|
||||
|
||||
if is_tf_available():
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import MobileBertConfig, is_tf_available
|
||||
from transformers.testing_utils import require_tf, slow
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_tf_common import TFModelTesterMixin, ids_tensor
|
||||
from .utils import require_tf, slow
|
||||
|
||||
|
||||
if is_tf_available():
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import OpenAIGPTConfig, is_tf_available
|
||||
from transformers.testing_utils import require_tf, slow
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_tf_common import TFModelTesterMixin, ids_tensor
|
||||
from .utils import require_tf, slow
|
||||
|
||||
|
||||
if is_tf_available():
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import RobertaConfig, is_tf_available
|
||||
from transformers.testing_utils import require_tf, slow
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_tf_common import TFModelTesterMixin, ids_tensor
|
||||
from .utils import require_tf, slow
|
||||
|
||||
|
||||
if is_tf_available():
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -18,10 +18,10 @@ import random
|
||||
import unittest
|
||||
|
||||
from transformers import TransfoXLConfig, is_tf_available
|
||||
from transformers.testing_utils import require_tf, slow
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_tf_common import TFModelTesterMixin, ids_tensor
|
||||
from .utils import require_tf, slow
|
||||
|
||||
|
||||
if is_tf_available():
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_tf_available
|
||||
from transformers.testing_utils import require_tf, slow
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_tf_common import TFModelTesterMixin, ids_tensor
|
||||
from .utils import require_tf, slow
|
||||
|
||||
|
||||
if is_tf_available():
|
||||
|
||||
@@ -16,8 +16,7 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_tf_available
|
||||
|
||||
from .utils import require_tf, slow
|
||||
from transformers.testing_utils import require_tf, slow
|
||||
|
||||
|
||||
if is_tf_available():
|
||||
|
||||
@@ -18,10 +18,10 @@ import random
|
||||
import unittest
|
||||
|
||||
from transformers import XLNetConfig, is_tf_available
|
||||
from transformers.testing_utils import require_tf, slow
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_tf_common import TFModelTesterMixin, ids_tensor
|
||||
from .utils import require_tf, slow
|
||||
|
||||
|
||||
if is_tf_available():
|
||||
|
||||
@@ -17,10 +17,10 @@ import random
|
||||
import unittest
|
||||
|
||||
from transformers import is_torch_available
|
||||
from transformers.testing_utils import require_multigpu, require_torch, slow, torch_device
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_common import ModelTesterMixin, ids_tensor
|
||||
from .utils import require_multigpu, require_torch, slow, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
@@ -162,7 +162,6 @@ class TransfoXLModelTester:
|
||||
|
||||
@require_torch
|
||||
class TransfoXLModelTest(ModelTesterMixin, unittest.TestCase):
|
||||
|
||||
all_model_classes = (TransfoXLModel, TransfoXLLMHeadModel) if is_torch_available() else ()
|
||||
all_generative_model_classes = (TransfoXLLMHeadModel,) if is_torch_available() else ()
|
||||
test_pruning = False
|
||||
@@ -448,7 +447,6 @@ class TransfoXLModelLanguageGenerationTest(unittest.TestCase):
|
||||
# father initially slaps him for making such an accusation , Rasputin watches as the
|
||||
# man is chased outside and beaten . Twenty years later , Rasputin sees a vision of
|
||||
# the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous ,
|
||||
|
||||
# with people , even a bishop , begging for his blessing . <eod> </s> <eos>
|
||||
|
||||
expected_output_ids = [
|
||||
@@ -595,54 +593,77 @@ class TransfoXLModelLanguageGenerationTest(unittest.TestCase):
|
||||
0,
|
||||
33,
|
||||
1,
|
||||
1857,
|
||||
142,
|
||||
1298,
|
||||
188,
|
||||
2,
|
||||
1,
|
||||
1009,
|
||||
29546,
|
||||
113,
|
||||
8,
|
||||
3654,
|
||||
4,
|
||||
1,
|
||||
1109,
|
||||
11739,
|
||||
4762,
|
||||
358,
|
||||
5,
|
||||
25,
|
||||
245,
|
||||
28,
|
||||
1110,
|
||||
7136,
|
||||
833,
|
||||
3,
|
||||
13,
|
||||
1041,
|
||||
1645,
|
||||
4,
|
||||
29546,
|
||||
11,
|
||||
104,
|
||||
7,
|
||||
1,
|
||||
1109,
|
||||
532,
|
||||
7129,
|
||||
2,
|
||||
10,
|
||||
83507,
|
||||
2,
|
||||
1162,
|
||||
1123,
|
||||
2,
|
||||
6,
|
||||
7245,
|
||||
10,
|
||||
2,
|
||||
5,
|
||||
11,
|
||||
104,
|
||||
7,
|
||||
1,
|
||||
1109,
|
||||
532,
|
||||
7129,
|
||||
2,
|
||||
10,
|
||||
24,
|
||||
603,
|
||||
490,
|
||||
2,
|
||||
71477,
|
||||
20098,
|
||||
104447,
|
||||
2,
|
||||
20961,
|
||||
1,
|
||||
2604,
|
||||
24,
|
||||
10,
|
||||
22,
|
||||
10,
|
||||
13,
|
||||
770,
|
||||
5863,
|
||||
4,
|
||||
1,
|
||||
329,
|
||||
3,
|
||||
0,
|
||||
7245,
|
||||
10,
|
||||
]
|
||||
# In 1991, the remains of Russian Tsar Nicholas II and his family (
|
||||
# except for Alexei and Maria ) are discovered. The voice of young son,
|
||||
# Tsarevich Alexei Nikolaevich, narrates the remainder of the story.
|
||||
# 1883 Western Siberia, a young Grigori Rasputin is asked by his father
|
||||
# and a group of men to perform magic. Rasputin has a vision and
|
||||
# denounces one of the men as a horse thief. Although his father initially
|
||||
# slaps him for making such an accusation, Rasputin watches as the man
|
||||
# is chased outside and beaten. Twenty years later, Rasputin sees a vision
|
||||
# of the Virgin Mary, prompting him to become a priest.
|
||||
# Rasputin quickly becomes famous, with people, even a bishop, begging for
|
||||
# his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar
|
||||
# Nicholas II and his family were discovered. The voice of <unk> young son,
|
||||
# Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos>
|
||||
# In 1991, the remains of Russian Tsar Nicholas II and his family ( except for
|
||||
# Alexei and Maria ) are discovered. The voice of young son, Tsarevich Alexei
|
||||
# Nikolaevich, narrates the remainder of the story. 1883 Western Siberia, a young
|
||||
# Grigori Rasputin is asked by his father and a group of men to perform magic.
|
||||
# Rasputin has a vision and denounces one of the men as a horse thief. Although
|
||||
# his father initially slaps him for making such an accusation, Rasputin watches
|
||||
# as the man is chased outside and beaten. Twenty years later, Rasputin sees a
|
||||
# vision of the Virgin Mary, prompting him to become a priest. Rasputin quickly
|
||||
# becomes famous, with people, even a bishop, begging for his blessing. In the
|
||||
# early 20th century, Rasputin became a symbol of the Russian Orthodox Church.
|
||||
# The image of Rasputin was used in the Russian national anthem, " Nearer, My God,
|
||||
# to Heaven ", and was used in the Russian national anthem, " " ( " The Great Spirit
|
||||
# of Heaven "
|
||||
|
||||
output_ids = model.generate(input_ids, max_length=200, do_sample=False)
|
||||
self.assertListEqual(output_ids[0].tolist(), expected_output_ids)
|
||||
|
||||
@@ -17,10 +17,10 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_torch_available
|
||||
from transformers.testing_utils import require_torch, slow, torch_device
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_common import ModelTesterMixin, ids_tensor
|
||||
from .utils import require_torch, slow, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
@@ -17,8 +17,7 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_torch_available
|
||||
|
||||
from .utils import slow
|
||||
from transformers.testing_utils import slow
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
@@ -18,10 +18,10 @@ import random
|
||||
import unittest
|
||||
|
||||
from transformers import is_torch_available
|
||||
from transformers.testing_utils import require_torch, slow, torch_device
|
||||
|
||||
from .test_configuration_common import ConfigTester
|
||||
from .test_modeling_common import ModelTesterMixin, ids_tensor
|
||||
from .utils import require_torch, slow, torch_device
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
+1
-1
@@ -3,9 +3,9 @@ from os.path import dirname, exists
|
||||
from shutil import rmtree
|
||||
from tempfile import NamedTemporaryFile, TemporaryDirectory
|
||||
|
||||
from tests.utils import require_tf, require_torch, slow
|
||||
from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline
|
||||
from transformers.convert_graph_to_onnx import convert, ensure_valid_input, infer_shapes
|
||||
from transformers.testing_utils import require_tf, require_torch, slow
|
||||
|
||||
|
||||
class FuncContiguousArgs:
|
||||
|
||||
@@ -19,8 +19,7 @@ import tempfile
|
||||
import unittest
|
||||
|
||||
from transformers import is_torch_available
|
||||
|
||||
from .utils import require_torch
|
||||
from transformers.testing_utils import require_torch
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import unittest
|
||||
|
||||
from transformers import is_tf_available
|
||||
|
||||
from .utils import require_tf
|
||||
from transformers.testing_utils import require_tf
|
||||
|
||||
|
||||
if is_tf_available():
|
||||
|
||||
+15
-4
@@ -3,8 +3,7 @@ from typing import Iterable, List, Optional
|
||||
|
||||
from transformers import pipeline
|
||||
from transformers.pipelines import SUPPORTED_TASKS, DefaultArgumentHandler, Pipeline
|
||||
|
||||
from .utils import require_tf, require_torch, slow, torch_device
|
||||
from transformers.testing_utils import require_tf, require_torch, slow, torch_device
|
||||
|
||||
|
||||
DEFAULT_DEVICE_NUM = -1 if torch_device == "cpu" else 0
|
||||
@@ -218,9 +217,15 @@ class MonoColumnInputTestCase(unittest.TestCase):
|
||||
"My name is <mask>",
|
||||
"The largest city in France is <mask>",
|
||||
]
|
||||
invalid_inputs = [
|
||||
"This is <mask> <mask>" # More than 1 mask_token in the input is not supported
|
||||
"This is" # No mask_token is not supported
|
||||
]
|
||||
for model_name in FILL_MASK_FINETUNED_MODELS:
|
||||
nlp = pipeline(task="fill-mask", model=model_name, tokenizer=model_name, framework="pt", topk=2,)
|
||||
self._test_mono_column_pipeline(nlp, valid_inputs, mandatory_keys, expected_check_keys=["sequence"])
|
||||
self._test_mono_column_pipeline(
|
||||
nlp, valid_inputs, mandatory_keys, invalid_inputs, expected_check_keys=["sequence"]
|
||||
)
|
||||
|
||||
@require_tf
|
||||
def test_tf_fill_mask(self):
|
||||
@@ -229,9 +234,15 @@ class MonoColumnInputTestCase(unittest.TestCase):
|
||||
"My name is <mask>",
|
||||
"The largest city in France is <mask>",
|
||||
]
|
||||
invalid_inputs = [
|
||||
"This is <mask> <mask>" # More than 1 mask_token in the input is not supported
|
||||
"This is" # No mask_token is not supported
|
||||
]
|
||||
for model_name in FILL_MASK_FINETUNED_MODELS:
|
||||
nlp = pipeline(task="fill-mask", model=model_name, tokenizer=model_name, framework="tf", topk=2,)
|
||||
self._test_mono_column_pipeline(nlp, valid_inputs, mandatory_keys, expected_check_keys=["sequence"])
|
||||
self._test_mono_column_pipeline(
|
||||
nlp, valid_inputs, mandatory_keys, invalid_inputs, expected_check_keys=["sequence"]
|
||||
)
|
||||
|
||||
@require_torch
|
||||
@slow
|
||||
|
||||
@@ -27,10 +27,9 @@ from transformers import (
|
||||
RobertaTokenizer,
|
||||
RobertaTokenizerFast,
|
||||
)
|
||||
from transformers.testing_utils import DUMMY_UNKWOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER # noqa: F401
|
||||
from transformers.tokenization_auto import TOKENIZER_MAPPING
|
||||
|
||||
from .utils import DUMMY_UNKWOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, slow # noqa: F401
|
||||
|
||||
|
||||
class AutoTokenizerTest(unittest.TestCase):
|
||||
# @slow
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
import os
|
||||
import unittest
|
||||
|
||||
from transformers.testing_utils import slow
|
||||
from transformers.tokenization_bert import (
|
||||
VOCAB_FILES_NAMES,
|
||||
BasicTokenizer,
|
||||
@@ -29,7 +30,6 @@ from transformers.tokenization_bert import (
|
||||
)
|
||||
|
||||
from .test_tokenization_common import TokenizerTesterMixin
|
||||
from .utils import slow
|
||||
|
||||
|
||||
class BertTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
import os
|
||||
import unittest
|
||||
|
||||
from transformers.testing_utils import custom_tokenizers
|
||||
from transformers.tokenization_bert import WordpieceTokenizer
|
||||
from transformers.tokenization_bert_japanese import (
|
||||
VOCAB_FILES_NAMES,
|
||||
@@ -26,7 +27,6 @@ from transformers.tokenization_bert_japanese import (
|
||||
)
|
||||
|
||||
from .test_tokenization_common import TokenizerTesterMixin
|
||||
from .utils import custom_tokenizers
|
||||
|
||||
|
||||
@custom_tokenizers
|
||||
|
||||
@@ -22,8 +22,8 @@ import tempfile
|
||||
from collections import OrderedDict
|
||||
from typing import TYPE_CHECKING, Dict, List, Tuple, Union
|
||||
|
||||
from tests.utils import require_tf, require_torch, slow
|
||||
from transformers import PreTrainedTokenizer, PreTrainedTokenizerBase, PreTrainedTokenizerFast
|
||||
from transformers.testing_utils import require_tf, require_torch, slow
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -508,9 +508,7 @@ class TokenizerTesterMixin:
|
||||
self.assertEqual(len(truncated_sequence), total_length - 2)
|
||||
self.assertEqual(truncated_sequence, sequence[:-2])
|
||||
|
||||
self.assertEqual(
|
||||
len(overflowing_tokens), 0
|
||||
) # No overflowing tokens when using 'longest' in python tokenizers
|
||||
self.assertEqual(len(overflowing_tokens), 2 + stride)
|
||||
|
||||
def test_maximum_encoding_length_pair_input(self):
|
||||
tokenizers = self.get_tokenizers(do_lower_case=False, model_max_length=100)
|
||||
@@ -634,7 +632,39 @@ class TokenizerTesterMixin:
|
||||
self.assertEqual(truncated_sequence, truncated_longest_sequence)
|
||||
|
||||
self.assertEqual(
|
||||
len(overflowing_tokens), 0
|
||||
len(overflowing_tokens), 2 + stride
|
||||
) # No overflowing tokens when using 'longest' in python tokenizers
|
||||
|
||||
information = tokenizer.encode_plus(
|
||||
seq_0,
|
||||
seq_1,
|
||||
max_length=len(sequence) - 2,
|
||||
add_special_tokens=False,
|
||||
stride=stride,
|
||||
truncation=True,
|
||||
return_overflowing_tokens=True,
|
||||
# add_prefix_space=False,
|
||||
)
|
||||
# Overflowing tokens are handled quite differently in slow and fast tokenizers
|
||||
if isinstance(tokenizer, PreTrainedTokenizerFast):
|
||||
truncated_sequence = information["input_ids"][0]
|
||||
overflowing_tokens = information["input_ids"][1]
|
||||
self.assertEqual(len(information["input_ids"]), 2)
|
||||
|
||||
self.assertEqual(len(truncated_sequence), len(sequence) - 2)
|
||||
self.assertEqual(truncated_sequence, truncated_longest_sequence)
|
||||
|
||||
self.assertEqual(len(overflowing_tokens), 2 + stride + len(smallest))
|
||||
self.assertEqual(overflowing_tokens, overflow_longest_sequence)
|
||||
else:
|
||||
truncated_sequence = information["input_ids"]
|
||||
overflowing_tokens = information["overflowing_tokens"]
|
||||
|
||||
self.assertEqual(len(truncated_sequence), len(sequence) - 2)
|
||||
self.assertEqual(truncated_sequence, truncated_longest_sequence)
|
||||
|
||||
self.assertEqual(
|
||||
len(overflowing_tokens), 2 + stride
|
||||
) # No overflowing tokens when using 'longest' in python tokenizers
|
||||
|
||||
information_first_truncated = tokenizer.encode_plus(
|
||||
@@ -643,7 +673,7 @@ class TokenizerTesterMixin:
|
||||
max_length=len(sequence) - 2,
|
||||
add_special_tokens=False,
|
||||
stride=stride,
|
||||
truncation=True,
|
||||
truncation="only_first",
|
||||
return_overflowing_tokens=True,
|
||||
# add_prefix_space=False,
|
||||
)
|
||||
@@ -1293,6 +1323,16 @@ class TokenizerTesterMixin:
|
||||
for key in output.keys():
|
||||
self.assertEqual(output[key], output_sequence[key])
|
||||
|
||||
def test_prepare_for_model(self):
|
||||
tokenizers = self.get_tokenizers(do_lower_case=False)
|
||||
for tokenizer in tokenizers:
|
||||
string_sequence = "Testing the prepare_for_model method."
|
||||
ids = tokenizer.encode(string_sequence, add_special_tokens=False)
|
||||
input_dict = tokenizer.encode_plus(string_sequence)
|
||||
prepared_input_dict = tokenizer.prepare_for_model(ids)
|
||||
|
||||
self.assertEqual(input_dict, prepared_input_dict)
|
||||
|
||||
@require_torch
|
||||
@require_tf
|
||||
def test_batch_encode_plus_tensors(self):
|
||||
|
||||
@@ -14,10 +14,10 @@
|
||||
# limitations under the License.
|
||||
|
||||
|
||||
from transformers.testing_utils import slow
|
||||
from transformers.tokenization_distilbert import DistilBertTokenizer, DistilBertTokenizerFast
|
||||
|
||||
from .test_tokenization_bert import BertTokenizationTest
|
||||
from .utils import slow
|
||||
|
||||
|
||||
class DistilBertTokenizationTest(BertTokenizationTest):
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user