Compare commits
148
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
203aa19ea8 | ||
|
|
dd3336f18e | ||
|
|
5930c8ec7c | ||
|
|
896300177b | ||
|
|
ae67b2439f | ||
|
|
e714412fe6 | ||
|
|
ddd40b3211 | ||
|
|
9dab39feea | ||
|
|
5b193b39b0 | ||
|
|
95d1962b9c | ||
|
|
604a2355dc | ||
|
|
77c718edef | ||
|
|
325b277db9 | ||
|
|
d15be2216c | ||
|
|
f3e23dd90a | ||
|
|
8b01d15c05 | ||
|
|
05bddf304e | ||
|
|
783a0c7ee9 | ||
|
|
e7844d60c2 | ||
|
|
b1ee69763c | ||
|
|
5f809e4976 | ||
|
|
4215f59c99 | ||
|
|
1d72460d55 | ||
|
|
ccbf74a685 | ||
|
|
d32279438a | ||
|
|
abf5c56e9d | ||
|
|
d73baeebc5 | ||
|
|
50acfc8717 | ||
|
|
7249533404 | ||
|
|
4781afd045 | ||
|
|
8e0bcb56ec | ||
|
|
a20969170b | ||
|
|
f1a4e06f1f | ||
|
|
32883b310b | ||
|
|
9ccb45a263 | ||
|
|
f19751117d | ||
|
|
511523672b | ||
|
|
182c611934 | ||
|
|
a9ae27cd0f | ||
|
|
01c40db4f8 | ||
|
|
35cb101eae | ||
|
|
290b6e18ac | ||
|
|
82dd96cae7 | ||
|
|
b01a8844a9 | ||
|
|
223bad242d | ||
|
|
d441f8d29d | ||
|
|
09a2f40684 | ||
|
|
4b506a37e3 | ||
|
|
a55809241f | ||
|
|
13be487212 | ||
|
|
eae6d8d14f | ||
|
|
dad5e12e54 | ||
|
|
ba2400189b | ||
|
|
529850ae7b | ||
|
|
615be03f9d | ||
|
|
0b2da0e592 | ||
|
|
9750e1300c | ||
|
|
1bca4fbd39 | ||
|
|
a9d56a675a | ||
|
|
12f14710ce | ||
|
|
9d37c56bab | ||
|
|
0b6c255a95 | ||
|
|
3d9556a72b | ||
|
|
e238e3d55a | ||
|
|
2e4624b415 | ||
|
|
d088d744ad | ||
|
|
233072fc1e | ||
|
|
283500ff9f | ||
|
|
c45d7a707d | ||
|
|
057411c56a | ||
|
|
89a78be51f | ||
|
|
aefc0c0429 | ||
|
|
8ce610bc96 | ||
|
|
6b6d035d8f | ||
|
|
d1f74b9aff | ||
|
|
3b924fabee | ||
|
|
067814102c | ||
|
|
d179fd69ca | ||
|
|
63761614eb | ||
|
|
221e23c6c1 | ||
|
|
d4cda29af1 | ||
|
|
62ec28ce4f | ||
|
|
a946724bbf | ||
|
|
015dc51fe3 | ||
|
|
1a647abf0b | ||
|
|
b23d3a5ad4 | ||
|
|
d533c7e9b9 | ||
|
|
d0486c8bc2 | ||
|
|
ec0a945cf9 | ||
|
|
8ab565a4be | ||
|
|
92dc959224 | ||
|
|
baf93b02c4 | ||
|
|
5d178954c9 | ||
|
|
ac921f0385 | ||
|
|
21c1fe5290 | ||
|
|
2db1cc807b | ||
|
|
dae244ad89 | ||
|
|
b2505f7db7 | ||
|
|
838950ee44 | ||
|
|
4d5a8d6557 | ||
|
|
cd30f98fd2 | ||
|
|
f867000f56 | ||
|
|
f0bda06f43 | ||
|
|
c3c61ea017 | ||
|
|
45addfe96d | ||
|
|
7096e47513 | ||
|
|
ce374ba877 | ||
|
|
0a19a49dfe | ||
|
|
443b0cad96 | ||
|
|
74843695eb | ||
|
|
0befb51327 | ||
|
|
dc31a72f50 | ||
|
|
7fad617dc1 | ||
|
|
df983b7483 | ||
|
|
cdf4cd7068 | ||
|
|
223084e42b | ||
|
|
201d23f285 | ||
|
|
82f7bbbd93 | ||
|
|
bf497376ee | ||
|
|
3653d01f2a | ||
|
|
aa69c81f29 | ||
|
|
227e0a406d | ||
|
|
3b7b646563 | ||
|
|
0039b965db | ||
|
|
46982d612f | ||
|
|
c483803d1b | ||
|
|
edfd82f5ff | ||
|
|
fa265230a2 | ||
|
|
b2747af543 | ||
|
|
bfacb2e34f | ||
|
|
2e6bb0e9c3 | ||
|
|
552e4591f5 | ||
|
|
02a0b43014 | ||
|
|
760f726e51 | ||
|
|
bfeaae2235 | ||
|
|
b25f7802de | ||
|
|
3cc23eee06 | ||
|
|
b9d8af07e6 | ||
|
|
1158e56551 | ||
|
|
5c82bf6831 | ||
|
|
0533cf4706 | ||
|
|
3bd55199cd | ||
|
|
fa5423b169 | ||
|
|
7d0ef00420 | ||
|
|
0cc4eae0e6 | ||
|
|
82ce8488bb | ||
|
|
d6b6ab11f0 | ||
|
|
40d98ebf50 |
+1
-1
@@ -47,4 +47,4 @@ deploy_doc "e7cfc1a" v2.9.0
|
||||
deploy_doc "7cb203f" v2.9.1
|
||||
deploy_doc "10d7239" v2.10.0
|
||||
deploy_doc "b42586e" v2.11.0
|
||||
deploy_doc "b0892fa" #v3.0.2 Latest stable release
|
||||
deploy_doc "1158e56" #v3.0.2 Latest stable release
|
||||
@@ -51,11 +51,4 @@ jobs:
|
||||
USE_CUDA: yes
|
||||
run: |
|
||||
source .env/bin/activate
|
||||
python -m pytest -n 2 --dist=loadfile -s ./tests/ | tee output.txt
|
||||
- name: cat output.txt
|
||||
run: cat output.txt
|
||||
- name: Upload output.txt
|
||||
uses: actions/upload-artifact@v1
|
||||
with:
|
||||
name: pytest_output
|
||||
path: output.txt
|
||||
python -m pytest -n 2 --dist=loadfile -s ./tests/
|
||||
|
||||
@@ -46,11 +46,14 @@ jobs:
|
||||
USE_CUDA: yes
|
||||
run: |
|
||||
source .env/bin/activate
|
||||
python -m pytest -n 1 --dist=loadfile -s ./tests/ | tee output.txt
|
||||
- name: cat output.txt
|
||||
run: cat output.txt
|
||||
- name: Upload output.txt
|
||||
uses: actions/upload-artifact@v1
|
||||
with:
|
||||
name: pytest_output
|
||||
path: output.txt
|
||||
python -m pytest -n 1 --dist=loadfile -s ./tests/
|
||||
- name: Run examples tests on GPU
|
||||
env:
|
||||
TF_FORCE_GPU_ALLOW_GROWTH: "true"
|
||||
OMP_NUM_THREADS: 1
|
||||
RUN_SLOW: yes
|
||||
USE_CUDA: yes
|
||||
run: |
|
||||
source .env/bin/activate
|
||||
pip install -r examples/requirements.txt
|
||||
python -m pytest -n 1 --dist=loadfile -s examples
|
||||
|
||||
+2
-2
@@ -66,7 +66,7 @@ If you are willing to contribute the model yourself, let us know so we can best
|
||||
guide you.
|
||||
|
||||
We have added a **detailed guide and templates** to guide you in the process of adding a new model. You can find them
|
||||
in the [`templates`](https://github.com/huggingface/transformers/templates) folder.
|
||||
in the [`templates`](https://github.com/huggingface/transformers/tree/master/templates) folder.
|
||||
|
||||
### Do you want a new feature (that is not a model)?
|
||||
|
||||
@@ -88,7 +88,7 @@ If your issue is well written we're already 80% of the way there by the time you
|
||||
post it.
|
||||
|
||||
We have added **templates** to guide you in the process of adding a new example script for training or testing the
|
||||
models in the library. You can find them in the [`templates`](https://github.com/huggingface/transformers/templates)
|
||||
models in the library. You can find them in the [`templates`](https://github.com/huggingface/transformers/tree/master/templates)
|
||||
folder.
|
||||
|
||||
## Start contributing! (Pull Requests)
|
||||
|
||||
@@ -149,6 +149,7 @@ function addHfMenu() {
|
||||
<div class="menu">
|
||||
<a href="/welcome">🔥 Sign in</a>
|
||||
<a href="/models">🚀 Models</a>
|
||||
<a href="http://discuss.huggingface.co">💬 Forum</a>
|
||||
</div>
|
||||
`;
|
||||
document.body.insertAdjacentHTML('afterbegin', div);
|
||||
|
||||
@@ -173,6 +173,7 @@ conversion utilities for the following models:
|
||||
:caption: Package Reference
|
||||
|
||||
main_classes/configuration
|
||||
main_classes/output
|
||||
main_classes/model
|
||||
main_classes/tokenizer
|
||||
main_classes/pipelines
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
Configuration
|
||||
----------------------------------------------------
|
||||
|
||||
The base class ``PretrainedConfig`` implements the common methods for loading/saving a configuration either from a local file or directory, or from a pretrained model configuration provided by the library (downloaded from HuggingFace's AWS S3 repository).
|
||||
The base class ``PretrainedConfig`` implements the common methods for loading/saving a configuration either from a
|
||||
local file or directory, or from a pretrained model configuration provided by the library (downloaded from
|
||||
HuggingFace's AWS S3 repository).
|
||||
|
||||
``PretrainedConfig``
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
Model outputs
|
||||
-------------
|
||||
|
||||
PyTorch models have outputs that are instances of subclasses of :class:`~transformers.file_utils.ModelOutput`. Those
|
||||
are data structures containing all the information returned by the model, but that can also be used as tuples or
|
||||
dictionaries.
|
||||
|
||||
Let's see of this looks on an example:
|
||||
|
||||
.. code-block::
|
||||
|
||||
from transformers import BertTokenizer, BertForSequenceClassification
|
||||
import torch
|
||||
|
||||
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
|
||||
model = BertForSequenceClassification.from_pretrained('bert-base-uncased')
|
||||
|
||||
inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
||||
labels = torch.tensor([1]).unsqueeze(0) # Batch size 1
|
||||
outputs = model(**inputs, labels=labels)
|
||||
|
||||
The ``outputs`` object is a :class:`~transformers.modeling_outputs.SequenceClassifierOutput`, as we can see in the
|
||||
documentation of that class below, it means it has an optional ``loss``, a ``logits`` an optional ``hidden_states`` and
|
||||
an optional ``attentions`` attribute. Here we have the ``loss`` since we passed along ``labels``, but we don't have
|
||||
``hidden_states`` and ``attentions`` because we didn't pass ``output_hidden_states=True`` or
|
||||
``output_attentions=True``.
|
||||
|
||||
You can access each attribute as you would usually do, and if that attribute has not been returned by the model, you
|
||||
will get ``None``. Here for instance ``outputs.loss`` is the loss computed by the model, and ``outputs.attentions`` is
|
||||
``None``.
|
||||
|
||||
When considering our ``outputs`` object as tuple, it only considers the attributes that don't have ``None`` values.
|
||||
Here for instance, it has two elements, ``loss`` then ``logits``, so
|
||||
|
||||
.. code-block::
|
||||
|
||||
outputs[:2]
|
||||
|
||||
will return the tuple ``(outputs.loss, outputs.logits)`` for instance.
|
||||
|
||||
When considering our ``outputs`` object as dictionary, it only considers the attributes that don't have ``None``
|
||||
values. Here for instance, it has two keys that are ``loss`` and ``logits``.
|
||||
|
||||
We document here the generic model outputs that are used by more than one model type. Specific output types are
|
||||
documented on their corresponding model page.
|
||||
|
||||
``ModelOutput``
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.file_utils.ModelOutput
|
||||
:members:
|
||||
|
||||
``BaseModelOutput``
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_outputs.BaseModelOutput
|
||||
:members:
|
||||
|
||||
``BaseModelOutputWithPooling``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_outputs.BaseModelOutputWithPooling
|
||||
:members:
|
||||
|
||||
``BaseModelOutputWithPast``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_outputs.BaseModelOutputWithPast
|
||||
:members:
|
||||
|
||||
``Seq2SeqModelOutput``
|
||||
~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_outputs.Seq2SeqModelOutput
|
||||
:members:
|
||||
|
||||
``CausalLMOutput``
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_outputs.CausalLMOutput
|
||||
:members:
|
||||
|
||||
``CausalLMOutputWithPast``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_outputs.CausalLMOutputWithPast
|
||||
:members:
|
||||
|
||||
``MaskedLMOutput``
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_outputs.MaskedLMOutput
|
||||
:members:
|
||||
|
||||
``Seq2SeqLMOutput``
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_outputs.Seq2SeqLMOutput
|
||||
:members:
|
||||
|
||||
``NextSentencePredictorOutput``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_outputs.NextSentencePredictorOutput
|
||||
:members:
|
||||
|
||||
``SequenceClassifierOutput``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_outputs.SequenceClassifierOutput
|
||||
:members:
|
||||
|
||||
``Seq2SeqSequenceClassifierOutput``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_outputs.Seq2SeqSequenceClassifierOutput
|
||||
:members:
|
||||
|
||||
``MultipleChoiceModelOutput``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_outputs.MultipleChoiceModelOutput
|
||||
:members:
|
||||
|
||||
``TokenClassifierOutput``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_outputs.TokenClassifierOutput
|
||||
:members:
|
||||
|
||||
``QuestionAnsweringModelOutput``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_outputs.QuestionAnsweringModelOutput
|
||||
:members:
|
||||
|
||||
``Seq2SeqQuestionAnsweringModelOutput``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_outputs.Seq2SeqQuestionAnsweringModelOutput
|
||||
:members:
|
||||
@@ -47,6 +47,13 @@ AlbertTokenizer
|
||||
create_token_type_ids_from_sequences, save_vocabulary
|
||||
|
||||
|
||||
Albert specific outputs
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_albert.AlbertForPretrainingOutput
|
||||
:members:
|
||||
|
||||
|
||||
AlbertModel
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
@@ -54,6 +61,13 @@ AlbertModel
|
||||
:members:
|
||||
|
||||
|
||||
AlbertForPreTraining
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.AlbertForPreTraining
|
||||
:members:
|
||||
|
||||
|
||||
AlbertForMaskedLM
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
@@ -96,6 +110,13 @@ TFAlbertModel
|
||||
:members:
|
||||
|
||||
|
||||
TFAlbertForPreTraining
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.TFAlbertForPreTraining
|
||||
:members:
|
||||
|
||||
|
||||
TFAlbertForMaskedLM
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
||||
@@ -59,6 +59,13 @@ BertTokenizerFast
|
||||
:members:
|
||||
|
||||
|
||||
Bert specific outputs
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_bert.BertForPretrainingOutput
|
||||
:members:
|
||||
|
||||
|
||||
BertModel
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
||||
@@ -69,6 +69,19 @@ DPRReaderTokenizerFast
|
||||
:members:
|
||||
|
||||
|
||||
DPR specific outputs
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_dpr.DPRContextEncoderOutput
|
||||
:members:
|
||||
|
||||
.. autoclass:: transformers.modeling_dpr.DPRQuestionEncoderOutput
|
||||
:members:
|
||||
|
||||
.. autoclass:: transformers.modeling_dpr.DPRReaderOutput
|
||||
:members:
|
||||
|
||||
|
||||
DPRContextEncoder
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
||||
@@ -71,6 +71,13 @@ ElectraTokenizerFast
|
||||
:members:
|
||||
|
||||
|
||||
Electra specific outputs
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_electra.ElectraForPretrainingOutput
|
||||
:members:
|
||||
|
||||
|
||||
ElectraModel
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
||||
@@ -61,6 +61,13 @@ FlaubertForSequenceClassification
|
||||
:members:
|
||||
|
||||
|
||||
FlaubertForTokenClassification
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.FlaubertForTokenClassification
|
||||
:members:
|
||||
|
||||
|
||||
FlaubertForQuestionAnsweringSimple
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
@@ -114,4 +121,4 @@ TFFlaubertForQuestionAnsweringSimple
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.TFFlaubertForQuestionAnsweringSimple
|
||||
:members:
|
||||
:members:
|
||||
|
||||
@@ -71,6 +71,13 @@ OpenAIGPTTokenizerFast
|
||||
:members:
|
||||
|
||||
|
||||
OpenAI specific outputs
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_openai.OpenAIGPTDoubleHeadsModelOutput
|
||||
:members:
|
||||
|
||||
|
||||
OpenAIGPTModel
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
||||
@@ -58,6 +58,13 @@ GPT2TokenizerFast
|
||||
:members:
|
||||
|
||||
|
||||
GPT2 specific outputs
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_gpt2.GPT2DoubleHeadsModelOutput
|
||||
:members:
|
||||
|
||||
|
||||
GPT2Model
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
||||
@@ -56,6 +56,13 @@ MobileBertTokenizerFast
|
||||
:members:
|
||||
|
||||
|
||||
MobileBert specific outputs
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_mobilebert.MobileBertForPretrainingOutput
|
||||
:members:
|
||||
|
||||
|
||||
MobileBertModel
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
||||
@@ -54,6 +54,16 @@ TransfoXLTokenizerFast
|
||||
:members:
|
||||
|
||||
|
||||
TransfoXL specific outputs
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_transfo_xl.TransfoXLModelOutput
|
||||
:members:
|
||||
|
||||
.. autoclass:: transformers.modeling_transfo_xl.TransfoXLLMHeadModelOutput
|
||||
:members:
|
||||
|
||||
|
||||
TransfoXLModel
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
||||
@@ -46,6 +46,14 @@ XLMTokenizer
|
||||
:members: build_inputs_with_special_tokens, get_special_tokens_mask,
|
||||
create_token_type_ids_from_sequences, save_vocabulary
|
||||
|
||||
|
||||
XLM specific outputs
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_xlm.XLMForQuestionAnsweringOutput
|
||||
:members:
|
||||
|
||||
|
||||
XLMModel
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
||||
@@ -50,6 +50,31 @@ XLNetTokenizer
|
||||
create_token_type_ids_from_sequences, save_vocabulary
|
||||
|
||||
|
||||
XLNet specific outputs
|
||||
~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. autoclass:: transformers.modeling_xlnet.XLNetModelOutput
|
||||
:members:
|
||||
|
||||
.. autoclass:: transformers.modeling_xlnet.XLNetLMHeadModelOutput
|
||||
:members:
|
||||
|
||||
.. autoclass:: transformers.modeling_xlnet.XLNetForSequenceClassificationOutput
|
||||
:members:
|
||||
|
||||
.. autoclass:: transformers.modeling_xlnet.XLNetForMultipleChoiceOutput
|
||||
:members:
|
||||
|
||||
.. autoclass:: transformers.modeling_xlnet.XLNetForTokenClassificationOutput
|
||||
:members:
|
||||
|
||||
.. autoclass:: transformers.modeling_xlnet.XLNetForQuestionAnsweringSimpleOutput
|
||||
:members:
|
||||
|
||||
.. autoclass:: transformers.modeling_xlnet.XLNetForQuestionAnsweringOutput
|
||||
:members:
|
||||
|
||||
|
||||
XLNetModel
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@ Original GPT
|
||||
<a href="https://huggingface.co/models?filter=openai-gpt">
|
||||
<img alt="Models" src="https://img.shields.io/badge/All_model_pages-openai--gpt-blueviolet">
|
||||
</a>
|
||||
<a href="model_doc/gpt">
|
||||
<a href="model_doc/gpt.html">
|
||||
<img alt="Doc" src="https://img.shields.io/badge/Model_documentation-openai--gpt-blueviolet">
|
||||
</a>
|
||||
|
||||
@@ -75,7 +75,7 @@ GPT-2
|
||||
<a href="https://huggingface.co/models?filter=gpt2">
|
||||
<img alt="Models" src="https://img.shields.io/badge/All_model_pages-gpt2-blueviolet">
|
||||
</a>
|
||||
<a href="model_doc/gpt2">
|
||||
<a href="model_doc/gpt2.html">
|
||||
<img alt="Doc" src="https://img.shields.io/badge/Model_documentation-gpt2-blueviolet">
|
||||
</a>
|
||||
|
||||
@@ -96,7 +96,7 @@ CTRL
|
||||
<a href="https://huggingface.co/models?filter=ctrl">
|
||||
<img alt="Models" src="https://img.shields.io/badge/All_model_pages-ctrl-blueviolet">
|
||||
</a>
|
||||
<a href="model_doc/ctrl">
|
||||
<a href="model_doc/ctrl.html">
|
||||
<img alt="Doc" src="https://img.shields.io/badge/Model_documentation-ctrl-blueviolet">
|
||||
</a>
|
||||
|
||||
@@ -117,7 +117,7 @@ Transformer-XL
|
||||
<a href="https://huggingface.co/models?filter=transfo-xl">
|
||||
<img alt="Models" src="https://img.shields.io/badge/All_model_pages-transfo--xl-blueviolet">
|
||||
</a>
|
||||
<a href="model_doc/transformerxl">
|
||||
<a href="model_doc/transformerxl.html">
|
||||
<img alt="Doc" src="https://img.shields.io/badge/Model_documentation-transfo--xl-blueviolet">
|
||||
</a>
|
||||
|
||||
@@ -148,7 +148,7 @@ Reformer
|
||||
<a href="https://huggingface.co/models?filter=reformer">
|
||||
<img alt="Models" src="https://img.shields.io/badge/All_model_pages-reformer-blueviolet">
|
||||
</a>
|
||||
<a href="model_doc/reformer">
|
||||
<a href="model_doc/reformer.html">
|
||||
<img alt="Doc" src="https://img.shields.io/badge/Model_documentation-reformer-blueviolet">
|
||||
</a>
|
||||
|
||||
@@ -183,7 +183,7 @@ XLNet
|
||||
<a href="https://huggingface.co/models?filter=xlnet">
|
||||
<img alt="Models" src="https://img.shields.io/badge/All_model_pages-xlnet-blueviolet">
|
||||
</a>
|
||||
<a href="model_doc/xlnet">
|
||||
<a href="model_doc/xlnet.html">
|
||||
<img alt="Doc" src="https://img.shields.io/badge/Model_documentation-xlnet-blueviolet">
|
||||
</a>
|
||||
|
||||
@@ -217,7 +217,7 @@ BERT
|
||||
<a href="https://huggingface.co/models?filter=bert">
|
||||
<img alt="Models" src="https://img.shields.io/badge/All_model_pages-bert-blueviolet">
|
||||
</a>
|
||||
<a href="model_doc/bert">
|
||||
<a href="model_doc/bert.html">
|
||||
<img alt="Doc" src="https://img.shields.io/badge/Model_documentation-bert-blueviolet">
|
||||
</a>
|
||||
|
||||
@@ -246,7 +246,7 @@ ALBERT
|
||||
<a href="https://huggingface.co/models?filter=albert">
|
||||
<img alt="Models" src="https://img.shields.io/badge/All_model_pages-albert-blueviolet">
|
||||
</a>
|
||||
<a href="model_doc/albert">
|
||||
<a href="model_doc/albert.html">
|
||||
<img alt="Doc" src="https://img.shields.io/badge/Model_documentation-albert-blueviolet">
|
||||
</a>
|
||||
|
||||
@@ -275,7 +275,7 @@ RoBERTa
|
||||
<a href="https://huggingface.co/models?filter=roberta">
|
||||
<img alt="Models" src="https://img.shields.io/badge/All_model_pages-roberta-blueviolet">
|
||||
</a>
|
||||
<a href="model_doc/roberta">
|
||||
<a href="model_doc/roberta.html">
|
||||
<img alt="Doc" src="https://img.shields.io/badge/Model_documentation-roberta-blueviolet">
|
||||
</a>
|
||||
|
||||
@@ -301,7 +301,7 @@ DistilBERT
|
||||
<a href="https://huggingface.co/models?filter=distilbert">
|
||||
<img alt="Models" src="https://img.shields.io/badge/All_model_pages-distilbert-blueviolet">
|
||||
</a>
|
||||
<a href="model_doc/distilbert">
|
||||
<a href="model_doc/distilbert.html">
|
||||
<img alt="Doc" src="https://img.shields.io/badge/Model_documentation-distilbert-blueviolet">
|
||||
</a>
|
||||
|
||||
@@ -326,7 +326,7 @@ XLM
|
||||
<a href="https://huggingface.co/models?filter=xlm">
|
||||
<img alt="Models" src="https://img.shields.io/badge/All_model_pages-xlm-blueviolet">
|
||||
</a>
|
||||
<a href="model_doc/xlm">
|
||||
<a href="model_doc/xlm.html">
|
||||
<img alt="Doc" src="https://img.shields.io/badge/Model_documentation-xlm-blueviolet">
|
||||
</a>
|
||||
|
||||
@@ -361,7 +361,7 @@ XLM-RoBERTa
|
||||
<a href="https://huggingface.co/models?filter=xlm-roberta">
|
||||
<img alt="Models" src="https://img.shields.io/badge/All_model_pages-xlm--roberta-blueviolet">
|
||||
</a>
|
||||
<a href="model_doc/xlmroberta">
|
||||
<a href="model_doc/xlmroberta.html">
|
||||
<img alt="Doc" src="https://img.shields.io/badge/Model_documentation-xlm--roberta-blueviolet">
|
||||
</a>
|
||||
|
||||
@@ -383,7 +383,7 @@ FlauBERT
|
||||
<a href="https://huggingface.co/models?filter=flaubert">
|
||||
<img alt="Models" src="https://img.shields.io/badge/All_model_pages-flaubert-blueviolet">
|
||||
</a>
|
||||
<a href="model_doc/flaubert">
|
||||
<a href="model_doc/flaubert.html">
|
||||
<img alt="Doc" src="https://img.shields.io/badge/Model_documentation-flaubert-blueviolet">
|
||||
</a>
|
||||
|
||||
@@ -401,7 +401,7 @@ ELECTRA
|
||||
<a href="https://huggingface.co/models?filter=electra">
|
||||
<img alt="Models" src="https://img.shields.io/badge/All_model_pages-electra-blueviolet">
|
||||
</a>
|
||||
<a href="model_doc/electra">
|
||||
<a href="model_doc/electra.html">
|
||||
<img alt="Doc" src="https://img.shields.io/badge/Model_documentation-electra-blueviolet">
|
||||
</a>
|
||||
|
||||
@@ -427,7 +427,7 @@ Longformer
|
||||
<a href="https://huggingface.co/models?filter=longformer">
|
||||
<img alt="Models" src="https://img.shields.io/badge/All_model_pages-longformer-blueviolet">
|
||||
</a>
|
||||
<a href="model_doc/longformer">
|
||||
<a href="model_doc/longformer.html">
|
||||
<img alt="Doc" src="https://img.shields.io/badge/Model_documentation-longformer-blueviolet">
|
||||
</a>
|
||||
|
||||
@@ -461,7 +461,7 @@ BART
|
||||
<a href="https://huggingface.co/models?filter=bart">
|
||||
<img alt="Models" src="https://img.shields.io/badge/All_model_pages-bart-blueviolet">
|
||||
</a>
|
||||
<a href="model_doc/bart">
|
||||
<a href="model_doc/bart.html">
|
||||
<img alt="Doc" src="https://img.shields.io/badge/Model_documentation-bart-blueviolet">
|
||||
</a>
|
||||
|
||||
@@ -488,7 +488,7 @@ MarianMT
|
||||
<a href="https://huggingface.co/models?filter=marian">
|
||||
<img alt="Models" src="https://img.shields.io/badge/All_model_pages-marian-blueviolet">
|
||||
</a>
|
||||
<a href="model_doc/marian">
|
||||
<a href="model_doc/marian.html">
|
||||
<img alt="Doc" src="https://img.shields.io/badge/Model_documentation-marian-blueviolet">
|
||||
</a>
|
||||
|
||||
@@ -506,7 +506,7 @@ T5
|
||||
<a href="https://huggingface.co/models?filter=t5">
|
||||
<img alt="Models" src="https://img.shields.io/badge/All_model_pages-t5-blueviolet">
|
||||
</a>
|
||||
<a href="model_doc/t5">
|
||||
<a href="model_doc/t5.html">
|
||||
<img alt="Doc" src="https://img.shields.io/badge/Model_documentation-t5-blueviolet">
|
||||
</a>
|
||||
|
||||
@@ -555,7 +555,7 @@ model know which part of the input vector corresponds to the text or the image.
|
||||
The pretrained model only works for classification.
|
||||
|
||||
..
|
||||
More information in this :doc:`model documentation </model_doc/mmbt>`.
|
||||
More information in this :doc:`model documentation </model_doc/mmbt.html>`.
|
||||
TODO: write this page
|
||||
|
||||
More technical aspects
|
||||
|
||||
@@ -123,7 +123,7 @@ are 512 preceding tokens available to condition on).
|
||||
stride = 512
|
||||
|
||||
lls = []
|
||||
for i in tqdm(range(1, encodings.input_ids.size(1), stride)):
|
||||
for i in tqdm(range(0, encodings.input_ids.size(1), stride)):
|
||||
begin_loc = max(i + stride - max_length, 0)
|
||||
end_loc = i + stride
|
||||
input_ids = encodings.input_ids[:,begin_loc:end_loc].to(device)
|
||||
|
||||
+28
-15
@@ -108,11 +108,11 @@ any other model from the model hub):
|
||||
>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
|
||||
>>> model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
||||
>>> tokenizer = AutoTokenizer.from_pretrained(model_name)
|
||||
>>> pipe = pipeline('sentiment-analysis', model=model, tokenizer=tokenizer)
|
||||
>>> classifier = pipeline('sentiment-analysis', model=model, tokenizer=tokenizer)
|
||||
>>> ## TENSORFLOW CODE
|
||||
>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
|
||||
>>> # This model only exists in PyTorch, so we use the `from_pt` flag to import that model in TensorFlow.
|
||||
>>> model = TFAutoModelForSequenceClassification.from_pretrained(model_name, from_pt=True)
|
||||
>>> model = TFAutoModelForSequenceClassification.from_pretrained(model_name, from_pt=True)
|
||||
>>> tokenizer = AutoTokenizer.from_pretrained(model_name)
|
||||
>>> classifier = pipeline('sentiment-analysis', model=model, tokenizer=tokenizer)
|
||||
|
||||
@@ -191,7 +191,7 @@ and get tensors back. You can specify all of that to the tokenizer:
|
||||
... return_tensors="tf"
|
||||
... )
|
||||
|
||||
The padding is automatically applied on the side the model expect it (in this case, on the right), with the
|
||||
The padding is automatically applied on the side expected by the model (in this case, on the right), with the
|
||||
padding token the model was pretrained with. The attention mask is also adapted to take the padding into account:
|
||||
|
||||
.. code-block::
|
||||
@@ -212,9 +212,9 @@ You can learn more about tokenizers :doc:`here <preprocessing>`.
|
||||
Using the model
|
||||
^^^^^^^^^^^^^^^
|
||||
|
||||
Once your input has been preprocessed by the tokenizer, you can directly send it to the model. As we mentioned, it will
|
||||
contain all the relevant information the model needs. If you're using a TensorFlow model, you can directly pass the
|
||||
dictionary keys to tensor, for a PyTorch model, you need to unpack the dictionary by adding :obj:`**`.
|
||||
Once your input has been preprocessed by the tokenizer, you can send it directly to the model. As we mentioned, it will
|
||||
contain all the relevant information the model needs. If you're using a TensorFlow model, you can pass the
|
||||
dictionary keys directly to tensor, for a PyTorch model, you need to unpack the dictionary by adding :obj:`**`.
|
||||
|
||||
.. code-block::
|
||||
|
||||
@@ -230,13 +230,18 @@ final activations of the model.
|
||||
|
||||
>>> ## PYTORCH CODE
|
||||
>>> print(pt_outputs)
|
||||
(tensor([[-4.0833, 4.3364],
|
||||
[ 0.0818, -0.0418]], grad_fn=<AddmmBackward>),)
|
||||
SequenceClassifierOutput(loss=None, logits=tensor([[-4.0833, 4.3364],
|
||||
[ 0.0818, -0.0418]], grad_fn=<AddmmBackward>), hidden_states=None, attentions=None)
|
||||
>>> ## TENSORFLOW CODE
|
||||
>>> print(tf_outputs)
|
||||
(<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
|
||||
array([[-4.0832963 , 4.3364134 ],
|
||||
[ 0.08181238, -0.04178794]], dtype=float32)>,)
|
||||
array([[-4.0832963 , 4.336414 ],
|
||||
[ 0.08181786, -0.04179301]], dtype=float32)>,)
|
||||
|
||||
The model can return more than just the final activations, which is why the PyTorch output is a special class and the
|
||||
TensorFlow output is a tuple. Here we only asked for the final activations, so we get a tuple with one element on the
|
||||
TensorFlow side and a :class:`~transformers.modeling_outputs.SequenceClassifierOutput` with just the ``logits`` field
|
||||
filled on the PyTorch side.
|
||||
|
||||
.. note::
|
||||
|
||||
@@ -249,7 +254,7 @@ Let's apply the SoftMax activation to get predictions.
|
||||
|
||||
>>> ## PYTORCH CODE
|
||||
>>> import torch.nn.functional as F
|
||||
>>> pt_predictions = F.softmax(pt_outputs[0], dim=-1)
|
||||
>>> pt_predictions = F.softmax(pt_outputs.logits, dim=-1)
|
||||
>>> ## TENSORFLOW CODE
|
||||
>>> import tensorflow as tf
|
||||
>>> tf_predictions = tf.nn.softmax(tf_outputs[0], axis=-1)
|
||||
@@ -262,7 +267,7 @@ We can see we get the numbers from before:
|
||||
>>> print(tf_predictions)
|
||||
tf.Tensor(
|
||||
[[2.2042994e-04 9.9977952e-01]
|
||||
[5.3086078e-01 4.6913919e-01]], shape=(2, 2), dtype=float32)
|
||||
[5.3086340e-01 4.6913657e-01]], shape=(2, 2), dtype=float32)
|
||||
>>> ## PYTORCH CODE
|
||||
>>> print(pt_predictions)
|
||||
tensor([[2.2043e-04, 9.9978e-01],
|
||||
@@ -285,7 +290,13 @@ training loop. 🤗 Transformers also provides a :class:`~transformers.Trainer`
|
||||
you are using TensorFlow) class to help with your training (taking care of things such as distributed training, mixed
|
||||
precision, etc.). See the :doc:`training tutorial <training>` for more details.
|
||||
|
||||
Once your model is fine-tuned, you can save it with its tokenizer the following way:
|
||||
.. note::
|
||||
|
||||
Pytorch model outputs are special dataclasses so that you can get autocompletion for their attributes in an IDE.
|
||||
They also behave like a tuple or a dictionary (e.g., you can index with an integer, a slice or a string) in which
|
||||
case the attributes not set (that have :obj:`None` values) are ignored.
|
||||
|
||||
Once your model is fine-tuned, you can save it with its tokenizer in the following way:
|
||||
|
||||
::
|
||||
|
||||
@@ -329,7 +340,9 @@ pretrained model. Behind the scenes, the library has one model class per combina
|
||||
code is easy to access and tweak if you need to.
|
||||
|
||||
In our previous example, the model was called "distilbert-base-uncased-finetuned-sst-2-english", which means it's
|
||||
using the :doc:`DistilBERT </model_doc/distilbert>` architecture. The model automatically created is then a
|
||||
using the :doc:`DistilBERT </model_doc/distilbert>` architecture. As
|
||||
:class:`~transformers.AutoModelForSequenceClassification` (or :class:`~transformers.TFAutoModelForSequenceClassification`
|
||||
if you are using TensorFlow)` was used, the model automatically created is then a
|
||||
:class:`~transformers.DistilBertForSequenceClassification`. You can look at its documentation for all details relevant
|
||||
to that specific model, or browse the source code. This is how you would directly instantiate model and tokenizer
|
||||
without the auto magic:
|
||||
@@ -352,7 +365,7 @@ Customizing the model
|
||||
|
||||
If you want to change how the model itself is built, you can define your custom configuration class. Each architecture
|
||||
comes with its own relevant configuration (in the case of DistilBERT, :class:`~transformers.DistilBertConfig`) which
|
||||
allows you to specify any of the hidden dimension, dropout rate etc. If you do core modifications, like changing the
|
||||
allows you to specify any of the hidden dimension, dropout rate, etc. If you do core modifications, like changing the
|
||||
hidden size, you won't be able to use a pretrained model anymore and will need to train from scratch. You would then
|
||||
instantiate the model directly from this configuration.
|
||||
|
||||
|
||||
@@ -98,8 +98,8 @@ of each other. The process is the following:
|
||||
>>> paraphrase = tokenizer(sequence_0, sequence_2, return_tensors="pt")
|
||||
>>> not_paraphrase = tokenizer(sequence_0, sequence_1, return_tensors="pt")
|
||||
|
||||
>>> paraphrase_classification_logits = model(**paraphrase)[0]
|
||||
>>> not_paraphrase_classification_logits = model(**not_paraphrase)[0]
|
||||
>>> paraphrase_classification_logits = model(**paraphrase).logits
|
||||
>>> not_paraphrase_classification_logits = model(**not_paraphrase).logits
|
||||
|
||||
>>> paraphrase_results = torch.softmax(paraphrase_classification_logits, dim=1).tolist()[0]
|
||||
>>> not_paraphrase_results = torch.softmax(not_paraphrase_classification_logits, dim=1).tolist()[0]
|
||||
@@ -375,7 +375,7 @@ Here is an example doing masked language modeling using a model and a tokenizer.
|
||||
>>> input = tokenizer.encode(sequence, return_tensors="pt")
|
||||
>>> mask_token_index = torch.where(input == tokenizer.mask_token_id)[1]
|
||||
|
||||
>>> token_logits = model(input)[0]
|
||||
>>> token_logits = model(input).logits
|
||||
>>> mask_token_logits = token_logits[0, mask_token_index, :]
|
||||
|
||||
>>> top_5_tokens = torch.topk(mask_token_logits, 5, dim=1).indices[0].tolist()
|
||||
@@ -436,7 +436,7 @@ Here is an example using the tokenizer and model and leveraging the :func:`~tran
|
||||
>>> input_ids = tokenizer.encode(sequence, return_tensors="pt")
|
||||
|
||||
>>> # get logits of last hidden state
|
||||
>>> next_token_logits = model(input_ids)[0][:, -1, :]
|
||||
>>> next_token_logits = model(input_ids).logits[:, -1, :]
|
||||
|
||||
>>> # filter
|
||||
>>> filtered_next_token_logits = top_k_top_p_filtering(next_token_logits, top_k=50, top_p=1.0)
|
||||
@@ -666,7 +666,7 @@ Here is an example doing named entity recognition using a model and a tokenizer.
|
||||
>>> tokens = tokenizer.tokenize(tokenizer.decode(tokenizer.encode(sequence)))
|
||||
>>> inputs = tokenizer.encode(sequence, return_tensors="pt")
|
||||
|
||||
>>> outputs = model(inputs)[0]
|
||||
>>> outputs = model(inputs).logits
|
||||
>>> predictions = torch.argmax(outputs, dim=2)
|
||||
>>> ## TENSORFLOW CODE
|
||||
>>> from transformers import TFAutoModelForTokenClassification, AutoTokenizer
|
||||
|
||||
@@ -52,7 +52,7 @@ 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
|
||||
transformers models 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.
|
||||
@@ -69,7 +69,7 @@ decomposed as "annoying" and "ly". This is especially useful in agglutinative la
|
||||
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. This also enables 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:
|
||||
|
||||
@@ -110,7 +110,7 @@ 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.
|
||||
: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).
|
||||
@@ -178,7 +178,7 @@ WordPiece is the subword tokenization algorithm used for :doc:`BERT <model_doc/b
|
||||
`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.
|
||||
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
|
||||
@@ -217,7 +217,7 @@ training corpus. You can then give a probability to each tokenization (which is
|
||||
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
|
||||
Those probabilities 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
|
||||
|
||||
@@ -229,15 +229,15 @@ tokenizations of :math:`x_{i}` (with the current vocabulary), then the loss is d
|
||||
SentencePiece
|
||||
=============
|
||||
|
||||
All the methods we have been looking at so far required some from of pretrokenization, which has a central problem: not
|
||||
All the methods we have been looking at so far required some form of pretokenization, 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.
|
||||
the '▁' character, that represents space. Decoding a tokenized text is then super easy: we just have to concatenate
|
||||
all of them together and replace '▁' with space.
|
||||
|
||||
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>`.
|
||||
|
||||
@@ -99,7 +99,7 @@ backwards pass and update the weights:
|
||||
|
||||
labels = torch.tensor([1,0]).unsqueeze(0)
|
||||
outputs = model(input_ids, attention_mask=attention_mask, labels=labels)
|
||||
loss = outputs[0]
|
||||
loss = outputs.loss
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
|
||||
@@ -111,7 +111,7 @@ The following is equivalent to the previous example:
|
||||
from torch.nn import functional as F
|
||||
labels = torch.tensor([1,0]).unsqueeze(0)
|
||||
outputs = model(input_ids, attention_mask=attention_mask)
|
||||
loss = F.cross_entropy(labels, outputs[0])
|
||||
loss = F.cross_entropy(labels, outputs.logitd)
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
|
||||
|
||||
+30
-1
@@ -21,7 +21,7 @@ This is still a work-in-progress – in particular documentation is still sparse
|
||||
| [**`text-classification`**](https://github.com/huggingface/transformers/tree/master/examples/text-classification) | GLUE, XNLI | ✅ | ✅ | ✅ | [](https://colab.research.google.com/github/huggingface/blog/blob/master/notebooks/trainer/01_text_classification.ipynb)
|
||||
| [**`token-classification`**](https://github.com/huggingface/transformers/tree/master/examples/token-classification) | CoNLL NER | ✅ | ✅ | ✅ | -
|
||||
| [**`multiple-choice`**](https://github.com/huggingface/transformers/tree/master/examples/multiple-choice) | SWAG, RACE, ARC | ✅ | ✅ | - | [](https://colab.research.google.com/github/ViktorAlm/notebooks/blob/master/MPC_GPU_Demo_for_TF_and_PT.ipynb)
|
||||
| [**`question-answering`**](https://github.com/huggingface/transformers/tree/master/examples/question-answering) | SQuAD | - | ✅ | - | -
|
||||
| [**`question-answering`**](https://github.com/huggingface/transformers/tree/master/examples/question-answering) | SQuAD | ✅ | ✅ | - | -
|
||||
| [**`text-generation`**](https://github.com/huggingface/transformers/tree/master/examples/text-generation) | - | n/a | n/a | n/a | [](https://colab.research.google.com/github/huggingface/blog/blob/master/notebooks/02_how_to_generate.ipynb)
|
||||
| [**`distillation`**](https://github.com/huggingface/transformers/tree/master/examples/distillation) | All | - | - | - | -
|
||||
| [**`summarization`**](https://github.com/huggingface/transformers/tree/master/examples/seq2seq) | CNN/Daily Mail | - | - | ✅ | -
|
||||
@@ -78,3 +78,32 @@ python examples/xla_spawn.py --num_cores 8 \
|
||||
```
|
||||
|
||||
Feedback and more use cases and benchmarks involving TPUs are welcome, please share with the community.
|
||||
|
||||
## Logging & Experiment tracking
|
||||
|
||||
You can easily log and monitor your runs code. [TensorBoard](https://www.tensorflow.org/tensorboard) and [Weights & Biases](https://docs.wandb.com/library/integrations/huggingface) are currently supported.
|
||||
|
||||
To use Weights & Biases, install the wandb package with:
|
||||
|
||||
```bash
|
||||
pip install wandb
|
||||
```
|
||||
|
||||
Then log in the command line:
|
||||
|
||||
```bash
|
||||
wandb login
|
||||
```
|
||||
|
||||
If you are in Jupyter or Colab, you should login with:
|
||||
|
||||
```python
|
||||
import wandb
|
||||
wandb.login()
|
||||
```
|
||||
|
||||
Whenever you use `Trainer` or `TFTrainer` classes, your losses, evaluation metrics, model topology and gradients (for `Trainer` only) will automatically be logged.
|
||||
|
||||
For advanced configuration and examples, refer to the [W&B documentation](https://docs.wandb.com/library/integrations/huggingface).
|
||||
|
||||
When using 🤗 Transformers with PyTorch Lightning, runs can be tracked through `WandbLogger`. Refer to related [documentation & examples](https://docs.wandb.com/library/frameworks/pytorch/lightning).
|
||||
|
||||
+47
-75
@@ -1,14 +1,11 @@
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict
|
||||
|
||||
import numpy as np
|
||||
import pytorch_lightning as pl
|
||||
import torch
|
||||
from pytorch_lightning.utilities import rank_zero_info, rank_zero_only
|
||||
from pytorch_lightning.utilities import rank_zero_info
|
||||
|
||||
from transformers import (
|
||||
AdamW,
|
||||
@@ -42,14 +39,6 @@ MODEL_MODES = {
|
||||
}
|
||||
|
||||
|
||||
def set_seed(args: argparse.Namespace):
|
||||
random.seed(args.seed)
|
||||
np.random.seed(args.seed)
|
||||
torch.manual_seed(args.seed)
|
||||
if args.gpus > 0:
|
||||
torch.cuda.manual_seed_all(args.seed)
|
||||
|
||||
|
||||
class BaseTransformer(pl.LightningModule):
|
||||
def __init__(
|
||||
self,
|
||||
@@ -63,7 +52,11 @@ class BaseTransformer(pl.LightningModule):
|
||||
):
|
||||
"""Initialize a model, tokenizer and config."""
|
||||
super().__init__()
|
||||
self.hparams = hparams # TODO: move to self.save_hyperparameters()
|
||||
# TODO: move to self.save_hyperparameters()
|
||||
# self.save_hyperparameters()
|
||||
# can also expand arguments into trainer signature for easier reading
|
||||
|
||||
self.hparams = hparams
|
||||
self.step_count = 0
|
||||
self.tfmr_ckpts = {}
|
||||
self.output_dir = Path(self.hparams.output_dir)
|
||||
@@ -114,17 +107,12 @@ class BaseTransformer(pl.LightningModule):
|
||||
]
|
||||
optimizer = AdamW(optimizer_grouped_parameters, lr=self.hparams.learning_rate, eps=self.hparams.adam_epsilon)
|
||||
self.opt = optimizer
|
||||
return [optimizer]
|
||||
|
||||
def optimizer_step(self, epoch, batch_idx, optimizer, optimizer_idx, second_order_closure=None):
|
||||
if self.trainer.use_tpu:
|
||||
xm.optimizer_step(optimizer)
|
||||
else:
|
||||
optimizer.step()
|
||||
optimizer.zero_grad()
|
||||
self.lr_scheduler.step() # By default, PL will only step every epoch.
|
||||
lrs = {f"lr_group_{i}": lr for i, lr in enumerate(self.lr_scheduler.get_lr())}
|
||||
self.logger.log_metrics(lrs)
|
||||
scheduler = get_linear_schedule_with_warmup(
|
||||
self.opt, num_warmup_steps=self.hparams.warmup_steps, num_training_steps=self.total_steps
|
||||
)
|
||||
scheduler = {"scheduler": scheduler, "interval": "step", "frequency": 1}
|
||||
return [optimizer], [scheduler]
|
||||
|
||||
def test_step(self, batch, batch_nb):
|
||||
return self.validation_step(batch, batch_nb)
|
||||
@@ -132,26 +120,24 @@ class BaseTransformer(pl.LightningModule):
|
||||
def test_epoch_end(self, outputs):
|
||||
return self.validation_end(outputs)
|
||||
|
||||
def train_dataloader(self):
|
||||
def setup(self, step):
|
||||
train_batch_size = self.hparams.train_batch_size
|
||||
dataloader = self.load_dataset("train", train_batch_size)
|
||||
dataloader = self.get_dataloader("train", train_batch_size)
|
||||
self.train_loader = dataloader
|
||||
self.total_steps = (
|
||||
(len(dataloader.dataset) // (train_batch_size * max(1, self.hparams.gpus)))
|
||||
// self.hparams.accumulate_grad_batches
|
||||
* float(self.hparams.max_epochs)
|
||||
)
|
||||
|
||||
t_total = (
|
||||
(len(dataloader.dataset) // (train_batch_size * max(1, self.hparams.n_gpu)))
|
||||
// self.hparams.gradient_accumulation_steps
|
||||
* float(self.hparams.num_train_epochs)
|
||||
)
|
||||
scheduler = get_linear_schedule_with_warmup(
|
||||
self.opt, num_warmup_steps=self.hparams.warmup_steps, num_training_steps=t_total
|
||||
)
|
||||
self.lr_scheduler = scheduler
|
||||
return dataloader
|
||||
def train_dataloader(self):
|
||||
return self.train_loader
|
||||
|
||||
def val_dataloader(self):
|
||||
return self.load_dataset("dev", self.hparams.eval_batch_size)
|
||||
return self.get_dataloader("dev", self.hparams.eval_batch_size)
|
||||
|
||||
def test_dataloader(self):
|
||||
return self.load_dataset("test", self.hparams.eval_batch_size)
|
||||
return self.get_dataloader("test", self.hparams.eval_batch_size)
|
||||
|
||||
def _feature_file(self, mode):
|
||||
return os.path.join(
|
||||
@@ -201,16 +187,16 @@ class BaseTransformer(pl.LightningModule):
|
||||
parser.add_argument("--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer.")
|
||||
parser.add_argument("--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.")
|
||||
parser.add_argument("--num_workers", default=4, type=int, help="kwarg passed to DataLoader")
|
||||
parser.add_argument(
|
||||
"--num_train_epochs", default=3, type=int, help="Total number of training epochs to perform."
|
||||
)
|
||||
|
||||
parser.add_argument("--num_train_epochs", dest="max_epochs", default=3, type=int)
|
||||
parser.add_argument("--train_batch_size", default=32, type=int)
|
||||
parser.add_argument("--eval_batch_size", default=32, type=int)
|
||||
|
||||
|
||||
class LoggingCallback(pl.Callback):
|
||||
@rank_zero_only
|
||||
def on_batch_end(self, trainer, pl_module):
|
||||
lrs = {f"lr_group_{i}": lr for i, lr in enumerate(self.lr_scheduler.get_lr())}
|
||||
pl_module.logger.log_metrics(lrs)
|
||||
|
||||
def on_validation_end(self, trainer: pl.Trainer, pl_module: pl.LightningModule):
|
||||
rank_zero_info("***** Validation results *****")
|
||||
metrics = trainer.callback_metrics
|
||||
@@ -219,16 +205,15 @@ class LoggingCallback(pl.Callback):
|
||||
if key not in ["log", "progress_bar"]:
|
||||
rank_zero_info("{} = {}\n".format(key, str(metrics[key])))
|
||||
|
||||
@rank_zero_only
|
||||
def on_test_end(self, trainer: pl.Trainer, pl_module: pl.LightningModule):
|
||||
logger.info("***** Test results *****")
|
||||
rank_zero_info("***** Test results *****")
|
||||
metrics = trainer.callback_metrics
|
||||
# Log and save results to file
|
||||
output_test_results_file = os.path.join(pl_module.hparams.output_dir, "test_results.txt")
|
||||
with open(output_test_results_file, "w") as writer:
|
||||
for key in sorted(metrics):
|
||||
if key not in ["log", "progress_bar"]:
|
||||
logger.info("{} = {}\n".format(key, str(metrics[key])))
|
||||
rank_zero_info("{} = {}\n".format(key, str(metrics[key])))
|
||||
writer.write("{} = {}\n".format(key, str(metrics[key])))
|
||||
|
||||
|
||||
@@ -251,26 +236,23 @@ def add_generic_args(parser, root_dir) -> None:
|
||||
parser.add_argument(
|
||||
"--fp16_opt_level",
|
||||
type=str,
|
||||
default="O1",
|
||||
default="O2",
|
||||
help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']."
|
||||
"See details at https://nvidia.github.io/apex/amp.html",
|
||||
)
|
||||
parser.add_argument("--fast_dev_run", action="store_true")
|
||||
parser.add_argument("--gpus", type=int, default=1)
|
||||
parser.add_argument("--n_tpu_cores", type=int, default=0)
|
||||
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
||||
parser.add_argument("--n_tpu_cores", dest="tpu_cores", type=int, default=0)
|
||||
parser.add_argument("--max_grad_norm", dest="gradient_clip_val", default=1.0, type=float, help="Max gradient norm")
|
||||
parser.add_argument("--do_train", action="store_true", help="Whether to run training.")
|
||||
parser.add_argument("--do_predict", action="store_true", help="Whether to run predictions on the test set.")
|
||||
parser.add_argument(
|
||||
"--gradient_accumulation_steps",
|
||||
dest="accumulate_grad_batches",
|
||||
type=int,
|
||||
default=1,
|
||||
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
||||
)
|
||||
|
||||
parser.add_argument("--seed", type=int, default=42, help="random seed for initialization")
|
||||
parser.add_argument("--resume_from_checkpoint", type=str, default=None)
|
||||
parser.add_argument("--val_check_interval", default=1.0, type=float)
|
||||
|
||||
|
||||
def generic_train(
|
||||
@@ -283,10 +265,13 @@ def generic_train(
|
||||
logging_callback=None,
|
||||
**extra_train_kwargs
|
||||
):
|
||||
pl.seed_everything(args.seed)
|
||||
|
||||
# init model
|
||||
set_seed(args)
|
||||
odir = Path(model.hparams.output_dir)
|
||||
odir.mkdir(exist_ok=True)
|
||||
|
||||
# add custom checkpoints
|
||||
if checkpoint_callback is None:
|
||||
checkpoint_callback = pl.callbacks.ModelCheckpoint(
|
||||
filepath=args.output_dir, prefix="checkpoint", monitor="val_loss", mode="min", save_top_k=1
|
||||
@@ -296,38 +281,25 @@ def generic_train(
|
||||
|
||||
train_params = {}
|
||||
|
||||
# TODO: remove with PyTorch 1.6 since pl uses native amp
|
||||
if args.fp16:
|
||||
train_params["use_amp"] = args.fp16
|
||||
train_params["precision"] = 16
|
||||
train_params["amp_level"] = args.fp16_opt_level
|
||||
|
||||
if args.n_tpu_cores > 0:
|
||||
global xm
|
||||
import torch_xla.core.xla_model as xm
|
||||
|
||||
train_params["num_tpu_cores"] = args.n_tpu_cores
|
||||
train_params["gpus"] = 0
|
||||
|
||||
if args.gpus > 1:
|
||||
train_params["distributed_backend"] = "ddp"
|
||||
|
||||
trainer = pl.Trainer(
|
||||
logger=logger,
|
||||
accumulate_grad_batches=args.gradient_accumulation_steps,
|
||||
gpus=args.gpus,
|
||||
max_epochs=args.num_train_epochs,
|
||||
early_stop_callback=early_stopping_callback,
|
||||
gradient_clip_val=args.max_grad_norm,
|
||||
checkpoint_callback=checkpoint_callback,
|
||||
callbacks=[logging_callback] + extra_callbacks,
|
||||
fast_dev_run=args.fast_dev_run,
|
||||
val_check_interval=args.val_check_interval,
|
||||
trainer = pl.Trainer.from_argparse_args(
|
||||
args,
|
||||
weights_summary=None,
|
||||
resume_from_checkpoint=args.resume_from_checkpoint,
|
||||
callbacks=[logging_callback] + extra_callbacks,
|
||||
logger=logger,
|
||||
checkpoint_callback=checkpoint_callback,
|
||||
early_stop_callback=early_stopping_callback,
|
||||
**train_params,
|
||||
)
|
||||
|
||||
if args.do_train:
|
||||
trainer.fit(model)
|
||||
trainer.logger.log_hyperparams(args)
|
||||
trainer.logger.save()
|
||||
|
||||
return trainer
|
||||
|
||||
@@ -199,6 +199,9 @@ def train(args, train_dataset, model, tokenizer):
|
||||
{"langs": (torch.ones(batch[0].shape, dtype=torch.int64) * args.lang_id).to(args.device)}
|
||||
)
|
||||
|
||||
if isinstance(model, torch.nn.DataParallel):
|
||||
inputs["return_tuple"] = True
|
||||
|
||||
outputs = model(**inputs)
|
||||
# model outputs are always tuple in transformers (see doc)
|
||||
loss = outputs[0]
|
||||
@@ -313,7 +316,8 @@ def evaluate(args, model, tokenizer, prefix=""):
|
||||
inputs.update(
|
||||
{"langs": (torch.ones(batch[0].shape, dtype=torch.int64) * args.lang_id).to(args.device)}
|
||||
)
|
||||
|
||||
if isinstance(model, torch.nn.DataParallel):
|
||||
inputs["return_tuple"] = True
|
||||
outputs = model(**inputs)
|
||||
|
||||
for i, feature_index in enumerate(feature_indices):
|
||||
|
||||
@@ -5,7 +5,7 @@ psutil
|
||||
sacrebleu
|
||||
rouge-score
|
||||
tensorflow_datasets
|
||||
pytorch-lightning==0.8.1
|
||||
pytorch-lightning==0.8.5
|
||||
matplotlib
|
||||
git-python==1.0.3
|
||||
faiss
|
||||
@@ -13,3 +13,4 @@ streamlit
|
||||
elasticsearch
|
||||
pandas
|
||||
nlp
|
||||
wget
|
||||
|
||||
+52
-43
@@ -7,19 +7,6 @@ For `bertabs` instructions, see `bertabs/README.md`.
|
||||
|
||||
|
||||
### Data
|
||||
|
||||
CNN/DailyMail data
|
||||
```bash
|
||||
cd examples/seq2seq
|
||||
wget https://s3.amazonaws.com/datasets.huggingface.co/summarization/cnn_dm.tgz
|
||||
tar -xzvf cnn_dm.tgz
|
||||
|
||||
export CNN_DIR=${PWD}/cnn_dm
|
||||
```
|
||||
|
||||
this should make a directory called cnn_dm/ with files like `test.source`.
|
||||
To use your own data, copy that files format. Each article to be summarized is on its own line.
|
||||
|
||||
XSUM Data:
|
||||
```bash
|
||||
cd examples/seq2seq
|
||||
@@ -27,20 +14,41 @@ wget https://s3.amazonaws.com/datasets.huggingface.co/summarization/xsum.tar.gz
|
||||
tar -xzvf xsum.tar.gz
|
||||
export XSUM_DIR=${PWD}/xsum
|
||||
```
|
||||
this should make a directory called `xsum/` with files like `test.source`.
|
||||
To use your own data, copy that files format. Each article to be summarized is on its own line.
|
||||
|
||||
|
||||
WMT16 English-Romanian Translation Data:
|
||||
CNN/DailyMail data
|
||||
```bash
|
||||
cd examples/seq2seq
|
||||
wget https://s3.amazonaws.com/datasets.huggingface.co/summarization/cnn_dm.tgz
|
||||
tar -xzvf cnn_dm.tgz
|
||||
export CNN_DIR=${PWD}/cnn_dm
|
||||
this should make a directory called `cnn_dm/` with files like `test.source`.
|
||||
```
|
||||
|
||||
WMT16 English-Romanian Translation Data:
|
||||
|
||||
This dataset comes in two formats. The "packed" version merges short training examples into examples of <200 tokens to increase GPU utilization (and also improves validation performance).
|
||||
|
||||
```bash
|
||||
cd examples/seq2seq
|
||||
wget https://s3.amazonaws.com/datasets.huggingface.co/translation/wmt_en_ro_packed_train_200.tgz
|
||||
tar -xzvf wmt_en_ro_packed_200.tgz
|
||||
export ENRO_DIR=wmt_en_ro_packed_train_200
|
||||
```
|
||||
|
||||
The original data can also be downloaded with this command:
|
||||
```bash
|
||||
wget https://s3.amazonaws.com/datasets.huggingface.co/translation/wmt_en_ro.tar.gz
|
||||
tar -xzvf wmt_en_ro.tar.gz
|
||||
export ENRO_DIR=${PWD}/wmt_en_ro
|
||||
this should make a directory called `wmt_en_ro/` with files like `test.source`.
|
||||
```
|
||||
|
||||
If you are using your own data, it must be formatted as one directory with 6 files: train.source, train.target, val.source, val.target, test.source, test.target.
|
||||
The `.source` files are the input, the `.target` files are the desired output.
|
||||
|
||||
|
||||
|
||||
### Tips and Tricks
|
||||
|
||||
General Tips:
|
||||
@@ -60,10 +68,14 @@ Summarization Tips:
|
||||
- If you want to run experiments on improving the summarization finetuning process, try the XSUM Shared Task (below). It's faster to train than CNNDM because the summaries are shorter.
|
||||
- For CNN/DailyMail, the default `val_max_target_length` and `test_max_target_length` will truncate the ground truth labels, resulting in slightly higher rouge scores. To get accurate rouge scores, you should rerun calculate_rouge on the `{output_dir}/test_generations.txt` file saved by `trainer.test()`
|
||||
- `--max_target_length=60 --val_max_target_length=60 --test_max_target_length=100 ` is a reasonable setting for XSUM.
|
||||
- `wandb` can be used by specifying `--logger wandb`. It is useful for reproducibility. Specify the environment variable `WANDB_PROJECT='hf_xsum'` to do the XSUM shared task.
|
||||
- `wandb` can be used by specifying `--logger_name wandb`. It is useful for reproducibility. Specify the environment variable `WANDB_PROJECT='hf_xsum'` to do the XSUM shared task.
|
||||
- If you are finetuning on your own dataset, start from `distilbart-cnn-12-6` if you want long summaries and `distilbart-xsum-12-6` if you want short summaries.
|
||||
(It rarely makes sense to start from `bart-large` unless you are a researching finetuning methods).
|
||||
|
||||
**Update 2018-07-18**
|
||||
Datasets: Seq2SeqDataset will be used for all models besides MBart, for which MBartDataset will be used.**
|
||||
A new dataset is needed to support multilingual tasks.
|
||||
|
||||
### Summarization Finetuning
|
||||
Run/modify `finetune.sh`
|
||||
|
||||
@@ -78,21 +90,35 @@ The following command should work on a 16GB GPU:
|
||||
--model_name_or_path facebook/bart-large
|
||||
```
|
||||
|
||||
*Note*: The following tips mostly apply to summarization finetuning.
|
||||
|
||||
### Translation Finetuning
|
||||
|
||||
First, follow the wmt_en_ro download instructions.
|
||||
Then you can finetune mbart_cc25 on english-romanian with the following command.
|
||||
**Recommendation:** Read and potentially modify the fairly opinionated defaults in `train_mbart_cc25_enro.sh` script before running it.
|
||||
**Recommendation:** Read and potentially modify the fairly opinionated defaults in `train_mbart_cc25_enro.sh` script before running it.
|
||||
|
||||
Best performing command:
|
||||
```bash
|
||||
export ENRO_DIR=${PWD}/wmt_en_ro # may need to be fixed depending on where you downloaded
|
||||
# optionally
|
||||
export ENRO_DIR='wmt_en_ro_packed_train_200' # Download instructions above
|
||||
# export WANDB_PROJECT="MT" # optional
|
||||
export MAX_LEN=200
|
||||
export BS=4
|
||||
export GAS=8
|
||||
./train_mbart_cc25_enro.sh --output_dir cc25_v1_frozen/
|
||||
export GAS=8 # gradient accumulation steps
|
||||
./train_mbart_cc25_enro.sh --output_dir enro_finetune_baseline --label_smoothing 0.1 --fp16_opt_level=O1 --logger_name wandb --sortish_sampler
|
||||
```
|
||||
This should take < 2h/epoch on a 16GB v100 and achieve val_avg_ BLEU score above 25. (you can see in wandb or metrics.json).
|
||||
To get results in line with fairseq, you need to do some postprocessing.
|
||||
|
||||
|
||||
MultiGPU command
|
||||
(using 8 GPUS as an example)
|
||||
```bash
|
||||
export ENRO_DIR='wmt_en_ro_packed_train_200' # Download instructions above
|
||||
# export WANDB_PROJECT="MT" # optional
|
||||
export MAX_LEN=200
|
||||
export BS=4
|
||||
export GAS=1 # gradient accumulation steps
|
||||
./train_mbart_cc25_enro.sh --output_dir enro_finetune_baseline --gpus 8 --logger_name wandb
|
||||
```
|
||||
### Finetuning Outputs
|
||||
As you train, `output_dir` will be filled with files, that look kind of like this (comments are mine).
|
||||
Some of them are metrics, some of them are checkpoints, some of them are metadata. Here is a quick tour:
|
||||
@@ -107,7 +133,7 @@ output_dir
|
||||
│ ├── tokenizer_config.json
|
||||
│ └── vocab.json
|
||||
├── git_log.json # repo, branch, and commit hash
|
||||
├── val_avg_rouge2=0.1984-step_count=11.ckpt # this is a pytorch lightning checkpoint associated with the best val score.
|
||||
├── val_avg_rouge2=0.1984-step_count=11.ckpt # this is a pytorch lightning checkpoint associated with the best val score. (it will be called BLEU for MT)
|
||||
├── metrics.json # new validation metrics will continually be appended to this
|
||||
├── student # this is a huggingface checkpoint generated by SummarizationDistiller. It is the student before it gets finetuned.
|
||||
│ ├── config.json
|
||||
@@ -123,23 +149,6 @@ from transformers import AutoModelForSeq2SeqLM
|
||||
model = AutoModelForSeq2SeqLM.from_pretrained(f'{output_dir}/best_tfmr')
|
||||
```
|
||||
|
||||
#### XSUM Shared Task
|
||||
Compare XSUM results with others by using `--logger wandb_shared`. This requires `wandb` registration.
|
||||
|
||||
Here is an example command, but you can do whatever you want. Hopefully this will make debugging and collaboration easier!
|
||||
```bash
|
||||
WANDB_PROJECT='hf_xsum' ./finetune.sh \
|
||||
--data_dir $XSUM_DIR \
|
||||
--output_dir xsum_frozen_embs \
|
||||
--model_name_or_path facebook/bart-large \
|
||||
--train_batch_size 16 --eval_batch_size 16 --freeze_embeds --freeze_encoder \
|
||||
--num_train_epochs 6 \
|
||||
--max_target_length=60 --val_max_target_length=60 --test_max_target_length=100 \
|
||||
--logger wandb
|
||||
```
|
||||
|
||||
You can see your wandb logs [here](https://app.wandb.ai/sshleifer/hf_xsum?workspace=user-)
|
||||
|
||||
### Evaluation Commands
|
||||
|
||||
To create summaries for each article in dataset, we use `run_eval.py`, here are a few commands that run eval for different tasks and models.
|
||||
@@ -148,7 +157,7 @@ If 'translation' is in your task name, the computed metric will be BLEU. Otherwi
|
||||
For t5, you need to specify --task translation_{src}_to_{tgt} as follows:
|
||||
```bash
|
||||
export DATA_DIR=wmt_en_ro
|
||||
python run_eval.py t5_base \
|
||||
python run_eval.py t5-base \
|
||||
$DATA_DIR/val.source t5_val_generations.txt \
|
||||
--reference_path $DATA_DIR/val.target \
|
||||
--score_path enro_bleu.json \
|
||||
|
||||
@@ -5,7 +5,7 @@ from pathlib import Path
|
||||
import numpy as np
|
||||
import pytorch_lightning as pl
|
||||
import torch
|
||||
from pytorch_lightning.callbacks import ModelCheckpoint
|
||||
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
|
||||
from pytorch_lightning.utilities import rank_zero_only
|
||||
|
||||
|
||||
@@ -90,3 +90,7 @@ def get_checkpoint_callback(output_dir, metric):
|
||||
period=0, # maybe save a checkpoint every time val is run, not just end of epoch.
|
||||
)
|
||||
return checkpoint_callback
|
||||
|
||||
|
||||
def get_early_stopping_callback(metric, patience):
|
||||
return EarlyStopping(monitor=f"val_{metric}", mode="max", patience=patience, verbose=True,)
|
||||
|
||||
@@ -15,28 +15,15 @@ from transformers import AdamW, BartConfig, BartForConditionalGeneration, T5Conf
|
||||
|
||||
try:
|
||||
from .finetune import SummarizationModule
|
||||
from .initialization_utils import init_student, copy_layers
|
||||
from .utils import (
|
||||
use_task_specific_params,
|
||||
SummarizationDataset,
|
||||
pickle_load,
|
||||
freeze_params,
|
||||
assert_all_frozen,
|
||||
any_requires_grad,
|
||||
)
|
||||
from .finetune import main as ft_main
|
||||
from .initialization_utils import init_student, copy_layers
|
||||
from .utils import use_task_specific_params, pickle_load, freeze_params, assert_all_frozen, any_requires_grad
|
||||
|
||||
except ImportError:
|
||||
from finetune import SummarizationModule
|
||||
from finetune import main as ft_main
|
||||
from initialization_utils import init_student, copy_layers
|
||||
from utils import (
|
||||
use_task_specific_params,
|
||||
SummarizationDataset,
|
||||
pickle_load,
|
||||
freeze_params,
|
||||
assert_all_frozen,
|
||||
any_requires_grad,
|
||||
)
|
||||
from utils import use_task_specific_params, pickle_load, freeze_params, assert_all_frozen, any_requires_grad
|
||||
|
||||
|
||||
class BartSummarizationDistiller(SummarizationModule):
|
||||
@@ -115,11 +102,6 @@ class BartSummarizationDistiller(SummarizationModule):
|
||||
if self.different_encoder:
|
||||
copy_layers(teacher.encoder.block, student.encoder.block, e_layers_to_copy)
|
||||
|
||||
def get_dataset(self, type_path) -> SummarizationDataset:
|
||||
n_obs = self.n_obs[type_path]
|
||||
dataset = SummarizationDataset(self.tokenizer, type_path=type_path, n_obs=n_obs, **self.dataset_kwargs)
|
||||
return dataset
|
||||
|
||||
def calc_mse_loss(self, teacher_outputs: torch.Tensor, student_outputs: torch.Tensor, mask) -> torch.FloatTensor:
|
||||
if mask is not None:
|
||||
# mask has False at padding_idx
|
||||
@@ -446,6 +428,7 @@ def distill_main(args):
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser = pl.Trainer.add_argparse_args(parser)
|
||||
parser = BartSummarizationDistiller.add_model_specific_args(parser, os.getcwd())
|
||||
args = parser.parse_args()
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ try:
|
||||
from .utils import (
|
||||
assert_all_frozen,
|
||||
use_task_specific_params,
|
||||
SummarizationDataset,
|
||||
lmap,
|
||||
flatten_list,
|
||||
pickle_save,
|
||||
@@ -32,12 +31,18 @@ try:
|
||||
get_git_info,
|
||||
ROUGE_KEYS,
|
||||
calculate_bleu_score,
|
||||
Seq2SeqDataset,
|
||||
MBartDataset,
|
||||
label_smoothed_nll_loss,
|
||||
)
|
||||
from .callbacks import Seq2SeqLoggingCallback, get_checkpoint_callback
|
||||
|
||||
from .callbacks import Seq2SeqLoggingCallback, get_checkpoint_callback, get_early_stopping_callback
|
||||
except ImportError:
|
||||
from utils import (
|
||||
Seq2SeqDataset,
|
||||
MBartDataset,
|
||||
assert_all_frozen,
|
||||
use_task_specific_params,
|
||||
SummarizationDataset,
|
||||
lmap,
|
||||
flatten_list,
|
||||
pickle_save,
|
||||
@@ -48,9 +53,9 @@ except ImportError:
|
||||
get_git_info,
|
||||
ROUGE_KEYS,
|
||||
calculate_bleu_score,
|
||||
assert_all_frozen,
|
||||
label_smoothed_nll_loss,
|
||||
)
|
||||
from callbacks import Seq2SeqLoggingCallback, get_checkpoint_callback
|
||||
from callbacks import Seq2SeqLoggingCallback, get_checkpoint_callback, get_early_stopping_callback
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -100,6 +105,7 @@ class SummarizationModule(BaseTransformer):
|
||||
self.hparams.git_sha = get_git_info()["repo_sha"]
|
||||
self.num_workers = hparams.num_workers
|
||||
self.decoder_start_token_id = None
|
||||
self.dataset_class = Seq2SeqDataset
|
||||
|
||||
def freeze_embeds(self):
|
||||
"""Freeze token embeddings and positional embeddings for bart, just token embeddings for t5."""
|
||||
@@ -124,12 +130,22 @@ class SummarizationModule(BaseTransformer):
|
||||
|
||||
def _step(self, batch: dict) -> Tuple:
|
||||
pad_token_id = self.tokenizer.pad_token_id
|
||||
source_ids, source_mask, y = batch["input_ids"], batch["attention_mask"], batch["decoder_input_ids"]
|
||||
y_ids = y[:, :-1].contiguous()
|
||||
lm_labels = y[:, 1:].clone()
|
||||
lm_labels[y[:, 1:] == pad_token_id] = -100
|
||||
outputs = self(source_ids, attention_mask=source_mask, decoder_input_ids=y_ids, labels=lm_labels,)
|
||||
loss = outputs[0]
|
||||
source_ids, source_mask, target_ids = batch["input_ids"], batch["attention_mask"], batch["decoder_input_ids"]
|
||||
decoder_input_ids = target_ids[:, :-1].contiguous() # Why this line?
|
||||
lm_labels = target_ids[:, 1:].clone() # why clone?
|
||||
outputs = self(source_ids, attention_mask=source_mask, decoder_input_ids=decoder_input_ids, use_cache=False)
|
||||
|
||||
if self.hparams.label_smoothing == 0:
|
||||
# Same behavior as modeling_bart.py
|
||||
loss_fct = torch.nn.CrossEntropyLoss(ignore_index=pad_token_id)
|
||||
lm_logits = outputs[0]
|
||||
assert lm_logits.shape[-1] == self.model.config.vocab_size
|
||||
loss = loss_fct(lm_logits.view(-1, lm_logits.shape[-1]), lm_labels.view(-1))
|
||||
else:
|
||||
lprobs = torch.nn.functional.log_softmax(outputs[0], dim=-1)
|
||||
loss, nll_loss = label_smoothed_nll_loss(
|
||||
lprobs, lm_labels, self.hparams.label_smoothing, ignore_index=pad_token_id
|
||||
)
|
||||
return (loss,)
|
||||
|
||||
def training_step(self, batch, batch_idx) -> Dict:
|
||||
@@ -163,7 +179,7 @@ class SummarizationModule(BaseTransformer):
|
||||
|
||||
def _generative_step(self, batch: dict) -> dict:
|
||||
pad_token_id = self.tokenizer.pad_token_id
|
||||
source_ids, source_mask, y = SummarizationDataset.trim_seq2seq_batch(batch, pad_token_id)
|
||||
source_ids, source_mask, y = Seq2SeqDataset.trim_seq2seq_batch(batch, pad_token_id)
|
||||
t0 = time.time()
|
||||
generated_ids = self.model.generate(
|
||||
input_ids=source_ids,
|
||||
@@ -187,10 +203,10 @@ class SummarizationModule(BaseTransformer):
|
||||
def test_epoch_end(self, outputs):
|
||||
return self.validation_epoch_end(outputs, prefix="test")
|
||||
|
||||
def get_dataset(self, type_path) -> SummarizationDataset:
|
||||
def get_dataset(self, type_path) -> Seq2SeqDataset:
|
||||
n_obs = self.n_obs[type_path]
|
||||
max_target_length = self.target_lens[type_path]
|
||||
dataset = SummarizationDataset(
|
||||
dataset = self.dataset_class(
|
||||
self.tokenizer,
|
||||
type_path=type_path,
|
||||
n_obs=n_obs,
|
||||
@@ -221,8 +237,8 @@ class SummarizationModule(BaseTransformer):
|
||||
dataloader = self.get_dataloader("train", batch_size=self.hparams.train_batch_size, shuffle=True)
|
||||
t_total = (
|
||||
(len(dataloader.dataset) // (self.hparams.train_batch_size * max(1, self.hparams.gpus)))
|
||||
// self.hparams.gradient_accumulation_steps
|
||||
* float(self.hparams.num_train_epochs)
|
||||
// self.hparams.accumulate_grad_batches
|
||||
* float(self.hparams.max_epochs)
|
||||
)
|
||||
scheduler = get_linear_schedule_with_warmup(
|
||||
self.opt, num_warmup_steps=self.hparams.warmup_steps, num_training_steps=t_total
|
||||
@@ -279,16 +295,23 @@ class SummarizationModule(BaseTransformer):
|
||||
parser.add_argument("--freeze_encoder", action="store_true")
|
||||
parser.add_argument("--freeze_embeds", action="store_true")
|
||||
parser.add_argument("--sortish_sampler", action="store_true", default=False)
|
||||
parser.add_argument("--logger", type=str, choices=["default", "wandb", "wandb_shared"], default="default")
|
||||
parser.add_argument("--logger_name", type=str, choices=["default", "wandb", "wandb_shared"], default="default")
|
||||
parser.add_argument("--n_train", type=int, default=-1, required=False, help="# examples. -1 means use all.")
|
||||
parser.add_argument("--n_val", type=int, default=500, required=False, help="# examples. -1 means use all.")
|
||||
parser.add_argument("--n_test", type=int, default=-1, required=False, help="# examples. -1 means use all.")
|
||||
parser.add_argument(
|
||||
"--task", type=str, default="summarization", required=False, help="# examples. -1 means use all."
|
||||
)
|
||||
parser.add_argument("--label_smoothing", type=float, default=0.0, required=False)
|
||||
parser.add_argument("--src_lang", type=str, default="", required=False)
|
||||
parser.add_argument("--tgt_lang", type=str, default="", required=False)
|
||||
|
||||
parser.add_argument(
|
||||
"--early_stopping_patience",
|
||||
type=int,
|
||||
default=-1,
|
||||
required=False,
|
||||
help="-1 means never early stop. early_stopping_patience is measured in validation checks, not epochs. So val_check_interval will effect it.",
|
||||
)
|
||||
return parser
|
||||
|
||||
|
||||
@@ -304,6 +327,9 @@ class TranslationModule(SummarizationModule):
|
||||
self.dataset_kwargs["tgt_lang"] = hparams.tgt_lang
|
||||
if self.model.config.decoder_start_token_id is None and isinstance(self.tokenizer, MBartTokenizer):
|
||||
self.decoder_start_token_id = self.tokenizer.lang_code_to_id[hparams.tgt_lang]
|
||||
self.model.config.decoder_start_token_id = self.decoder_start_token_id
|
||||
if isinstance(self.tokenizer, MBartTokenizer):
|
||||
self.dataset_class = MBartDataset
|
||||
|
||||
def calc_generative_metrics(self, preds, target) -> dict:
|
||||
return calculate_bleu_score(preds, target)
|
||||
@@ -318,27 +344,36 @@ def main(args, model=None) -> SummarizationModule:
|
||||
model: SummarizationModule = SummarizationModule(args)
|
||||
else:
|
||||
model: SummarizationModule = TranslationModule(args)
|
||||
|
||||
dataset = Path(args.data_dir).name
|
||||
if (
|
||||
args.logger == "default"
|
||||
args.logger_name == "default"
|
||||
or args.fast_dev_run
|
||||
or str(args.output_dir).startswith("/tmp")
|
||||
or str(args.output_dir).startswith("/var")
|
||||
):
|
||||
logger = True # don't pollute wandb logs unnecessarily
|
||||
elif args.logger == "wandb":
|
||||
elif args.logger_name == "wandb":
|
||||
from pytorch_lightning.loggers import WandbLogger
|
||||
|
||||
logger = WandbLogger(name=model.output_dir.name)
|
||||
project = os.environ.get("WANDB_PROJECT", dataset)
|
||||
logger = WandbLogger(name=model.output_dir.name, project=project)
|
||||
|
||||
elif args.logger == "wandb_shared":
|
||||
elif args.logger_name == "wandb_shared":
|
||||
from pytorch_lightning.loggers import WandbLogger
|
||||
|
||||
logger = WandbLogger(name=model.output_dir.name)
|
||||
logger = WandbLogger(name=model.output_dir.name, project=f"hf_{dataset}")
|
||||
|
||||
if args.early_stopping_patience >= 0:
|
||||
es_callback = get_early_stopping_callback(model.val_metric, args.early_stopping_patience)
|
||||
else:
|
||||
es_callback = False
|
||||
trainer: pl.Trainer = generic_train(
|
||||
model,
|
||||
args,
|
||||
logging_callback=Seq2SeqLoggingCallback(),
|
||||
checkpoint_callback=get_checkpoint_callback(args.output_dir, model.val_metric),
|
||||
early_stopping_callback=es_callback,
|
||||
logger=logger,
|
||||
# TODO: early stopping callback seems messed up
|
||||
)
|
||||
@@ -352,13 +387,17 @@ def main(args, model=None) -> SummarizationModule:
|
||||
model.hparams.test_checkpoint = checkpoints[-1]
|
||||
trainer.resume_from_checkpoint = checkpoints[-1]
|
||||
trainer.logger.log_hyperparams(model.hparams)
|
||||
trainer.test(model) # this breaks in DDP, known lightning issue. See evaluate_checkpoint to recover metrics.
|
||||
|
||||
# test() without a model tests using the best checkpoint automatically
|
||||
trainer.test()
|
||||
return model
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser = pl.Trainer.add_argparse_args(parser)
|
||||
parser = SummarizationModule.add_model_specific_args(parser, os.getcwd())
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
main(args)
|
||||
|
||||
@@ -10,5 +10,4 @@ python finetune.py \
|
||||
--do_predict \
|
||||
--n_val 1000 \
|
||||
--val_check_interval 0.1 \
|
||||
--sortish_sampler \
|
||||
$@
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Fill examples with bitext up to max_tokens without breaking up examples.
|
||||
[['I went', 'yo fui'],
|
||||
['to the store', 'a la tienda']
|
||||
]
|
||||
=> ['I went to the store', 'yo fui a la tienda']
|
||||
"""
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
from tqdm import tqdm
|
||||
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
|
||||
def pack_examples(tok, src_examples, tgt_examples, max_tokens=1024):
|
||||
|
||||
finished_src, finished_tgt = [], []
|
||||
|
||||
sorted_examples = list(sorted(zip(src_examples, tgt_examples), key=lambda x: len(x[0])))
|
||||
new_src, new_tgt = sorted_examples[0]
|
||||
|
||||
def is_too_big(strang):
|
||||
return tok(strang, return_tensors="pt").input_ids.shape[1] > max_tokens
|
||||
|
||||
for src, tgt in tqdm(sorted_examples[1:]):
|
||||
cand_src = new_src + " " + src
|
||||
cand_tgt = new_tgt + " " + tgt
|
||||
if is_too_big(cand_src) or is_too_big(cand_tgt): # cant fit, finalize example
|
||||
finished_src.append(new_src)
|
||||
finished_tgt.append(new_tgt)
|
||||
new_src, new_tgt = src, tgt
|
||||
else: # can fit, keep adding
|
||||
new_src, new_tgt = cand_src, cand_tgt
|
||||
# import ipdb; ipdb.set_trace()
|
||||
|
||||
# cleanup
|
||||
if new_src:
|
||||
assert new_tgt
|
||||
finished_src.append(new_src)
|
||||
finished_tgt.append(new_tgt)
|
||||
return finished_src, finished_tgt
|
||||
|
||||
|
||||
def minify(src_dir: Path, dest_dir: Path, n: int):
|
||||
"""Write first n lines of each file f in src_dir to dest_dir/f"""
|
||||
dest_dir.mkdir(exist_ok=True)
|
||||
for path in src_dir.iterdir():
|
||||
new = [x.rstrip() for x in list(path.open().readlines())][:n]
|
||||
dest_path = dest_dir.joinpath(path.name)
|
||||
print(dest_path)
|
||||
dest_path.open("w").write("\n".join(new))
|
||||
|
||||
|
||||
def pack_data_dir(tok, data_dir: Path, max_tokens, save_path):
|
||||
save_path = Path(save_path)
|
||||
save_path.mkdir(exist_ok=True)
|
||||
for split in ["val", "test", "train"]:
|
||||
src_path, tgt_path = data_dir / f"{split}.source", data_dir / f"{split}.target"
|
||||
src_docs = [x.rstrip() for x in Path(src_path).open().readlines()]
|
||||
tgt_docs = [x.rstrip() for x in Path(tgt_path).open().readlines()]
|
||||
packed_src, packed_tgt = pack_examples(tok, src_docs, tgt_docs, max_tokens)
|
||||
print(f"packed {split} split from {len(src_docs)} examples -> {len(packed_src)}.")
|
||||
Path(save_path / f"{split}.source").open("w").write("\n".join(packed_src))
|
||||
Path(save_path / f"{split}.target").open("w").write("\n".join(packed_tgt))
|
||||
|
||||
|
||||
def packer_cli():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--tok_name", type=str, help="like facebook/bart-large-cnn,t5-base, etc.")
|
||||
parser.add_argument("--max_seq_len", type=int, default=128)
|
||||
parser.add_argument("--data_dir", type=str)
|
||||
parser.add_argument("--save_path", type=str)
|
||||
args = parser.parse_args()
|
||||
tokenizer = AutoTokenizer.from_pretrained(args.tok_name)
|
||||
return pack_data_dir(tokenizer, Path(args.data_dir), args.max_seq_len, args.save_path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
packer_cli()
|
||||
@@ -0,0 +1,65 @@
|
||||
### Motivation
|
||||
Without processing, english-> romanian mbart-large-en-ro gets BLEU score 26.8 on the WMT data.
|
||||
With post processing, it can score 37..
|
||||
Here is the postprocessing code, stolen from @mjpost in this [issue](https://github.com/pytorch/fairseq/issues/1758)
|
||||
|
||||
|
||||
|
||||
### Instructions
|
||||
Note: You need to have your test_generations.txt before you start this process.
|
||||
(1) Setup `mosesdecoder` and `wmt16-scripts`
|
||||
```bash
|
||||
cd $HOME
|
||||
git clone git@github.com:moses-smt/mosesdecoder.git
|
||||
cd mosesdecoder
|
||||
git@github.com:rsennrich/wmt16-scripts.git
|
||||
```
|
||||
|
||||
(2) define a function for post processing.
|
||||
It removes diacritics and does other things I don't understand
|
||||
```bash
|
||||
ro_post_process () {
|
||||
sys=$1
|
||||
ref=$2
|
||||
export MOSES_PATH=$HOME/mosesdecoder
|
||||
REPLACE_UNICODE_PUNCT=$MOSES_PATH/scripts/tokenizer/replace-unicode-punctuation.perl
|
||||
NORM_PUNC=$MOSES_PATH/scripts/tokenizer/normalize-punctuation.perl
|
||||
REM_NON_PRINT_CHAR=$MOSES_PATH/scripts/tokenizer/remove-non-printing-char.perl
|
||||
REMOVE_DIACRITICS=$MOSES_PATH/wmt16-scripts/preprocess/remove-diacritics.py
|
||||
NORMALIZE_ROMANIAN=$MOSES_PATH/wmt16-scripts/preprocess/normalise-romanian.py
|
||||
TOKENIZER=$MOSES_PATH/scripts/tokenizer/tokenizer.perl
|
||||
|
||||
|
||||
|
||||
lang=ro
|
||||
for file in $sys $ref; do
|
||||
cat $file \
|
||||
| $REPLACE_UNICODE_PUNCT \
|
||||
| $NORM_PUNC -l $lang \
|
||||
| $REM_NON_PRINT_CHAR \
|
||||
| $NORMALIZE_ROMANIAN \
|
||||
| $REMOVE_DIACRITICS \
|
||||
| $TOKENIZER -no-escape -l $lang \
|
||||
> $(basename $file).tok
|
||||
done
|
||||
# compute BLEU
|
||||
cat $(basename $sys).tok | sacrebleu -tok none -s none -b $(basename $ref).tok
|
||||
}
|
||||
```
|
||||
|
||||
(3) Call the function on test_generations.txt and test.target
|
||||
For example,
|
||||
```bash
|
||||
ro_post_process enro_finetune/test_generations.txt wmt_en_ro/test.target
|
||||
```
|
||||
This will split out a new blue score and write a new fine called `test_generations.tok` with post-processed outputs.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
```
|
||||
@@ -30,6 +30,7 @@ def generate_summaries_or_translations(
|
||||
device: str = DEFAULT_DEVICE,
|
||||
fp16=False,
|
||||
task="summarization",
|
||||
decoder_start_token_id=None,
|
||||
**gen_kwargs,
|
||||
) -> None:
|
||||
fout = Path(out_file).open("w", encoding="utf-8")
|
||||
@@ -37,6 +38,8 @@ def generate_summaries_or_translations(
|
||||
model = AutoModelForSeq2SeqLM.from_pretrained(model_name).to(device)
|
||||
if fp16:
|
||||
model = model.half()
|
||||
if decoder_start_token_id is None:
|
||||
decoder_start_token_id = gen_kwargs.pop("decoder_start_token_id", None)
|
||||
|
||||
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
||||
|
||||
@@ -46,11 +49,14 @@ def generate_summaries_or_translations(
|
||||
for batch in tqdm(list(chunks(examples, batch_size))):
|
||||
if "t5" in model_name:
|
||||
batch = [model.config.prefix + text for text in batch]
|
||||
batch = tokenizer(batch, max_length=1024, return_tensors="pt", truncation=True, padding="max_length").to(
|
||||
device
|
||||
)
|
||||
batch = tokenizer(batch, return_tensors="pt", truncation=True, padding="max_length").to(device)
|
||||
input_ids, attention_mask = trim_batch(**batch, pad_token_id=tokenizer.pad_token_id)
|
||||
summaries = model.generate(input_ids=input_ids, attention_mask=attention_mask, **gen_kwargs)
|
||||
summaries = model.generate(
|
||||
input_ids=input_ids,
|
||||
attention_mask=attention_mask,
|
||||
decoder_start_token_id=decoder_start_token_id,
|
||||
**gen_kwargs,
|
||||
)
|
||||
dec = tokenizer.batch_decode(summaries, skip_special_tokens=True, clean_up_tokenization_spaces=False)
|
||||
for hypothesis in dec:
|
||||
fout.write(hypothesis + "\n")
|
||||
@@ -68,6 +74,13 @@ def run_generate():
|
||||
parser.add_argument("--device", type=str, required=False, default=DEFAULT_DEVICE, help="cuda, cuda:1, cpu etc.")
|
||||
parser.add_argument("--task", type=str, default="summarization", help="typically translation or summarization")
|
||||
parser.add_argument("--bs", type=int, default=8, required=False, help="batch size")
|
||||
parser.add_argument(
|
||||
"--decoder_start_token_id",
|
||||
type=int,
|
||||
default=None,
|
||||
required=False,
|
||||
help="decoder_start_token_id (otherwise will look at config)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--n_obs", type=int, default=-1, required=False, help="How many observations. Defaults to all."
|
||||
)
|
||||
@@ -85,6 +98,7 @@ def run_generate():
|
||||
device=args.device,
|
||||
fp16=args.fp16,
|
||||
task=args.task,
|
||||
decoder_start_token_id=args.decoder_start_token_id,
|
||||
)
|
||||
if args.reference_path is None:
|
||||
return
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
import pytorch_lightning as pl
|
||||
import wget
|
||||
|
||||
from transformers.testing_utils import slow
|
||||
|
||||
from .finetune import SummarizationModule, main
|
||||
from .test_seq2seq_examples import CUDA_AVAILABLE, MBART_TINY
|
||||
from .utils import load_json
|
||||
|
||||
|
||||
def fetch_and_save_wmt_100():
|
||||
# TODO(SS): DELETEME
|
||||
DATA_URL = "https://s3.amazonaws.com/datasets.huggingface.co/translation/wmt_en_ro_test_data.tgz"
|
||||
|
||||
dest_dir = "wmt_100_dir"
|
||||
if os.path.isdir(dest_dir):
|
||||
return dest_dir
|
||||
filename = wget.download(DATA_URL)
|
||||
tarball = tarfile.TarFile(filename)
|
||||
tarball.extractall(path=dest_dir)
|
||||
os.remove(filename)
|
||||
return dest_dir
|
||||
|
||||
|
||||
@slow
|
||||
@pytest.mark.skipif(not CUDA_AVAILABLE, reason="too slow to run on CPU")
|
||||
def test_train_mbart_cc25_enro_script():
|
||||
data_dir = "examples/seq2seq/test_data/wmt_en_ro"
|
||||
env_vars_to_replace = {
|
||||
"$MAX_LEN": 200,
|
||||
"$BS": 4,
|
||||
"$GAS": 1,
|
||||
"$ENRO_DIR": data_dir,
|
||||
"facebook/mbart-large-cc25": MBART_TINY,
|
||||
}
|
||||
|
||||
# Clean up bash script
|
||||
bash_script = Path("examples/seq2seq/train_mbart_cc25_enro.sh").open().read().split("finetune.py")[1].strip()
|
||||
bash_script = bash_script.replace("\\\n", "").strip().replace("$@", "")
|
||||
for k, v in env_vars_to_replace.items():
|
||||
bash_script = bash_script.replace(k, str(v))
|
||||
output_dir = tempfile.mkdtemp(prefix="output")
|
||||
|
||||
if CUDA_AVAILABLE:
|
||||
gpus = 1 # torch.cuda.device_count()
|
||||
else:
|
||||
bash_script = bash_script.replace("--fp16", "")
|
||||
gpus = 0
|
||||
|
||||
testargs = (
|
||||
["finetune.py"]
|
||||
+ bash_script.split()
|
||||
+ [f"--output_dir={output_dir}", f"--gpus={gpus}", "--learning_rate=3e-1"]
|
||||
)
|
||||
with patch.object(sys, "argv", testargs):
|
||||
parser = argparse.ArgumentParser()
|
||||
parser = pl.Trainer.add_argparse_args(parser)
|
||||
parser = SummarizationModule.add_model_specific_args(parser, os.getcwd())
|
||||
args = parser.parse_args()
|
||||
# assert args.gpus == gpus THIS BREAKS
|
||||
# args.gpus = gpus
|
||||
model = main(args)
|
||||
contents = os.listdir(output_dir)
|
||||
# ckpt_name = "val_avg_rouge2=0.0000-step_count=2.ckpt" # "val_avg_rouge2=0.0000-epoch=1.ckpt" #
|
||||
# "epoch=1-val_avg_rouge2=0.0000.ckpt"
|
||||
contents = {os.path.basename(p) for p in contents}
|
||||
|
||||
# self.assertIn(ckpt_name, contents)
|
||||
|
||||
assert "test_generations.txt" in contents
|
||||
assert "test_results.txt" in contents
|
||||
|
||||
metrics = load_json(model.metrics_save_path)
|
||||
first_step_stats = metrics["val"][0]
|
||||
last_step_stats = metrics["val"][-1]
|
||||
assert last_step_stats["val_avg_gen_time"] >= 0.01
|
||||
assert 1.0 >= last_step_stats["val_avg_gen_time"]
|
||||
assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"]
|
||||
|
||||
assert isinstance(last_step_stats[f"val_avg_{model.val_metric}"], float)
|
||||
# desired_n_evals = int(args_d["max_epochs"] * (1 / args_d["val_check_interval"]) + 1)
|
||||
# assert len(metrics["val"]) == desired_n_evals
|
||||
assert len(metrics["test"]) == 1
|
||||
@@ -0,0 +1,100 @@
|
||||
UN Chief Says There Is No Military Solution in Syria
|
||||
Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.
|
||||
The U.N. chief again urged all parties, including the divided U.N. Security Council, to unite and support inclusive negotiations to find a political solution.
|
||||
Ban told a news conference Wednesday that he plans to meet with foreign ministers of the five permanent council nations - the U.S., Russia, China, Britain and France - on the sidelines of the General Assembly's ministerial session later this month to discuss Syria.
|
||||
He expressed regret that divisions in the council and among the Syrian people and regional powers "made this situation unsolvable."
|
||||
Ban urged the five permanent members to show the solidarity and unity they did in achieving an Iran nuclear deal in addressing the Syria crisis.
|
||||
8 Poll Numbers That Show Donald Trump Is For Real
|
||||
Some have tried to label him a flip-flopper.
|
||||
Others have dismissed him as a joke.
|
||||
And some are holding out for an implosion.
|
||||
But no matter how some Republicans are trying to drag Donald Trump down from atop the polls, it hasn't worked (yet).
|
||||
Ten of the last 11 national polls have shown Donald Trump's lead at double digits, and some are starting to ask seriously what it means for the real estate mogul's nomination chances.
|
||||
Of course, it's still early in the election cycle.
|
||||
None of this is to say that Trump is likely to win the Republican nomination.
|
||||
Pundits point out that at this time in 2011, Rick Perry's lead was giving way to a rising Herman Cain, neither of whom won even one state in the nomination process.
|
||||
And there are many reasons he would struggle in a general election.
|
||||
But outside groups like Jeb Bush's Super PAC and the economic conservative group Club for Growth are recognizing Trump's staying power and beginning to unload their dollars to topple him.
|
||||
Here are some recent poll numbers that suggest that the real estate mogul isn't just a passing phase:
|
||||
Trump's favorability ratings have turned 180 degrees.
|
||||
Right before Donald Trump announced his candidacy in mid-June, a Monmouth University poll showed only two in 10 Republicans had a positive view of the real estate mogul.
|
||||
By mid-July, it was 40 percent.
|
||||
In early August, it was 52 percent.
|
||||
Now, six in 10 Republicans have a favorable view of Donald Trump.
|
||||
Roughly three in 10 say they have a negative view.
|
||||
And these numbers hold up in early states.
|
||||
A Quinnipiac poll in Iowa last week found that 60 percent of Republicans there had a favorable view of Trump.
|
||||
Two-thirds of GOP voters would be happy with Trump as the nominee.
|
||||
In a CNN/ORC poll last week, 67 percent of Republicans said they would be either "enthusiastic" or "satisfied" if Trump were the nominee.
|
||||
Only two in 10 say they would be "upset" if he were the nominee.
|
||||
Only Ben Carson generates roughly the same level of enthusiasm as Trump (43 percent say they would be "enthusiastic" vs. 40 percent who say the same of Trump).
|
||||
The next closest in enthusiasm?
|
||||
Marco Rubio with only 21 percent.
|
||||
On the flip side, 47 percent of Republican voters say they would be "dissatisfied" or "upset" if establishment favorite Jeb Bush becomes the nominee.
|
||||
A majority of Republicans don't see Trump's temperament as a problem.
|
||||
While Donald Trump has been widely criticized for his bombast and insults, 52 percent of leaned Republican voters nationwide think that the real estate mogul has the right temperament to be president, according to Monday's ABC News/Washington Post poll.
|
||||
The same number holds in the first-in-the-nation caucus state of Iowa, where the same 52 percent of Republicans think he has the personality to be commander in chief, according to Quinnipiac last week.
|
||||
Still, 44 percent think he doesn't have the personality to serve effectively, and almost six in 10 independents say his temperament does not belong in the White House, according to ABC/Post.
|
||||
Republican voters are getting used to the idea.
|
||||
When they put on their pundit hats, Republican voters think Trump is for real.
|
||||
When asked who is most likely to win the GOP nomination, four in 10 said Trump was the best bet, according to a CNN/ORC poll out last week.
|
||||
That's a change from when four in 10 placed their money on Jeb Bush in late July.
|
||||
Full disclosure: GOP voters haven't had the clearest crystal ball in the past.
|
||||
At this time last cycle, four in 10 Republicans picked Rick Perry to win the nomination, vs. only 28 percent for eventual nominee Mitt Romney.
|
||||
Still, it shows that a plurality of GOP voters see Trump's campaign as plausible.
|
||||
Even if Republicans rallied around another candidate, Trump still beats almost everyone.
|
||||
Some pundits point out that the splintered field is likely contributing to Trump's lead, while anti-Trump support is be spread diffusely among more than a dozen other candidates.
|
||||
But a Monmouth University poll in early September shows that, in a hypothetical head-to-head matchup between Trump and most other Republican candidates, Trump almost always garners majority support.
|
||||
He leads Carly Fiorina by 13 points, Marco Rubio by 14 points, Walker by 15 points, Jeb Bush by 19 points, and, finally, Rand Paul, John Kasich and Chris Christie by 33 points each.
|
||||
He's in a dead heat with Ted Cruz.
|
||||
The only candidate who beats him?
|
||||
Ben Carson would lead the businessman by a wide 19 points in a hypothetical head-to-head.
|
||||
A bare majority of Donald Trump's supporters say they've made up their minds.
|
||||
A new CBS/NYT poll out on Tuesday shows that just more than half of voters who support Trump say they have locked in their votes.
|
||||
Obviously, a lot can happen to change that, and no one can really say they would never change their mind.
|
||||
46 percent said they are leaving the door open to switching candidates.
|
||||
Still, Trump's strongest competition at the moment is from fellow outsider neurosurgeon Ben Carson, but voters who say they have made up their minds are twice as likely to go for Trump.
|
||||
Six in 10 Republicans say they agree with Trump on immigration.
|
||||
Even since Donald Trump called immigrants from Mexico "rapists" in his campaign announcement speech two months ago, immigration has been front and center in the 2016 conversation.
|
||||
Some are worried that Trump's bombast will drive crucial Hispanic voters away from the Republican Party and damage rebranding efforts.
|
||||
But according to Monday's new ABC/Post poll, six in 10 Republicans say they agree with Trump on immigration issues.
|
||||
So as long as immigration remains in the spotlight, it seems Donald Trump will remain too.
|
||||
Frustration with government is climbing to new highs.
|
||||
Donald Trump and Ben Carson now account for roughly half of the support from Republican voters, largely due to their outsider status.
|
||||
Six in 10 Republicans in Monday's new ABC/Post poll say they want a political outsider over someone with government experience.
|
||||
And they are angry at Washington, too.
|
||||
A Des Moines Register/Bloomberg poll in Iowa from two weeks ago shows that three in four Iowa Republicans are frustrated with Republicans in Congress, with 54 percent "unsatisfied" and 21 percent "mad as hell."
|
||||
Jeremy Corbyn to make debut at Prime Minister's Questions
|
||||
Since his election, Mr Corbyn's debut at PMQs has been keenly awaited
|
||||
New Labour leader Jeremy Corbyn is to make his debut at Prime Minister's Questions later, taking on David Cameron for the first time.
|
||||
Mr Corbyn will rise to ask the first of his six allotted questions shortly after midday, with his performance likely to be closely scrutinised by the media and Labour MPs.
|
||||
He has called for "less theatre and more facts" at the weekly showpiece.
|
||||
He has also said he could skip some sessions, leaving them to colleagues.
|
||||
The encounter will be the first parliamentary test of Mr Corbyn's leadership, coming after his appointment of a shadow cabinet and his speech to the TUC annual congress on Tuesday.
|
||||
Meanwhile, the Labour leader's decision to stand in silence during the singing of the national anthem at a service on Tuesday to mark the 75th anniversary of the Battle of Britain has attracted criticism from a number of Tory MPs and is the focus of several front page stories in the newspapers.
|
||||
Mr Corbyn's decision not to sing the national anthem has attracted attention
|
||||
A spokesman for Mr Corbyn said he had "stood in respectful silence" and did recognise the "heroism of the Royal Air Force in the Battle of Britain."
|
||||
But a member of Mr Corbyn's shadow cabinet, Owen Smith, told BBC Two's Newsnight programme he would have advised the Labour leader to sing the national anthem "irrespective" of his belief that the monarchy should be abolished.
|
||||
Nearly a dozen shadow ministers have refused to serve in Mr Corbyn's top team, citing differences over the economy, defence and foreign affairs, while less than a sixth of the parliamentary party originally backed him as leader.
|
||||
BBC political correspondent Robin Brant says policy differences are also "stacking up" within Labour following Mr Corbyn's appointment over its position on the European Union and the government's cap on benefits.
|
||||
Mr Corbyn told the TUC conference Labour was putting forward amendments to remove the whole idea of a cap altogether.
|
||||
Hours later Mr Smith, the shadow work and pensions secretary, said the party was "very clear" that it was only opposing government plans to reduce the level of cap from £26,000 to £23,000.
|
||||
Mr Corbyn will be the fifth Labour leader that David Cameron has faced across the despatch box over the past decade since he became Tory leader.
|
||||
The Labour leader, who has promised a different approach to politics, says he has "crowd sourced" ideas for questions to ask Mr Cameron and has been given more than 30,000 suggestions.
|
||||
The Islington North MP has said PMQs is too confrontational and that he will refrain from both "repartee" and trading barbs, instead vowing to focus on serious issues such as poverty, inequality and the challenges facing young people.
|
||||
Mr Corbyn has said that Angela Eagle, the shadow business secretary, will deputise for him at PMQs when he does not attend - for instance when Mr Cameron is travelling abroad.
|
||||
He has also floated the idea of allowing other colleagues to take the floor on occasion, saying he had approached the Commons Speaker John Bercow to discuss the issue.
|
||||
When he became leader in 2005, Mr Cameron said he wanted to move away from the "Punch and Judy" style of politics often associated with PMQs but admitted some years later that he had failed.
|
||||
Since it was first televised in 1990, PMQs has been seen as a key barometer of a leader's judgement, their command of the Commons and their standing among their fellow MPs although critics have argued it has become a caricature and is in need of far-reaching reforms.
|
||||
'Shot in Joburg': Homeless youth trained as photographers
|
||||
Downtown Johannesburg is a tough place to be homeless.
|
||||
But one group of former street children have found a way to learn a skill and make a living.
|
||||
"I was shot in Joburg" is a non-profit studio that teaches homeless youngsters how to take photographs of their neighbourhood and make a profit from it.
|
||||
BBC News went to meet one of the project's first graduates.
|
||||
JD Sports boss says higher wages could hurt expansion
|
||||
JD Sports Executive Chairman Peter Cowgill says a higher minimum wage for UK workers could mean "more spending power in the pockets of potential consumers."
|
||||
But that spending power is unlikely to outweigh the higher labour costs at his firm, he says.
|
||||
The costs could hit JD Sports' expansion plans, he added, which could mean fewer extra jobs.
|
||||
Thanasi Kokkinakis backed by Tennis Australia president Steve Healy
|
||||
Thanasi Kokkinakis deserves kudos rather than criticism for his behaviour.
|
||||
Thanasi Kokkinakis has been the collateral damage in the recent storm around his friend Nick Kyrgios and deserves kudos rather than criticism for his own behaviour, according to Tennis Australia president Steve Healy.
|
||||
@@ -0,0 +1,100 @@
|
||||
Șeful ONU declară că nu există soluții militare în Siria
|
||||
Secretarul General Ban Ki-moon afirmă că răspunsul său la suportul militar al Rusiei pentru Siria este că „nu există o soluție militară” la conflictul care durează de aproape cinci ani iar mai multe arme nu ar face decât să agraveze violența și suferința a milioane de oameni.
|
||||
Șeful ONU a solicitat din nou tuturor părților, inclusiv Consiliului de securitate ONU divizat să se unifice și să susțină negocierile pentru a găsi o soluție politică.
|
||||
Ban a declarat miercuri în cadrul unei conferințe că intenționează să se întâlnească luna aceasta cu miniștrii de externe din cinci țări permanent prezente în consiliu - SUA, Rusia, China, Anglia și Franța - pe marginea sesiunii ministeriale a Adunării Generale pentru a discuta despre Siria.
|
||||
Ban și-a exprimat regretul că divizările în consiliu și între poporul sirian și puterile regionale „au făcut această situație de nerezolvat”.
|
||||
Ban le-a cerut celor cinci membri permanenți să dea dovadă de solidaritatea și unitatea arătate atunci când au reușit să încheie un acord referitor la armele nucleare ale Iranului, abordând astfel criza din Siria.
|
||||
8 cifre din sondaje care arată că Donald Trump are șanse reale
|
||||
Unii au încercat să îl eticheteze ca politician „flip-flop”.
|
||||
Alții l-au numit o glumă.
|
||||
Iar alții așteaptă implozia.
|
||||
Însă indiferent de modul în care unii republicani încearcă să îl dărâme pe Donald Trump din vârful sondajelor, nu a funcționat (încă).
|
||||
Zece din ultimele 11 sondaje naționale au arătat că Donald Trump conduce cu un procent din două cifre iar unele voci încep să se întrebe serios ce înseamnă acest lucru pentru șansele de numire ale mogulului imobiliar.
|
||||
Desigur, este încă prematur.
|
||||
Nimic din toate acestea nu spune că Trump va câștiga cursa pentru nominalizarea republicanilor.
|
||||
Pundits arată că, în aceeași perioadă a anului 2011, avansul lui Rick Perry îi făcea loc lui Herman Cain în sondaje, dar niciunul dintre ei nu a câștigat în vreun stat în cursa de nominalizare.
|
||||
Iar motivele pentru care s-ar lupta din greu la alegerile generale sunt numeroase.
|
||||
Însă grupurile din exterior precum Super PAC al lui Jeb Bush și grupul conservator economic Club for Growth admit puterea lui Trump și încep să îl susțină cu bani.
|
||||
În continuare vă prezentăm câteva cifre din sondaje recente care sugerează că mogulul imobiliar nu este doar ceva trecător:
|
||||
Cifrele care indică susținerea față de Trump s-au întors la 180 grade.
|
||||
Chiar înainte ca Donald Trump să își anunțe candidatura, la mijlocul lui iunie, un sondaj realizat de Universitatea din Monmouth arăta că doar doi din 10 republicani aveau o părere pozitivă despre mogulul imobiliar.
|
||||
Până la mijlocul lui iulie, procentul a urcat la 40%.
|
||||
La începutul lui august, era 52%.
|
||||
În prezent, șase din 10 republicani au o părere favorabilă despre Donald Trump.
|
||||
Aproximativ trei din 10 declară că au o părere negativă.
|
||||
Aceste cifre se mențin.
|
||||
Un sondaj realizat săptămâna trecută de Quinnipiac în Iowa a concluzionat că 60% dintre republicanii din regiune au o părere favorabilă despre Trump.
|
||||
Două treimi dintre alegătorii GOP ar fi fericiți dacă Trump ar câștiga cursa pentru nominalizare.
|
||||
Într-un sondaj realizat săptămâna trecută de CNN/ORC, 67% dintre republicani au declarat că ar fi „entuziasmați” sau „mulțumiți” dacă Trump ar câștiga cursa pentru nominalizare.
|
||||
Doar doi din 10 declară că ar fi „supărați” dacă Trump ar câștiga cursa pentru nominalizare.
|
||||
Doar Ben Carson generează aproximativ același nivel de entuziasm ca Trump (43% declară că ar fi „entuziasmați” față de 40% care declară același lucru despre Trump).
|
||||
Cel mai aproape în ceea ce privește entuziasmul?
|
||||
Marco Rubio, cu doar 21%.
|
||||
De partea cealaltă, 47% dintre alegătorii republicani afirmă că ar fi „nemulțumiți” sau „supărați” dacă favoritul Jeb Bush câștigă cursa pentru nominalizare.
|
||||
Majoritatea republicanilor nu consideră temperamentul lui Trump o problemă.
|
||||
Deși Donald Trump a fost puternic criticat pentru insultele aduse și stilul său bombastic, 52% dintre alegătorii republicani la nivel național consideră că mogulul imobiliar are temperamentul potrivit pentru a fi președinte, conform sondajului realizat luni de ABC News/Washington Post.
|
||||
Regăsim aceleași cifre în statul Iowa, unde tot 52% dintre republicani cred că Trump are personalitatea potrivită pentru a fi conducător, conform sondajului realizat săptămâna trecută de Quinnipiac.
|
||||
Totuși, 44% sunt de părere că nu are personalitatea necesară pentru a acționa eficient și aproape șase din 10 independenți afirmă că temperamentul său nu are ce căuta la Casa Albă, conform ABC/Post.
|
||||
Alegătorii republicani se obișnuiesc cu ideea.
|
||||
Atunci când iau atitudinea de intelectuali, alegătorii republicani consideră că Trump este autentic.
|
||||
Conform unui sondaj realizat săptămâna trecută de CNN/ORC, la întrebarea cine are cele mai multe șanse să câștige cursa pentru nominalizare GOP, patru din 10 au declarat că Trump.
|
||||
Situația s-a schimbat față de finalul lui iulie, când patru din 10 ar fi pariat pe Jeb Bush.
|
||||
Informare completă: în trecut, alegătorii GOP nu au citit foarte bine viitorul.
|
||||
În aceeași perioadă a ultimelor alegeri, patru din 10 republicani l-au ales pe Rick Perry în cursa pentru nominalizare, față de doar 28% pentru Mitt Romney.
|
||||
Însă, aceste cifre arată că majoritatea alegătorilor GOP consideră plauzibilă campania lui Trump.
|
||||
Chiar dacă republicanii sau repliat spre un alt candidat. Trump încă se află în fruntea tuturor.
|
||||
Unele voci spun că situația divizată va contribui probabil la victoria lui Trump, în timp ce susținerea contra lui Trump se va împărți la mai mult de doisprezece candidați.
|
||||
Însă un sondaj derulat la începutul lui septembrie de Universitatea din Monmouth arată că, în situația ipotetică a unei colaborări între Trump și majoritatea celorlalți candidați republicani, aproape întotdeauna Trump va beneficia de susținerea majoritară.
|
||||
Trump se află la distanță de 13 puncte de Carly Fiorina, la 14 puncte de Marco Rubio, la 15 puncte de Walker, la 19 puncte de Jeb Bush și, în cele din urmă, la câte 33 de puncte față de Rand Paul, John Kasich și Chris Christie.
|
||||
Este aproape la egalitate cu Ted Cruz.
|
||||
Singurul candidat care îl învinge?
|
||||
Ben Carson l-ar învinge pe omul de afaceri cu 19 puncte într-o confruntare ipotetică de unu la unu.
|
||||
Majoritatea susținătorilor lui Donald Trump declară că s-au decis.
|
||||
Un nou sondaj realizat marți de CBS/NYT arată că peste jumătate dintre alegătorii care îl susțin pe Trump declară că nu își schimbă opțiunea de vot.
|
||||
Evident, se pot întâmpla multe în acest sens și nimeni nu poate spune că aceștia nu se vor răzgândi niciodată.
|
||||
46% afirmă că lasă portița deschisă posibilității de a-și schimba opțiunea.
|
||||
Cu toate acestea, cel mai important adversar al lui Trump este în prezent neurochirurgul Ben Carson, însă este de două ori mai probabil ca alegătorii care declară că s-au decis să voteze cu Trump.
|
||||
Șase din 10 republicani afirmă că sunt de acord cu Trump în problema imigrării.
|
||||
De când Donald Trump i-a numit pe imigranții din Mexic „violatori” în discursul de deschidere a campaniei sale, în urmă cu două luni, imigrarea a fost subiectul central în campania pentru 2016.
|
||||
Unii sunt îngrijorați că stilul bombastic al lui Trump va duce la o scindare între alegătorii hispanici importanți și Partidul Republican și va prejudicia eforturile de rebranding.
|
||||
Însă, conform sondajului realizat luni de ABC/Post, șase din 10 republicani afirmă că sunt de acord cu Trump în problema imigrării.
|
||||
Așa că, se pare că atâta timp cât problema imigrării rămâne în lumina reflectoarelor, la fel va rămâne și Doland Trump.
|
||||
Frustrarea față de autorități atinge noi culmi.
|
||||
Donald Trump și Ben Carson sunt acum susținuți de aproape jumătate dintre alegătorii republicani, în mare parte datorită statutului lor de outsideri.
|
||||
Conform sondajului realizat luni de ABC/Post, șase din 10 republicani afirmă că preferă un outsider politic în detrimentul cuiva cu experiență în guvernare.
|
||||
Oamenii sunt de asemenea supărați pe autoritățile de la Washington.
|
||||
Un sondaj derulat în urmă cu două săptămâni în Iowa de către Des Moines Register/Bloomberg arată că trei din patru republicani din Iowa sunt frustrați de prestația republicanilor din COngres, 54% declarându-se „nemulțumiți” iar 21% „nervoși la culme”.
|
||||
Jeremy Corbyn își face debutul la Prime Minister's Questions
|
||||
Încă de la alegerea sa, debutul domnului Corbyn la PMQs a fost îndelung așteptat
|
||||
Noul lider al Partidului Laburist, Jeremy Corbyn, își va face mai târziu debutul la Prime Minister's Questions, confruntându-se pentru prima dată cu David Cameron.
|
||||
Dl Corbyn va adresa primele dintre cele șase întrebări la care are dreptul la scurt timp după prânz; prestația sa va fi probabil analizată îndeaproape de mass-media și parlamentarii laburiști.
|
||||
În cadrul aparițiilor săptămânale, el a cerut „mai puțin teatru și mai multe fapte”.
|
||||
A declarat de asemenea că poate renunța la câteva participări și că le cedează colegilor săi.
|
||||
Confruntarea va fi primul test parlamentar al Dl Corbyn în poziție de lider, venind după ce a numit un „cabinet fantomă” și după discursul pe care l-a ținut marți la congresul anual TUC.
|
||||
Între timp, decizia liderului Partidului laburist de a păstra tăcerea la rostirea imnului național în cadrul unei slujbe ținute marți cu ocazia aniversării a 75 de ani de la Bătălia Angliei a atras critici din partea unor parlamentari conservatori și a ținut prima pagină a ziarelor.
|
||||
Decizia domnului Corbyn de a nu cânta imnul național a atras atenția
|
||||
Un purtător de cuvânt al Dl Corbyn a declarat că acesta „a păstrat tăcerea în mod respectuos” și a recunoscut „eroismul Forțelor aeriene britanice în Bătălia Angliei.”
|
||||
Însă un membru al cabinetului fantomă al Dl Corbyn, Owen Smith, a declarat pentru emisiunea Two's Newsnight transmisă de BBC că i-ar fi recomandat liderului laburist să cânte imnul național „indiferent” de credința sa că monarhia ar trebui abolită.
|
||||
În jur de doisprezece miniștri din cabinetul fantomă au refuzat să facă parte din echipa de frunte a Dl Corbyn, argumentând prin diferențe de opinie legate de economie, apărare și externe, în timp ce mai puțin de o șesime din partidul parlamentar l-a susținut ca lider.
|
||||
Corespondentul politic al BBC, Robin Brant, declară că diferențele de politică „se cumulează” în Partidul Laburist după numirea domnului Corbyn referitor la poziția sa față de Uniunea Europeană și limita de beneficii.
|
||||
Dl Corbyn a declarat la conferința TUC că Partidul Laburist va aduce modificări prin care se va elimina integral ideea limitării.
|
||||
Câteva ore mai târziu, Dl Smith, Ministrul Muncii și Pensiilor, a declarat că partidul „este foarte clar” în opoziția exclusivă față de planurile guvernului de a reduce nivelul „cap” de la 26.000 lire la 23.000 lire.
|
||||
Dl Corbyn va fi al cincilea lider laburist cu care se confruntă David Cameron la tribună în ultimul deceniu, de când a preluat conducerea Partidului Conservator.
|
||||
Liderul laburist, care a promis o abordare diferită a politicii, spune că are idei „din surse externe” pentru întrebări pe care să i le adreseze Domnului Cameron și că a primit peste 30.000 de sugestii.
|
||||
Parlamentarul Islington North a afirmat că PMQs implică un nivel de confruntare prea înalt și că se va abține de la replici și atacuri, angajându-se să se concentreze în schimb pe probleme serioase precum sărăcia, inegalitatea și provocările cu care se confruntă tinerii.
|
||||
Dl Corbyn a declarat că Angela Eagle, Ministrul de finanțe, îi va ține locul la PMQs atunci când el nu poate participa - de exemplu atunci când Dl Cameron se deplasează în străinătate.
|
||||
A exprimat de asemenea ideea că va permite altor colegi să ia cuvântul ocazional, spunând că l-a abordat pe Președintele Camerei Deputaților, John Bercow, pentru a discuta acest aspect.
|
||||
În 2005, când a preluat conducerea, Dl Cameron a declarat că dorește să renunțe la stilul politic „Punch and Judy” asociat adesea cu PMQs însă a recunoscut câțiva ani mai târziu că nu a reușit în demersul său.
|
||||
De la prima transmisie, în 1990, PMQs a fost considerată un barometru cheie al raționamentului unui lider, al modului în care acesta conduce Camera Deputaților și a poziției sale în rândul colegilor parlamentari, deși criticii afirmă a ca devenit o caricatură și că are nevoie de o reformare profundă.
|
||||
„Cadru în Joburg”: Tineri fără adăpost beneficiază de cursuri de fotografie
|
||||
Este dificil să fii un om fără adăpost în Johannesburg.
|
||||
Însă un grup de oameni care au trăit pe străzi în copilărie au găsit un mod de a învăța o meserie și de a-și câștiga traiul.
|
||||
„I was shot în Joburg” este un studio non-profit care îi învață pe tinerii fără adăpost să facă fotografii ale zonelor în care trăiesc și să câștige bani din asta.
|
||||
BBC News s-a întâlnit cu unul dintre primii absolvenți ai proiectului.
|
||||
Șeful JD Sports spune că salariile mai mari ar putea dăuna extinderii
|
||||
Președintele JD Sports, Peter Cowgill, declară că o creștere a salariului minim în Marea Britanie ar putea însemna „o putere de cumpărare mai mare în buzunarele potențialilor consumatori.”
|
||||
Este însă puțin probabil ca respectiva putere de cumpărare să depășească costurile mai mari pentru forța de muncă în cadrul firmei, afirmă el.
|
||||
Costurile ar putea avea impact asupra planurilor de extindere ale JD Sports, a adăugat el, ceea ce ar putea însemna mai puține locuri de muncă noi.
|
||||
Thanasi Kokkinakis susținut de președintele Tennis Australia, Steve Healy
|
||||
Thanasi Kokkinakis ar merita să fie lăudat și nu criticat pentru comportamentul său.
|
||||
Thanasi Kokkinakis a fost victimă colaterală în „furtuna” creată în jurul prietenului său, Nick Kyrgios, iar comportamentul său merită mai degrabă cuvinte de laudă și nu critică, în opinia președintelui Tennis Australia, Steve Healy.
|
||||
@@ -0,0 +1,100 @@
|
||||
Membership of Parliament: see Minutes
|
||||
Approval of Minutes of previous sitting: see Minutes
|
||||
Membership of Parliament: see Minutes
|
||||
Verification of credentials: see Minutes
|
||||
Documents received: see Minutes
|
||||
Written statements and oral questions (tabling): see Minutes
|
||||
Petitions: see Minutes
|
||||
Texts of agreements forwarded by the Council: see Minutes
|
||||
Action taken on Parliament's resolutions: see Minutes
|
||||
Agenda for next sitting: see Minutes
|
||||
Closure of sitting
|
||||
(The sitting was closed at 7.45 p.m.)
|
||||
Election of Vice-Presidents of the European Parliament (deadline for submitting nominations): see Minutes
|
||||
(The sitting was suspended at 12.40 p.m. and resumed at 3.00 p.m.)
|
||||
Election of Quaestors of the European Parliament (deadline for submitting nominations): see Minutes
|
||||
(The sitting was suspended at 3.25 p.m. and resumed at 6.00 p.m.)
|
||||
Agenda for next sitting: see Minutes
|
||||
Closure of sitting
|
||||
(The sitting was closed at 6.15 p.m.)
|
||||
Opening of the sitting
|
||||
(The sitting was opened at 9.35 a.m.)
|
||||
Documents received: see Minutes
|
||||
Approval of Minutes of previous sitting: see Minutes
|
||||
Membership of Parliament: see Minutes
|
||||
Membership of committees (deadline for tabling amendments): see Minutes
|
||||
(The sitting was suspended at 7 p.m. and resumed at 9 p.m.)
|
||||
Agenda for next sitting: see Minutes
|
||||
Closure of sitting
|
||||
(The sitting was suspended at 23.25 p.m.)
|
||||
Documents received: see Minutes
|
||||
Communication of Council common positions: see Minutes
|
||||
(The sitting was suspended at 11.35 a.m. and resumed for voting time at noon)
|
||||
Approval of Minutes of previous sitting: see Minutes
|
||||
Committee of Inquiry into the crisis of the Equitable Life Assurance Society (extension of mandate): see Minutes
|
||||
Announcement by the President: see Minutes
|
||||
1.
|
||||
Membership of committees (vote)
|
||||
2.
|
||||
Amendment of the ACP-EC Partnership Agreement (vote)
|
||||
4.
|
||||
Certification of train drivers operating locomotives and trains on the railway system in the Community (vote)
|
||||
6.
|
||||
Law applicable to non-contractual obligations ("ROME II") (vote)
|
||||
8.
|
||||
Seventh and eighth annual reports on arms exports (vote)
|
||||
Corrections to votes and voting intentions: see Minutes
|
||||
Membership of committees and delegations: see Minutes
|
||||
Request for waiver of parliamentary immunity: see Minutes
|
||||
Decisions concerning certain documents: see Minutes
|
||||
Written statements for entry in the register (Rule 116): see Minutes
|
||||
Forwarding of texts adopted during the sitting: see Minutes
|
||||
Dates for next sittings: see Minutes
|
||||
Adjournment of the session
|
||||
I declare the session of the European Parliament adjourned.
|
||||
(The sitting was closed at 1 p.m.)
|
||||
Approval of Minutes of previous sitting: see Minutes
|
||||
Membership of Parliament: see Minutes
|
||||
Request for the defence of parliamentary immunity: see Minutes
|
||||
Appointments to committees (proposal by the Conference of Presidents): see Minutes
|
||||
Documents received: see Minutes
|
||||
Texts of agreements forwarded by the Council: see Minutes
|
||||
Action taken on Parliament's resolutions: see Minutes
|
||||
Oral questions and written statements (tabling): see Minutes
|
||||
Written statements (Rule 116): see Minutes
|
||||
Agenda: see Minutes
|
||||
1.
|
||||
Appointments to parliamentary committees (vote): see Minutes
|
||||
Voting time
|
||||
Agenda for next sitting: see Minutes
|
||||
Closure of sitting
|
||||
(The sitting was closed at 12 midnight)
|
||||
Opening of the sitting
|
||||
(The sitting was opened at 09.05)
|
||||
Documents received: see Minutes
|
||||
Approval of Minutes of previous sitting: see Minutes
|
||||
1.
|
||||
Protection of passengers against displaced luggage (vote)
|
||||
2.
|
||||
Approval of motor vehicles with regard to the forward field of vision of the driver (vote)
|
||||
3.
|
||||
EC-Korea Agreement on scientific and technological cooperation (vote)
|
||||
4.
|
||||
Mainstreaming sustainability in development cooperation policies (vote)
|
||||
5.
|
||||
Draft Amending Budget No 1/2007 (vote)
|
||||
7.
|
||||
EC-Gabon Fisheries Partnership (vote)
|
||||
10.
|
||||
Limitation periods in cross-border disputes involving personal injuries and fatal accidents (vote)
|
||||
12.
|
||||
Strategy for a strengthened partnership with the Pacific Islands (vote)
|
||||
13.
|
||||
The European private company statute (vote)
|
||||
That concludes the vote.
|
||||
Corrections to votes and voting intentions: see Minutes
|
||||
Assignment conferred on a Member: see Minutes
|
||||
Membership of committees and delegations: see Minutes
|
||||
Decisions concerning certain documents: see Minutes
|
||||
Forwarding of texts adopted during the sitting: see Minutes
|
||||
Dates for next sittings: see Minutes
|
||||
@@ -0,0 +1,100 @@
|
||||
Componenţa Parlamentului: a se vedea procesul-verbal
|
||||
Aprobarea procesului-verbal al şedinţei precedente: a se vedea procesul-verbal
|
||||
Componenţa Parlamentului: a se vedea procesul-verbal
|
||||
Verificarea prerogativelor: a se vedea procesul-verbal
|
||||
Depunere de documente: a se vedea procesul-verbal
|
||||
Declaraţii scrise şi întrebări orale (depunere): consultaţi procesul-verbal
|
||||
Petiţii: a se vedea procesul-verbal
|
||||
Transmiterea de către Consiliu a textelor acordurilor: a se vedea procesul-verbal
|
||||
Cursul dat rezoluţiilor Parlamentului: a se vedea procesul-verbal
|
||||
Ordinea de zi a următoarei şedinţe: a se vedea procesul-verbal
|
||||
Ridicarea şedinţei
|
||||
(Se levanta la sesión a las 19.45 horas)
|
||||
Alegerea vicepreşedinţilor Parlamentului European (termenul de depunere a candidaturilor): consultaţi procesul-verbal
|
||||
(Die Sitzung wird um 12.40 Uhr unterbrochen und um 15.00 Uhr wiederaufgenommen).
|
||||
Alegerea chestorilor Parlamentului European (termenul de depunere a candidaturilor): consultaţi procesul-verbal
|
||||
(Die Sitzung wird um 15.25 Uhr unterbrochen und um 18.00 Uhr wiederaufgenommen).
|
||||
Ordinea de zi a următoarei şedinţe: a se vedea procesul-verbal
|
||||
Ridicarea şedinţei
|
||||
(Die Sitzung wird um 18.15 Uhr geschlossen.)
|
||||
Deschiderea şedinţei
|
||||
(Die Sitzung wird um 9.35 Uhr eröffnet.)
|
||||
Depunerea documentelor: a se vedea procesul-verbal
|
||||
Aprobarea procesului-verbal al şedinţei precedente: a se vedea procesul-verbal
|
||||
Componenţa Parlamentului: a se vedea procesul-verbal
|
||||
Componenţa comisiilor (termenul de depunere a amendamentelor): consultaţi procesul-verbal
|
||||
(La seduta, sospesa alle 19.00, è ripresa alle 21.00)
|
||||
Ordinea de zi a următoarei şedinţe: a se vedea procesul-verbal
|
||||
Ridicarea şedinţei
|
||||
(Die Sitzung wird um 23.25 Uhr geschlossen.)
|
||||
Depunerea documentelor: a se vedea procesul-verbal
|
||||
Comunicarea poziţiilor comune ale Parlamentului: a se vedea procesul-verbal
|
||||
(La séance, suspendue à 11h35 dans l'attente de l'Heure des votes, est reprise à midi)
|
||||
Aprobarea procesului-verbal al şedinţei precedente: a se vedea procesul-verbal
|
||||
Comisia de anchetă privind criza societăţii de asigurări "Equitable Life” (prelungirea mandatului): consultaţi procesul-verbal
|
||||
Comunicarea Preşedintelui: consultaţi procesul-verbal
|
||||
1.
|
||||
Componenţa comisiilor (vot)
|
||||
2.
|
||||
Modificarea Acordului de parteneriat ACP-CE ("Acordul de la Cotonou”) (vot)
|
||||
4.
|
||||
Certificarea mecanicilor de locomotivă care conduc locomotive şi trenuri în sistemul feroviar comunitar (vot)
|
||||
6.
|
||||
Legea aplicabilă obligaţiilor necontractuale ("Roma II”) (vot)
|
||||
8.
|
||||
Al şaptelea şi al optulea raport anual privind exportul de armament (vot)
|
||||
Corectările voturilor şi intenţiile de vot: a se vedea procesul-verbal
|
||||
Componenţa comisiilor şi a delegaţiilor: a se vedea procesul-verbal
|
||||
Cerere de ridicare a imunităţii parlamentare: consultaţi procesul-verbal
|
||||
Decizii privind anumite documente: a se vedea procesul-verbal
|
||||
Declaraţii scrise înscrise în registru (articolul 116 din Regulamentul de procedură): a se vedea procesul-verbal
|
||||
Transmiterea textelor adoptate în cursul prezentei şedinţe: a se vedea procesul-verbal
|
||||
Calendarul următoarelor şedinţe: a se vedea procesul-verbal
|
||||
Întreruperea sesiunii
|
||||
Dichiaro interrotta la sessione del Parlamento europeo.
|
||||
(La seduta è tolta alle 13.00)
|
||||
Aprobarea procesului-verbal al şedinţei precedente: a se vedea procesul-verbal
|
||||
Componenţa Parlamentului: a se vedea procesul-verbal
|
||||
Cerere de apărare a imunităţii parlamentare: consultaţi procesul-verbal
|
||||
Numiri în comisii (propunerea Conferinţei preşedinţilor): consultaţi procesul-verbal
|
||||
Depunerea documentelor: a se vedea procesul-verbal
|
||||
Transmiterea de către Consiliu a textelor acordurilor: a se vedea procesul-verbal
|
||||
Continuări ale rezoluţiilor Parlamentului: consultaţi procesul-verbal
|
||||
Declaraţii scrise şi întrebări orale (depunere): consultaţi procesul-verbal
|
||||
Declaraţii scrise (articolul 116 din Regulamentul de procedură)
|
||||
Ordinea de zi: a se vedea procesul-verbal
|
||||
1.
|
||||
Numiri în comisiile parlamentare (vot): consultaţi procesul-verbal
|
||||
Timpul afectat votului
|
||||
Ordinea de zi a următoarei şedinţe: a se vedea procesul-verbal
|
||||
Ridicarea şedinţei
|
||||
(La seduta è tolta alle 24.00)
|
||||
Deschiderea şedinţei
|
||||
(The sitting was opened at 09.05)
|
||||
Depunerea documentelor: a se vedea procesul-verbal
|
||||
Aprobarea procesului-verbal al şedinţei precedente: a se vedea procesul-verbal
|
||||
1.
|
||||
Protecţia pasagerilor împotriva deplasării bagajelor (vot)
|
||||
2.
|
||||
Omologarea vehiculelor cu motor cu privire la câmpul de vizibilitate înainte al conducătorului auto (vot)
|
||||
3.
|
||||
Acordul CE-Coreea de cooperare ştiinţifică şi tehnologică (vot)
|
||||
4.
|
||||
Integrarea durabilităţii în politicile de cooperare pentru dezvoltare (vot)
|
||||
5.
|
||||
Proiect de buget rectificativ nr.1/2007 (vot)
|
||||
7.
|
||||
Acordul de parteneriat în domeniul pescuitului între Comunitatea Europeană şi Republica Gaboneză (vot)
|
||||
10.
|
||||
Termenele de prescripţie aplicabile în cadrul litigiilor transfrontaliere cu privire la vătămările corporale şi accidentele mortale (vot)
|
||||
12.
|
||||
Relaţiile UE cu insulele din Pacific: Strategie pentru un parteneriat consolidat (vot)
|
||||
13.
|
||||
Statutul societăţii private europene (vot)
|
||||
Damit ist die Abstimmungsstunde beendet.
|
||||
Corectările voturilor şi intenţiile de vot: a se vedea procesul-verbal
|
||||
Misiune încredinţată unui deputat: consultaţi procesul-verbal
|
||||
Componenţa comisiilor şi a delegaţiilor: a se vedea procesul-verbal
|
||||
Decizii privind anumite documente: a se vedea procesul-verbal
|
||||
Transmiterea textelor adoptate în cursul prezentei şedinţe: a se vedea procesul-verbal
|
||||
Calendarul următoarelor şedinţe: a se vedea procesul-verbal
|
||||
@@ -0,0 +1,100 @@
|
||||
Brazil's Former Presidential Chief-of-Staff to Stand Trial
|
||||
A federal judge on Tuesday accepted the charges filed against Brazil's former presidential chief of staff for his alleged involvement in a massive corruption scheme at state-owned oil company Petrobras.
|
||||
The federal prosecutor's office said Jose Dirceu will face trial on the corruption, racketeering and money laundering charges filed earlier this month.
|
||||
Fourteen other people will also be tried, including Joao Vaccari Neto, the former treasurer of Brazil's governing Workers' Party and Renato de Souza Duque, Petrobras' former head of corporate services.
|
||||
Dirceu is the most senior member of the ruling Workers' Party to be taken into custody in connection with the scheme.
|
||||
Dirceu served as former President Luiz Inacio Lula da Silva's chief of staff between 2003 and 2005.
|
||||
He was arrested early August in his home, where he already was under house arrest serving an 11-year sentence for his involvement in a cash-for-votes scheme in Congress more than 10 years ago.
|
||||
Prosecutors have said that Dirceu masterminded the kickback scheme at Petrobras, accepted bribes while in office and continued to receive payments from contractors after he was jailed in late 2013 for the vote-buying scandal.
|
||||
According to prosecutors, the scheme at Petrobras involved roughly $2 billion in bribes and other illegal funds.
|
||||
Some of that money was allegedly funneled back to campaign coffers of the ruling party and its allies.
|
||||
It also allegedly included the payment of bribes to Petrobras executives in return for inflated contracts.
|
||||
'Miraculous' recovery for Peshawar massacre schoolboy
|
||||
A teenager paralysed after being shot four times in Pakistan's deadliest terror attack has made a "miraculous" recovery following treatment in the UK.
|
||||
Muhammad Ibrahim Khan, 13, had been told by doctors in Pakistan that he would never walk again.
|
||||
At least 140 people, mostly children, were killed when gunmen stormed Peshawar's Army Public School last December.
|
||||
Muhammad, who arrived in London last month for surgery, is being discharged from hospital later.
|
||||
Exactly nine months ago, on an ordinary Tuesday morning, Muhammad sat in his first aid class listening to his teachers intently.
|
||||
At the same time seven gunmen disguised in security uniforms were entering the Army Public School.
|
||||
They were strapped with explosives and had one simple mission in mind: Kill every man, woman and child they came across.
|
||||
"I can't forget what happened that day," Muhammad says with a severe stare.
|
||||
We were sitting in the auditorium, we were asking questions... and then we heard heavy gunfire outside.
|
||||
The terrorists moved inside and they started killing - our teacher was burned alive.
|
||||
Muhammad described pulling four other pupils out of the auditorium as the carnage unfolded.
|
||||
He said he then heard his friend, Hamza calling to him.
|
||||
He said, 'oh brother save me'.
|
||||
I held his hand.
|
||||
That's when I was shot in the back, and he was shot in the head.
|
||||
Most of the people killed in the attack were pupils
|
||||
Hamza died in Muhammad's arms.
|
||||
Muhammad recalled blacking out after that, and the next thing he knew he was in a hospital bed, paralysed from the waist down.
|
||||
Doctors in Peshawar in northern Pakistan, and then Rawalpindi, close to the capital, told his family there was no treatment, and he would never walk again.
|
||||
"Seeing him I felt like my soul had left my body," says Muhammad's father, Sher Khan
|
||||
Those nine months were the hardest in my life.
|
||||
But Mr Khan and his wife, Sherbano, refused to believe that their cricket-mad son would never be able to use his legs again.
|
||||
They campaigned, and appealed for help on Pakistani TV, gaining the support of high profile people such as cricketer turned politician Imran Khan.
|
||||
Finally, they were able to raise the funds to bring Muhammad to the UK and provide him with treatment at London's private Harley Street Clinic.
|
||||
Consultant neurosurgeon Irfan Malik described Muhammad as "terrified" when he first arrived at the hospital.
|
||||
"He'd spent the last [few] months lying on a bed, unable to move side to side," says Mr Malik.
|
||||
He was weak, he had a pressure sore on his back.
|
||||
He wasn't in great shape.
|
||||
A vertebra at the base of Muhammad's spine was destroyed
|
||||
Muhammad was shot in his shoulder, his hip, and his back during the attack, damaging his lower spine - leading to paralysis.
|
||||
But during six hours of surgery, Mr Malik and his team were able to reattach nerve endings and reconstruct the damaged part of the spine.
|
||||
Even Mr Malik was surprised at what happened next.
|
||||
Exactly one week after the surgery Muhammad stood up and started taking steps and walking.
|
||||
We were not expecting to get that sort of excellent result.
|
||||
That was miraculous," he says.
|
||||
Less than two weeks after his operation, Muhammad is ready to leave hospital and start the long road to recovery.
|
||||
Muhammad has defied the odds and started to walk again
|
||||
He says he wants to build his strength and continue his education in the UK.
|
||||
But he says he is determined to return to Pakistan, join the army and help fight terrorism.
|
||||
"I feel like I have a second chance at life," he says as he shows off pictures he's drawn of guns scribbled out next to school books and pens
|
||||
Muhammad grows physically stronger every day but the psychological trauma he continues to endure is unimaginable.
|
||||
"My anger is not diminishing" he says.
|
||||
In my school little kids were killed.
|
||||
What was their crime?
|
||||
His mother, wiping a tear from her eye, caressed his head and said: "I can see my son walking again."
|
||||
He'll be able to get on with his normal life.
|
||||
'Super Voice' 4G service from Three offers better signal
|
||||
Three is making use of a lower frequency 4G spectrum that can travel more widely
|
||||
Mobile phone provider Three has launched a UK service it says will improve reception inside buildings and in rural black spots.
|
||||
Its 4G Super Voice enables customers to make calls and send texts using a lower frequency spectrum.
|
||||
Other networks are looking into introducing the technology, known as Voice Over Long-Term Evolution (VoLTE).
|
||||
It currently works on only the Samsung Galaxy S5, but recent iPhone handsets will be added in the coming months.
|
||||
Three said up to 5.5 million customers would have access to the service by 2017.
|
||||
Chief technology officer Bryn Jones said: "By the end of the year, one million of our customers will have access to better indoor coverage and be able to use their phones in more places than ever before."
|
||||
Stars prepare for panto season
|
||||
Pantomime season is big business for theatres up and down the UK, with many getting ready for this year's season now.
|
||||
Some of the biggest names in showbusiness now take part in the yuletide theatre.
|
||||
Matthew Kelly and Hayley Mills will be appearing in Cinderella - one as an ugly sister, the other as fairy godmother.
|
||||
They reveal their panto secrets to BBC Breakfast.
|
||||
Steven Wilson: 'If I don't do anything, I feel this creeping guilt'
|
||||
Steven Wilson was recently the big winner at the Progressive Music Awards
|
||||
Steven Wilson is often dubbed the hardest working musician in the world of progressive rock.
|
||||
The multi-talented musician won three prizes at this month's Progressive Music Awards in London, including album of the year for Hand.
|
||||
The Guardian's five-star review called it "a smart, soulful and immersive work of art."
|
||||
Since the 1980s, Wilson has been the driving force in a number of musical projects, the best known of which is the rock band Porcupine Tree.
|
||||
Now, ahead of two sell-out shows at the Royal Albert Hall, Wilson is releasing a vinyl-only double LP, Transience, to showcase the "more accessible" side of his solo output.
|
||||
He tells the BBC about his love of vinyl, his busy schedule and explains how comic actor Matt Berry came to be his support act.
|
||||
What does vinyl mean to you?
|
||||
I grew up at the very tail end of the vinyl era, and at the time, I remember, we couldn't wait for CD to come along because vinyl was so frustrating.
|
||||
You would buy the record, take it home, and it would have a scratch, and you would have to take it back again.
|
||||
I love CDs, and for some kinds of music - classical for example - it is better than vinyl.
|
||||
But the problem with the CD and digital downloads is that there's nothing you can really cherish or treasure.
|
||||
Owning vinyl is like having a beautiful painting hanging in your living room.
|
||||
It's something you can hold, pore over the lyrics and immerse yourself in the art work.
|
||||
I thought it was just a nostalgic thing, but it can't be if kids too young to remember vinyl are enjoying that kind of experience.
|
||||
Do you have a piece of vinyl that you treasure?
|
||||
The truth is I got rid of 100% of my vinyl in the 90s.
|
||||
All the vinyl I have is re-bought.
|
||||
I started off from the perspective that I wanted to recreate the collection I had when I was 15, but it's gone beyond that.
|
||||
The first record which I persuaded my parents to buy for me was Electric Light Orchestra's Out of the Blue.
|
||||
If I still had my original copy, it would have sentimental value, but, alas, it's in a charity shop somewhere.
|
||||
Steven Wilson hopes the album will be a doorway for potential new fans
|
||||
Why release your new compilation Transience on vinyl?
|
||||
It was originally conceived as an idea for Record Store Day, but we missed the boat on that.
|
||||
My record company had suggested I put together some of my shorter, more accessible songs.
|
||||
I got a bit obsessed by the idea to make something like "an introduction to Steven Wilson," and I was committed to it being a vinyl-only release.
|
||||
Anyone who buys the vinyl does also get a high-resolution download.
|
||||
Do you have a concern that the album won't show your work in a true light?
|
||||
@@ -0,0 +1,100 @@
|
||||
Fostul șef al cabinetului prezidențial brazilian este adus în fața instanței
|
||||
Marți, un judecător federal a acceptat acuzațiile aduse împotriva fostului șef al cabinetului prezidențial brazilian pentru presupusa implicare a acestuia într-o schemă masivă de corupție privind compania petrolieră de stat Petrobras.
|
||||
Biroul procurorului federal a declarat că Jose Dirceu va fi trimis în judecată pentru acuzațiile de corupție, înșelătorie și spălare de bani aduse în această lună.
|
||||
Alte paisprezece persoane vor fi judecate, printre acestea numărându-se Joao Vaccari Neto, fostul trezorier al Partidului Muncitorilor, aflat la putere în Brazilia, și Renato de Souza Duque, fostul președinte al serviciilor pentru întreprinderi ale Petrobras.
|
||||
Dirceu este cel mai vechi membru al Partidului Muncitorilor aflat la guvernare luat în custodie pentru legăturile cu această schemă.
|
||||
Dirceu a servit ca șef de cabinet al fostului președinte Luiz Inacio Lula da Silva între 2003 și 2005.
|
||||
A fost arestat la începutul lui august de acasă, unde deja se afla sub arest la domiciliu, cu o pedeapsă de 11 ani pentru implicarea într-o schemă de cumpărare a voturilor în Congres cu peste 10 ani în urmă.
|
||||
Procurorii au declarat că Dirceu a dezvoltat schema de luare de mită de la Petrobras, a acceptat mită în timp ce se afla în funcție și a continuat să primească plăți de la antreprenori după ce a fost închis la sfârșitul lui 2013 pentru scandalul voturilor cumpărate.
|
||||
Conform procurorilor, schema de la Petrobras a implicat aproximativ 2 miliarde de dolari sub formă de mită și alte fonduri ilegale.
|
||||
O parte din acei bani s-ar fi întors în fondul de campanie al partidului aflat la guvernare și al aliaților acestora.
|
||||
De asemenea, ar fi inclus mită către directorii Petrobras în schimbul unor contracte umflate.
|
||||
Recuperarea „miraculoasă” a unui elev supraviețuitor al masacrului de la Peshawar
|
||||
Un adolescent paralizat după ce fusese împușcat de patru ori în cel mai cumplit atac terorist din Pakistan a reușit o recuperare „miraculoasă” după ce a urmat un tratament în Regatul Unit.
|
||||
Lui Mohamed Ibrahim Khan, în vârstă de 13 ani, doctorii din Pakistan îi spuseseră că nu va mai putea să meargă niciodată.
|
||||
Cel puțin 140 de persoane, majoritatea copii, au fost ucise când bărbați înarmați au atacat școala publică a armatei din Peshawar în luna decembrie a anului trecut.
|
||||
Mohamed, care a sosit la Londra luna trecută pentru operație, va fi externat mai târziu din spital.
|
||||
Exact cu nouă luni în urmă, într-o dimineață obișnuită de marți, Mohamed stătea la ora de primul ajutor și își asculta atent profesorii.
|
||||
Chiar atunci, șapte bărbați înarmați deghizați în uniformele agenților de pază intrau în școala publică a armatei.
|
||||
Purtau centuri cu explozivi și aveau de îndeplinit o misiune simplă: să îi ucidă pe toți bărbații, femeile și copiii care le ieșeau în cale.
|
||||
„Nu pot uita ce s-a întâmplat în acea zi”, spune Mohamed cu o privire aspră.
|
||||
Stăteam în amfiteatru, puneam întrebări... apoi am auzit focuri de armă afară.
|
||||
Teroriștii au intrat înăuntru și au început să ucidă. Profesorul nostru a fost ars de viu.
|
||||
Mohamed descrie cum a scos patru elevi din amfiteatru în timp ce se desfășura carnagiul.
|
||||
Apoi spune că și-a auzit prietenul, pe Hamza, strigându-l.
|
||||
Spunea „oh, frate, salvează-mă”.
|
||||
L-am ținut de mână.
|
||||
Atunci eu am fost împușcat în spate, iar el în cap.
|
||||
Cei mai mulți dintre cei uciși în atac erau elevi
|
||||
Hamza a murit în brațele lui Mohamed.
|
||||
Mohamed își amintește că imediat după asta a leșinat și că următorul lucru pe care l-a știut a fost că se afla pe un pat de spital, paralizat de la brâu în jos.
|
||||
Doctorii din Peshawar din nordul Pakistanului, apoi cei din Rawalpindi, aproape de capitală, i-au spus familiei sale că nu exista tratament și că nu va mai putea merge niciodată.
|
||||
„Când l-am văzut, am simțit cum îmi iese sufletul”, spune Sher Khan, tatăl lui Mohamed.
|
||||
Acele nouă luni au fost cele mai grele din viața mea.
|
||||
Însă Khan și soția lui, Sherbano, au refuzat să creadă că fiul lor atât de pasionat de crichet nu-și va mai putea folosi vreodată picioarele.
|
||||
Au făcut o campanie și au cerut ajutor de la televiziunea pakistaneză, atrăgând sprijinul unor oameni faimoși precum Imran Khan, jucător de crichet devenit politician.
|
||||
Într-un final, au reușit să strângă fonduri pentru a-l duce pe Mohamed în Regatul Unit și a-i oferi tratament la clinica privată Harley Street din Londra.
|
||||
Neurochirurgul consultant Irfan Malik l-a descris pe Mohamed drept „înspăimântat” când acesta a ajuns la spital.
|
||||
„Își petrecuse ultimele [câteva] luni zăcând în pat, fără să se poată mișca de pe o parte pe alta, spune Malik.
|
||||
Era slăbit, se pusese multă presiune pe spatele lui.
|
||||
Nu era într-o formă prea bună.
|
||||
O vertebră de la baza coloanei vertebrale a lui Mohamed fusese distrusă
|
||||
Mohamed fusese împușcat în umăr, în șold și în spate în timpul atacului, iar coloana vertebrală inferioară îi fusese distrusă, ducând la paralizie.
|
||||
Însă, în timpul unei operații care a durat șase ore, Malik și echipa lui au reușit să lege din nou terminațiile nervoase și să reconstruiască partea distrusă a coloanei.
|
||||
Chiar și Malik a fost surprins de ceea ce s-a întâmplat în continuare.
|
||||
Exact la o săptămână după operație, Mohamed s-a ridicat și a început să facă pași și să meargă.
|
||||
Nu ne așteptam la un rezultat atât de bun.
|
||||
A fost un miracol”, spune acesta.
|
||||
În mai puțin de două săptămâni de la operație, Mohamed este gata să părăsească spitalul și să înceapă procesul lung de recuperare.
|
||||
Mohamed a sfidat soarta și a început să meargă din nou
|
||||
Vrea să devină puternic și să își continue studiile în Regatul Unit.
|
||||
Însă este hotărât să revină în Pakistan, să se înroleze în armată și să lupte împotriva terorismului.
|
||||
„Simt că am încă o șansă la viață” spune el, arătând imaginile cu arme desenate de el lângă manuale școlare și stilouri
|
||||
Fizic, Mohamed devine tot mai puternic în fiecare zi, însă trauma psihologică prin care trece și acum este de neimaginat.
|
||||
„Furia mea nu a scăzut”, mărturisește el.
|
||||
În școala mea au fost uciși copii mici.
|
||||
Ce crimă au comis ei?
|
||||
Mama lui își șterge o lacrimă, îl mângâie pe creștet și spune: „Îmi văd fiul mergând din nou”.
|
||||
Va putea să-și continue firesc viața.
|
||||
Serviciul 4G „Super Voice” de la Three oferă semnal mai bun
|
||||
Three folosește un spectru 4G cu o frecvență mai joasă, care poate acoperi o zonă mai extinsă
|
||||
Furnizorul de telefonie mobilă Three a lansat în Regatul Unit un serviciu despre care spune că va îmbunătăți recepția în interiorul clădirilor și în zonele rurale fără semnal.
|
||||
Serviciul 4G Super Voice le permite clienților să efectueze apeluri și să trimită mesaje text folosind un spectru cu o frecvență mai joasă.
|
||||
Și alte rețele intenționează să introducă aceeași tehnologie, cunoscută ca „Voice Over Long-Term Evolution (VoLTE)”.
|
||||
Aceasta funcționează momentan doar cu Samsung Galaxy S5, însă telefoanele iPhone recente vor beneficia de ea în lunile următoare.
|
||||
Three menționează că până la 5,5 milioane de clienți vor avea acces la serviciu până în 2017.
|
||||
Responsabilul șef pentru tehnologie, Bryn Jones a declarat: „Până la sfârșitul anului, un milion dintre clienții noștri vor avea acces la o acoperire mai bună în interior și își vor putea folosi telefoanele în mai multe locuri ca până acum”.
|
||||
Vedetele se pregătesc pentru stagiunea de pantomimă
|
||||
Stagiunea de pantomimă este foarte importantă pentru teatrele din tot Regatul Unit, multe dintre ele pregătindu-se acum pentru stagiunea din acest an.
|
||||
Acum, la teatrul de Crăciun participă unele dintre numele cele mai mari din showbusiness.
|
||||
Matthew Kelly și Hayley Mills vor apărea în Cenușăreasa - primul în rolul uneia dintre surorile rele, iar a doua în rolul zânei.
|
||||
Aceștia dezvăluie secretele pantomimei lor la BBC Breakfast.
|
||||
Steven Wilson: „Dacă nu fac nimic, mă simt vinovat”
|
||||
Steven Wilson a fost desemnat recent drept marele câștigător al Progressive Music Awards
|
||||
Steven Wilson a fost numit de multe ori drept cel mai muncitor muzician din lumea rockului progresiv.
|
||||
Talentatul muzician a câștigat trei premii la Progressive Music Awards, care a avut loc luna aceasta la Londra, printre care și premiul pentru cel mai bun album al anului pentru Hand.
|
||||
În recenzia sa de cinci stele, The Guardian a numit albumul „o operă de artă inteligentă, expresivă și captivantă”.
|
||||
Încă din anii 1980, Wilson este motorul mai multor proiecte muzicale, cel mai cunoscut dintre acestea fiind trupa de rock Porcupine Tree.
|
||||
Acum, înainte de două spectacole cu casa închisă la Royal Albert Hall, Wilson lansează un dublu LP doar în format vinil, Transience, pentru a arăta latura „mai accesibilă” a activității sale solo.
|
||||
A povestit pentru BBC despre dragostea lui pentru viniluri și despre programul său încărcat și a explicat cum a ajuns actorul de comedie Matt Berry să îi deschidă spectacolele.
|
||||
Ce înseamnă vinil pentru tine?
|
||||
Am crescut chiar în perioada de sfârșit a erei vinilurilor și îmi amintesc că atunci abia așteptam apariția CD-ului, căci vinilul era atât de enervant.
|
||||
Cumpărai un disc, mergeai cu el acasă, avea o zgârietură și trebuia să îl aduci înapoi.
|
||||
Iubesc CD-urile, iar pentru anumite tipuri de muzică, de exemplu cea clasică, sunt mai bune decât vinilurile.
|
||||
Însă problema cu CD-urile și cu descărcările digitale este aceea că nu mai există nimic pe care să îl prețuiești cu adevărat.
|
||||
Să ai un vinil e ca și cum ai avea un tablou frumos agățat în sufragerie.
|
||||
E ceva ce poți ține în mână, în timp ce te lași absorbit de versuri și copleșit de actul artistic.
|
||||
Am crezut că e doar o chestie nostalgică, însă nu are cum să fie așa dacă unor puști prea tineri să-și amintească de viniluri le place acest gen de experiență.
|
||||
Ai vreun vinil la care ții în mod special?
|
||||
Recunosc că am scăpat de toate vinilurile în anii '90.
|
||||
Toate vinilurile pe care le am sunt cumpărate din nou.
|
||||
Am pornit de la ideea de a reface colecția pe care o aveam la 15 ani, însă am trecut de limita aceea.
|
||||
Primul disc pe care mi-am convins părinții să mi-l cumpere a fost Out of the Blue de la Electric Light Orchestra.
|
||||
Dacă aș mai fi avut încă exemplarul inițial, acesta ar fi avut valoare sentimentală, însă, din păcate, se află pe undeva printr-un magazin de caritate.
|
||||
Steven Wilson speră că albumul va fi o poartă către posibili fani noi
|
||||
De ce ți-ai lansat noua compilație Transience pe vinil?
|
||||
Aceasta a fost concepută inițial ca idee pentru Ziua magazinelor de discuri, însă am ratat ocazia.
|
||||
Casa mea de discuri sugerase să adun câteva dintre melodiile mele mai scurte și mai accesibile.
|
||||
Am ajuns să fiu ușor obsedat de ideea de a face ceva gen „introducere în muzica lui Steven Wilson” și am ținut neapărat ca proiectul să fie lansat doar pe vinil.
|
||||
Cine cumpără vinilul primește, de asemenea, și o variantă descărcată la rezoluție înaltă.
|
||||
Ești îngrijorat că albumul nu va arăta muzica ta în adevărata ei lumină?
|
||||
@@ -9,15 +9,17 @@ from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from pytest import param
|
||||
from torch.utils.data import DataLoader
|
||||
|
||||
from transformers import AutoTokenizer
|
||||
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, MBartTokenizer
|
||||
from transformers.testing_utils import require_multigpu
|
||||
|
||||
from .distillation import distill_main, evaluate_checkpoint
|
||||
from .finetune import main
|
||||
from .pack_dataset import pack_data_dir
|
||||
from .run_eval import generate_summaries_or_translations, run_generate
|
||||
from .utils import SummarizationDataset, lmap, load_json
|
||||
from .utils import MBartDataset, Seq2SeqDataset, label_smoothed_nll_loss, lmap, load_json
|
||||
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
@@ -25,7 +27,9 @@ logging.basicConfig(level=logging.DEBUG)
|
||||
logger = logging.getLogger()
|
||||
CUDA_AVAILABLE = torch.cuda.is_available()
|
||||
CHEAP_ARGS = {
|
||||
"logger": "default",
|
||||
"label_smoothing": 0.2,
|
||||
"early_stopping_patience": 2,
|
||||
"logger_name": "default",
|
||||
"length_penalty": 0.5,
|
||||
"cache_dir": "",
|
||||
"task": "summarization",
|
||||
@@ -47,7 +51,7 @@ CHEAP_ARGS = {
|
||||
"max_grad_norm": 1.0,
|
||||
"do_train": True,
|
||||
"do_predict": True,
|
||||
"gradient_accumulation_steps": 1,
|
||||
"accumulate_grad_batches": 1,
|
||||
"server_ip": "",
|
||||
"server_port": "",
|
||||
"seed": 42,
|
||||
@@ -59,7 +63,7 @@ CHEAP_ARGS = {
|
||||
"weight_decay": 0.0,
|
||||
"adam_epsilon": 1e-08,
|
||||
"warmup_steps": 0,
|
||||
"num_train_epochs": 1,
|
||||
"max_epochs": 1,
|
||||
"train_batch_size": 2,
|
||||
"eval_batch_size": 2,
|
||||
"max_source_length": 12,
|
||||
@@ -79,11 +83,11 @@ CHEAP_ARGS = {
|
||||
|
||||
|
||||
def _dump_articles(path: Path, articles: list):
|
||||
with path.open("w") as f:
|
||||
f.write("\n".join(articles))
|
||||
content = "\n".join(articles)
|
||||
Path(path).open("w").writelines(content)
|
||||
|
||||
|
||||
ARTICLES = [" Sam ate lunch today", "Sams lunch ingredients"]
|
||||
ARTICLES = [" Sam ate lunch today.", "Sams lunch ingredients."]
|
||||
SUMMARIES = ["A very interesting story about what I ate for lunch.", "Avocado, celery, turkey, coffee"]
|
||||
T5_TINY = "patrickvonplaten/t5-tiny-random"
|
||||
BART_TINY = "sshleifer/bart-tiny-random"
|
||||
@@ -121,7 +125,7 @@ class TestSummarizationDistiller(unittest.TestCase):
|
||||
updates = dict(
|
||||
student_encoder_layers=2,
|
||||
student_decoder_layers=1,
|
||||
num_train_epochs=4,
|
||||
max_epochs=4,
|
||||
val_check_interval=0.25,
|
||||
alpha_hid=2.0,
|
||||
model_name_or_path="IGNORE_THIS_IT_DOESNT_GET_USED",
|
||||
@@ -139,6 +143,26 @@ class TestSummarizationDistiller(unittest.TestCase):
|
||||
|
||||
evaluate_checkpoint(ckpts[0], dest_dir=Path(tempfile.mkdtemp()))
|
||||
|
||||
def test_loss_fn(self):
|
||||
model = AutoModelForSeq2SeqLM.from_pretrained(BART_TINY)
|
||||
input_ids, mask = model.dummy_inputs["input_ids"], model.dummy_inputs["attention_mask"]
|
||||
target_ids = torch.tensor([[0, 4, 8, 2], [0, 8, 2, 1]], dtype=torch.long, device=model.device)
|
||||
decoder_input_ids = target_ids[:, :-1].contiguous() # Why this line?
|
||||
lm_labels = target_ids[:, 1:].clone() # why clone?
|
||||
model_computed_loss = model(
|
||||
input_ids, attention_mask=mask, decoder_input_ids=decoder_input_ids, labels=lm_labels, use_cache=False
|
||||
).loss
|
||||
|
||||
logits = model(input_ids, attention_mask=mask, decoder_input_ids=decoder_input_ids, use_cache=False).logits
|
||||
|
||||
lprobs = torch.nn.functional.log_softmax(logits, dim=-1)
|
||||
smoothed_loss, nll_loss = label_smoothed_nll_loss(
|
||||
lprobs, lm_labels, 0.1, ignore_index=model.config.pad_token_id
|
||||
)
|
||||
with self.assertRaises(AssertionError):
|
||||
# TODO: understand why this breaks
|
||||
self.assertEqual(nll_loss, model_computed_loss)
|
||||
|
||||
@unittest.skip("T5 distillation is broken at the moment")
|
||||
def test_distill_t5(self):
|
||||
updates = dict(
|
||||
@@ -153,9 +177,11 @@ class TestSummarizationDistiller(unittest.TestCase):
|
||||
|
||||
def _test_distiller_cli(self, updates, check_contents=True):
|
||||
default_updates = dict(
|
||||
label_smoothing_eps=0.0,
|
||||
early_stopping_patience=-1,
|
||||
train_batch_size=1,
|
||||
eval_batch_size=2,
|
||||
num_train_epochs=2,
|
||||
max_epochs=2,
|
||||
alpha_mlm=0.2,
|
||||
alpha_ce=0.8,
|
||||
do_predict=True,
|
||||
@@ -186,7 +212,7 @@ class TestSummarizationDistiller(unittest.TestCase):
|
||||
self.assertGreaterEqual(last_step_stats["val_avg_gen_time"], 0.01)
|
||||
self.assertGreaterEqual(1.0, last_step_stats["val_avg_gen_time"])
|
||||
self.assertIsInstance(last_step_stats[f"val_avg_{model.val_metric}"], float)
|
||||
desired_n_evals = int(args_d["num_train_epochs"] * (1 / args_d["val_check_interval"]) + 1)
|
||||
desired_n_evals = int(args_d["max_epochs"] * (1 / args_d["val_check_interval"]) + 1)
|
||||
self.assertEqual(len(metrics["val"]), desired_n_evals)
|
||||
self.assertEqual(len(metrics["test"]), 1)
|
||||
return model
|
||||
@@ -207,11 +233,13 @@ def test_run_eval_bart(model):
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
["model"], [pytest.param(T5_TINY), pytest.param(BART_TINY), pytest.param(MBART_TINY), pytest.param(MARIAN_TINY)]
|
||||
["model"], [pytest.param(T5_TINY), pytest.param(BART_TINY), pytest.param(MBART_TINY), pytest.param(MARIAN_TINY)],
|
||||
)
|
||||
def test_finetune(model):
|
||||
args_d: dict = CHEAP_ARGS.copy()
|
||||
task = "translation" if model in [MBART_TINY, MARIAN_TINY] else "summarization"
|
||||
args_d["label_smoothing"] = 0.1 if task == "translation" else 0
|
||||
|
||||
tmp_dir = make_test_data_dir()
|
||||
output_dir = tempfile.mkdtemp(prefix="output_")
|
||||
args_d.update(
|
||||
@@ -249,22 +277,68 @@ def test_finetune(model):
|
||||
assert bart.decoder.embed_tokens == bart.shared
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
["tok"], [pytest.param(T5_TINY), pytest.param(BART_TINY), pytest.param(MBART_TINY), pytest.param(MARIAN_TINY)]
|
||||
)
|
||||
def test_dataset(tok):
|
||||
def test_pack_dataset():
|
||||
tokenizer = AutoTokenizer.from_pretrained("facebook/mbart-large-cc25")
|
||||
|
||||
tmp_dir = Path(make_test_data_dir())
|
||||
orig_examples = tmp_dir.joinpath("train.source").open().readlines()
|
||||
save_dir = Path(tempfile.mkdtemp(prefix="packed_"))
|
||||
pack_data_dir(tokenizer, tmp_dir, 128, save_dir)
|
||||
orig_paths = {x.name for x in tmp_dir.iterdir()}
|
||||
new_paths = {x.name for x in save_dir.iterdir()}
|
||||
packed_examples = save_dir.joinpath("train.source").open().readlines()
|
||||
# orig: [' Sam ate lunch today.\n', 'Sams lunch ingredients.']
|
||||
# desired_packed: [' Sam ate lunch today.\n Sams lunch ingredients.']
|
||||
assert len(packed_examples) < len(orig_examples)
|
||||
assert len(packed_examples) == 1
|
||||
assert len(packed_examples[0]) == sum(len(x) for x in orig_examples)
|
||||
assert orig_paths == new_paths
|
||||
|
||||
|
||||
def test_mbart_dataset_truncation():
|
||||
tokenizer = MBartTokenizer.from_pretrained(MBART_TINY)
|
||||
tmp_dir = make_test_data_dir()
|
||||
max_len_source = max(len(tokenizer.encode(a)) for a in ARTICLES)
|
||||
max_len_target = max(len(tokenizer.encode(a)) for a in SUMMARIES)
|
||||
trunc = 4
|
||||
src_lang, tgt_lang = "ro_RO", "de_DE" # NOT WHAT IT WAS TRAINED ON
|
||||
train_dataset = MBartDataset(
|
||||
tokenizer,
|
||||
data_dir=tmp_dir,
|
||||
type_path="train",
|
||||
max_source_length=trunc,
|
||||
max_target_length=1000, # ignored
|
||||
src_lang=src_lang,
|
||||
tgt_lang=tgt_lang,
|
||||
)
|
||||
dataloader = DataLoader(train_dataset, batch_size=2, collate_fn=train_dataset.collate_fn)
|
||||
for batch in dataloader:
|
||||
assert isinstance(batch, dict)
|
||||
assert batch["attention_mask"].shape == batch["input_ids"].shape
|
||||
# show that articles were trimmed.
|
||||
assert batch["input_ids"].shape[1] == trunc
|
||||
# show that targets are the same len
|
||||
assert batch["decoder_input_ids"].shape[1] == trunc
|
||||
# check language codes in correct place
|
||||
assert batch["decoder_input_ids"][0, 0].item() == tokenizer.lang_code_to_id[tgt_lang]
|
||||
assert batch["decoder_input_ids"][0, -1].item() == tokenizer.eos_token_id
|
||||
assert batch["input_ids"][0, -2].item() == tokenizer.eos_token_id
|
||||
assert batch["input_ids"][0, -1].item() == tokenizer.lang_code_to_id[src_lang]
|
||||
|
||||
assert max_len_target > trunc # Truncated
|
||||
assert max_len_source > trunc
|
||||
break # No need to test every batch
|
||||
|
||||
|
||||
@pytest.mark.parametrize(["tok"], [pytest.param(T5_TINY), pytest.param(BART_TINY), param(MARIAN_TINY)])
|
||||
def test_summarization_dataset_truncation(tok):
|
||||
tokenizer = AutoTokenizer.from_pretrained(tok)
|
||||
tmp_dir = make_test_data_dir()
|
||||
max_len_source = max(len(tokenizer.encode(a)) for a in ARTICLES)
|
||||
max_len_target = max(len(tokenizer.encode(a)) for a in SUMMARIES)
|
||||
trunc_target = 4
|
||||
train_dataset = SummarizationDataset(
|
||||
tokenizer,
|
||||
data_dir=tmp_dir,
|
||||
type_path="train",
|
||||
max_source_length=20,
|
||||
max_target_length=trunc_target,
|
||||
tgt_lang="ro_RO",
|
||||
train_dataset = Seq2SeqDataset(
|
||||
tokenizer, data_dir=tmp_dir, type_path="train", max_source_length=20, max_target_length=trunc_target,
|
||||
)
|
||||
dataloader = DataLoader(train_dataset, batch_size=2, collate_fn=train_dataset.collate_fn)
|
||||
for batch in dataloader:
|
||||
@@ -275,3 +349,4 @@ def test_dataset(tok):
|
||||
# show that targets were truncated
|
||||
assert batch["decoder_input_ids"].shape[1] == trunc_target # Truncated
|
||||
assert max_len_target > trunc_target # Truncated
|
||||
break # No need to test every batch
|
||||
|
||||
@@ -4,18 +4,17 @@ export PYTHONPATH="../":"${PYTHONPATH}"
|
||||
python finetune.py \
|
||||
--learning_rate=3e-5 \
|
||||
--fp16 \
|
||||
--gpus 1 \
|
||||
--do_train \
|
||||
--do_predict \
|
||||
--val_check_interval 0.1 \
|
||||
--n_val 500 \
|
||||
--val_check_interval 0.25 \
|
||||
--adam_eps 1e-06 \
|
||||
--num_train_epochs 3 --src_lang en_XX --tgt_lang ro_RO \
|
||||
--freeze_encoder --freeze_embeds --data_dir $ENRO_DIR \
|
||||
--max_source_length=300 --max_target_length 300 --val_max_target_length=300 --test_max_target_length 300 \
|
||||
--num_train_epochs 6 --src_lang en_XX --tgt_lang ro_RO \
|
||||
--data_dir $ENRO_DIR \
|
||||
--max_source_length $MAX_LEN --max_target_length $MAX_LEN --val_max_target_length $MAX_LEN --test_max_target_length $MAX_LEN \
|
||||
--train_batch_size=$BS --eval_batch_size=$BS --gradient_accumulation_steps=$GAS \
|
||||
--model_name_or_path facebook/mbart-large-cc25 \
|
||||
--task translation \
|
||||
--warmup_steps 500 \
|
||||
--logger wandb --sortish_sampler \
|
||||
--freeze_embeds \
|
||||
--early_stopping_patience 4 \
|
||||
--model_name_or_path facebook/mbart-large-cc25 \
|
||||
$@
|
||||
|
||||
+120
-87
@@ -1,7 +1,10 @@
|
||||
import itertools
|
||||
import json
|
||||
import linecache
|
||||
import os
|
||||
import pickle
|
||||
import warnings
|
||||
from logging import getLogger
|
||||
from pathlib import Path
|
||||
from typing import Callable, Dict, Iterable, List
|
||||
|
||||
@@ -12,50 +15,43 @@ from rouge_score import rouge_scorer, scoring
|
||||
from sacrebleu import corpus_bleu
|
||||
from torch import nn
|
||||
from torch.utils.data import Dataset, Sampler
|
||||
from tqdm import tqdm
|
||||
|
||||
from transformers import BartTokenizer
|
||||
|
||||
|
||||
def encode_file(
|
||||
tokenizer,
|
||||
data_path,
|
||||
max_length,
|
||||
pad_to_max_length=True,
|
||||
return_tensors="pt",
|
||||
overwrite_cache=False,
|
||||
prefix="",
|
||||
tok_name="",
|
||||
):
|
||||
def label_smoothed_nll_loss(lprobs, target, epsilon, ignore_index=-100):
|
||||
"""From fairseq"""
|
||||
if target.dim() == lprobs.dim() - 1:
|
||||
target = target.unsqueeze(-1)
|
||||
nll_loss = -lprobs.gather(dim=-1, index=target)
|
||||
smooth_loss = -lprobs.sum(dim=-1, keepdim=True)
|
||||
if ignore_index is not None:
|
||||
pad_mask = target.eq(ignore_index)
|
||||
nll_loss.masked_fill_(pad_mask, 0.0)
|
||||
smooth_loss.masked_fill_(pad_mask, 0.0)
|
||||
bs = pad_mask.long().sum()
|
||||
else:
|
||||
nll_loss = nll_loss.squeeze(-1)
|
||||
smooth_loss = smooth_loss.squeeze(-1)
|
||||
bs = lprobs.shape[0]
|
||||
|
||||
nll_loss = nll_loss.sum() # mean()? Scared to break other math.
|
||||
smooth_loss = smooth_loss.sum()
|
||||
eps_i = epsilon / lprobs.size(-1)
|
||||
loss = (1.0 - epsilon) * nll_loss + eps_i * smooth_loss
|
||||
return loss / bs, nll_loss / bs
|
||||
|
||||
|
||||
def encode_line(tokenizer, line, max_length, pad_to_max_length=True, return_tensors="pt"):
|
||||
extra_kw = {"add_prefix_space": True} if isinstance(tokenizer, BartTokenizer) else {}
|
||||
cache_path = Path(f"{data_path}_{tok_name}{max_length}.pt")
|
||||
if not overwrite_cache and cache_path.exists():
|
||||
try:
|
||||
examples = torch.load(cache_path)
|
||||
assert isinstance(examples, list)
|
||||
return examples
|
||||
|
||||
except Exception:
|
||||
print(f"failed to load from {cache_path}, retokenizing {data_path}")
|
||||
data_path = Path(data_path)
|
||||
|
||||
lns = lmap(str.strip, data_path.open().readlines())
|
||||
lns = [prefix + text for text in lns]
|
||||
assert lns, f"found empty file at {data_path}"
|
||||
examples = []
|
||||
for text in tqdm(lns, desc=f"Tokenizing {data_path.name}"):
|
||||
tokenized = tokenizer(
|
||||
[text],
|
||||
max_length=max_length,
|
||||
padding="max_length" if pad_to_max_length else None,
|
||||
truncation=True,
|
||||
return_tensors=return_tensors,
|
||||
**extra_kw,
|
||||
)
|
||||
assert tokenized.input_ids.shape[1] == max_length
|
||||
examples.append(tokenized)
|
||||
torch.save(lmap(dict, examples), cache_path.open("wb"))
|
||||
return examples
|
||||
return tokenizer(
|
||||
[line],
|
||||
max_length=max_length,
|
||||
padding="max_length" if pad_to_max_length else None,
|
||||
truncation=True,
|
||||
return_tensors=return_tensors,
|
||||
**extra_kw,
|
||||
)
|
||||
|
||||
|
||||
def lmap(f: Callable, x: Iterable) -> List:
|
||||
@@ -79,80 +75,111 @@ def trim_batch(
|
||||
return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])
|
||||
|
||||
|
||||
class SummarizationDataset(Dataset):
|
||||
class Seq2SeqDataset(Dataset):
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer,
|
||||
data_dir,
|
||||
max_source_length,
|
||||
max_target_length,
|
||||
type_path="train",
|
||||
max_source_length=1024,
|
||||
max_target_length=56,
|
||||
n_obs=None,
|
||||
overwrite_cache=False,
|
||||
prefix="",
|
||||
src_lang=None,
|
||||
tgt_lang=None,
|
||||
prefix="",
|
||||
):
|
||||
super().__init__()
|
||||
# FIXME: the rstrip logic strips all the chars, it seems.
|
||||
tok_name = tokenizer.__class__.__name__.lower().rstrip("tokenizer")
|
||||
if hasattr(tokenizer, "set_lang") and src_lang is not None:
|
||||
tokenizer.set_lang(src_lang) # HACK: only applies to mbart
|
||||
self.source = encode_file(
|
||||
tokenizer,
|
||||
os.path.join(data_dir, type_path + ".source"),
|
||||
max_source_length,
|
||||
overwrite_cache=overwrite_cache,
|
||||
prefix=prefix,
|
||||
tok_name=tok_name,
|
||||
)
|
||||
tgt_path = os.path.join(data_dir, type_path + ".target")
|
||||
if hasattr(tokenizer, "set_lang"):
|
||||
assert tgt_lang is not None, "--tgt_lang must be passed to build a translation"
|
||||
tokenizer.set_lang(tgt_lang) # HACK: only applies to mbart
|
||||
self.target = encode_file(
|
||||
tokenizer, tgt_path, max_target_length, overwrite_cache=overwrite_cache, tok_name=tok_name
|
||||
)
|
||||
self.src_file = Path(data_dir).joinpath(type_path + ".source")
|
||||
self.tgt_file = Path(data_dir).joinpath(type_path + ".target")
|
||||
self.src_lens = self.get_char_lens(self.src_file)
|
||||
self.max_source_length = max_source_length
|
||||
self.max_target_length = max_target_length
|
||||
assert min(self.src_lens) > 0, f"found empty line in {self.src_file}"
|
||||
self.tokenizer = tokenizer
|
||||
self.prefix = prefix
|
||||
if n_obs is not None:
|
||||
self.source = self.source[:n_obs]
|
||||
self.target = self.target[:n_obs]
|
||||
self.pad_token_id = tokenizer.pad_token_id
|
||||
self.src_lens = self.src_lens[:n_obs]
|
||||
self.pad_token_id = self.tokenizer.pad_token_id
|
||||
self.src_lang = src_lang
|
||||
self.tgt_lang = tgt_lang
|
||||
|
||||
def __len__(self):
|
||||
return len(self.source)
|
||||
return len(self.src_lens)
|
||||
|
||||
def __getitem__(self, index):
|
||||
source_ids = self.source[index]["input_ids"].squeeze()
|
||||
target_ids = self.target[index]["input_ids"].squeeze()
|
||||
src_mask = self.source[index]["attention_mask"].squeeze()
|
||||
return {"input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids}
|
||||
def __getitem__(self, index) -> Dict[str, torch.Tensor]:
|
||||
index = index + 1 # linecache starts at 1
|
||||
source_line = self.prefix + linecache.getline(str(self.src_file), index).rstrip("\n")
|
||||
tgt_line = linecache.getline(str(self.tgt_file), index).rstrip("\n")
|
||||
assert source_line, f"empty source line for index {index}"
|
||||
assert tgt_line, f"empty tgt line for index {index}"
|
||||
source_inputs = encode_line(self.tokenizer, source_line, self.max_source_length)
|
||||
target_inputs = encode_line(self.tokenizer, tgt_line, self.max_target_length)
|
||||
|
||||
source_ids = source_inputs["input_ids"].squeeze()
|
||||
target_ids = target_inputs["input_ids"].squeeze()
|
||||
src_mask = source_inputs["attention_mask"].squeeze()
|
||||
return {
|
||||
"input_ids": source_ids,
|
||||
"attention_mask": src_mask,
|
||||
"decoder_input_ids": target_ids,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def trim_seq2seq_batch(batch, pad_token_id):
|
||||
def get_char_lens(data_file):
|
||||
return [len(x) for x in Path(data_file).open().readlines()]
|
||||
|
||||
@staticmethod
|
||||
def trim_seq2seq_batch(batch, pad_token_id) -> tuple:
|
||||
y = trim_batch(batch["decoder_input_ids"], pad_token_id)
|
||||
source_ids, source_mask = trim_batch(batch["input_ids"], pad_token_id, attention_mask=batch["attention_mask"])
|
||||
return source_ids, source_mask, y
|
||||
|
||||
def collate_fn(self, batch) -> dict:
|
||||
def collate_fn(self, batch) -> Dict[str, torch.Tensor]:
|
||||
input_ids = torch.stack([x["input_ids"] for x in batch])
|
||||
masks = torch.stack([x["attention_mask"] for x in batch])
|
||||
target_ids = torch.stack([x["decoder_input_ids"] for x in batch])
|
||||
pad_token_id = self.pad_token_id
|
||||
y = trim_batch(target_ids, pad_token_id)
|
||||
source_ids, source_mask = trim_batch(input_ids, pad_token_id, attention_mask=masks)
|
||||
batch = {"input_ids": source_ids, "attention_mask": source_mask, "decoder_input_ids": y}
|
||||
batch = {
|
||||
"input_ids": source_ids,
|
||||
"attention_mask": source_mask,
|
||||
"decoder_input_ids": y,
|
||||
}
|
||||
return batch
|
||||
|
||||
@property
|
||||
def src_lens(self): # Can delete?
|
||||
return lmap(len, self.source)
|
||||
|
||||
@property
|
||||
def tgt_lens(self):
|
||||
return lmap(len, self.target)
|
||||
|
||||
def make_sortish_sampler(self, batch_size):
|
||||
return SortishSampler(self.source, batch_size)
|
||||
return SortishSampler(self.src_lens, batch_size)
|
||||
|
||||
|
||||
class MBartDataset(Seq2SeqDataset):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
if self.max_source_length != self.max_target_length:
|
||||
warnings.warn(
|
||||
f"Mbart will ignore max_target_length = {self.max_target_length} and use {self.max_source_length} for both sides."
|
||||
)
|
||||
|
||||
def __getitem__(self, index) -> Dict[str, str]:
|
||||
index = index + 1 # linecache starts at 1
|
||||
source_line = self.prefix + linecache.getline(str(self.src_file), index).rstrip("\n")
|
||||
tgt_line = linecache.getline(str(self.tgt_file), index).rstrip("\n")
|
||||
assert source_line, f"empty source line for index {index}"
|
||||
assert tgt_line, f"empty tgt line for index {index}"
|
||||
return {
|
||||
"tgt_texts": tgt_line,
|
||||
"src_texts": source_line,
|
||||
}
|
||||
|
||||
def collate_fn(self, batch) -> Dict[str, torch.Tensor]:
|
||||
batch_encoding = self.tokenizer.prepare_translation_batch(
|
||||
[x["src_texts"] for x in batch],
|
||||
src_lang=self.src_lang,
|
||||
tgt_texts=[x["tgt_texts"] for x in batch],
|
||||
tgt_lang=self.tgt_lang,
|
||||
max_length=self.max_source_length,
|
||||
)
|
||||
return batch_encoding.data
|
||||
|
||||
|
||||
class SortishSampler(Sampler):
|
||||
@@ -162,7 +189,7 @@ class SortishSampler(Sampler):
|
||||
self.data, self.bs = data, batch_size
|
||||
|
||||
def key(self, i):
|
||||
return len(self.data[i])
|
||||
return self.data[i]
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.data)
|
||||
@@ -181,11 +208,17 @@ class SortishSampler(Sampler):
|
||||
return iter(sort_idx)
|
||||
|
||||
|
||||
logger = getLogger(__name__)
|
||||
|
||||
|
||||
def use_task_specific_params(model, task):
|
||||
# update config with summarization specific params
|
||||
"""Update config with summarization specific params."""
|
||||
task_specific_params = model.config.task_specific_params
|
||||
|
||||
if task_specific_params is not None:
|
||||
model.config.update(task_specific_params.get(task, {}))
|
||||
pars = task_specific_params.get(task, {})
|
||||
logger.info(f"using task specific params for {task}: {pars}")
|
||||
model.config.update(pars)
|
||||
|
||||
|
||||
def pickle_load(path):
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
# coding=utf-8
|
||||
# Copyright 2018 HuggingFace Inc..
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
import sys
|
||||
import unittest
|
||||
from time import time
|
||||
from unittest.mock import patch
|
||||
|
||||
from transformers.testing_utils import require_torch_tpu
|
||||
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
logger = logging.getLogger()
|
||||
|
||||
|
||||
def get_setup_file():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("-f")
|
||||
args = parser.parse_args()
|
||||
return args.f
|
||||
|
||||
|
||||
@require_torch_tpu
|
||||
class TorchXLAExamplesTests(unittest.TestCase):
|
||||
def test_run_glue(self):
|
||||
import xla_spawn
|
||||
|
||||
stream_handler = logging.StreamHandler(sys.stdout)
|
||||
logger.addHandler(stream_handler)
|
||||
|
||||
output_directory = "run_glue_output"
|
||||
|
||||
testargs = f"""
|
||||
text-classification/run_glue.py
|
||||
--num_cores=8
|
||||
text-classification/run_glue.py
|
||||
--do_train
|
||||
--do_eval
|
||||
--task_name=MRPC
|
||||
--data_dir=../glue_data/MRPC
|
||||
--cache_dir=./cache_dir
|
||||
--num_train_epochs=1
|
||||
--max_seq_length=128
|
||||
--learning_rate=3e-5
|
||||
--output_dir={output_directory}
|
||||
--overwrite_output_dir
|
||||
--logging_steps=5
|
||||
--save_steps=5
|
||||
--overwrite_cache
|
||||
--tpu_metrics_debug
|
||||
--model_name_or_path=bert-base-cased
|
||||
--per_device_train_batch_size=64
|
||||
--per_device_eval_batch_size=64
|
||||
--evaluate_during_training
|
||||
--overwrite_cache
|
||||
""".split()
|
||||
with patch.object(sys, "argv", testargs):
|
||||
start = time()
|
||||
xla_spawn.main()
|
||||
end = time()
|
||||
|
||||
result = {}
|
||||
with open(f"{output_directory}/eval_results_mrpc.txt") as f:
|
||||
lines = f.readlines()
|
||||
for line in lines:
|
||||
key, value = line.split(" = ")
|
||||
result[key] = float(value)
|
||||
|
||||
del result["eval_loss"]
|
||||
for value in result.values():
|
||||
# Assert that the model trains
|
||||
self.assertGreaterEqual(value, 0.70)
|
||||
|
||||
# Assert that the script takes less than 100 seconds to make sure it doesn't hang.
|
||||
self.assertLess(end - start, 100)
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
language:
|
||||
- bulgarian
|
||||
- czech
|
||||
- polish
|
||||
- russian
|
||||
- bg
|
||||
- cs
|
||||
- pl
|
||||
- ru
|
||||
---
|
||||
|
||||
# bert-base-bg-cs-pl-ru-cased
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
---
|
||||
language:
|
||||
- english
|
||||
language: en
|
||||
---
|
||||
|
||||
# bert-base-cased-conversational
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
language:
|
||||
- russian
|
||||
- ru
|
||||
---
|
||||
|
||||
# rubert-base-cased-conversational
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
language:
|
||||
- russian
|
||||
- ru
|
||||
---
|
||||
|
||||
# rubert-base-cased-sentence
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
language:
|
||||
- russian
|
||||
- ru
|
||||
---
|
||||
|
||||
# rubert-base-cased
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: swedish
|
||||
language: sv
|
||||
---
|
||||
|
||||
# Swedish BERT Models
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: swedish
|
||||
language: sv
|
||||
---
|
||||
|
||||
# Swedish BERT Models
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: swedish
|
||||
language: sv
|
||||
---
|
||||
|
||||
# Swedish BERT Models
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: italian
|
||||
language: it
|
||||
---
|
||||
|
||||
# GePpeTto GPT2 Model 🇮🇹
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: setswana
|
||||
language: tn
|
||||
---
|
||||
|
||||
# TswanaBert
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: zulu
|
||||
language: zu
|
||||
---
|
||||
|
||||
# zuBERTa
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: italian
|
||||
language: it
|
||||
---
|
||||
|
||||
# UmBERTo Commoncrawl Cased
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: italian
|
||||
language: it
|
||||
---
|
||||
|
||||
# UmBERTo Wikipedia Uncased
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
---
|
||||
language: he
|
||||
|
||||
thumbnail: https://avatars1.githubusercontent.com/u/3617152?norod.jpg
|
||||
widget:
|
||||
- text: "<|startoftext|>החוק השני של מועדון קרב הוא"
|
||||
- text: "<|startoftext|>ראש הממשלה בן גוריון"
|
||||
- text: "<|startoftext|>למידת מכונה (סרט)"
|
||||
- text: "<|startoftext|>מנשה פומפרניקל"
|
||||
- text: "<|startoftext|>אי שוויון "
|
||||
|
||||
license: mit
|
||||
---
|
||||
|
||||
|
||||
# hewiki-articles-distilGPT2py-il
|
||||
|
||||
## A tiny GPT2 model for generating Hebrew text
|
||||
|
||||
A distilGPT2 sized model. <br>
|
||||
Training data was hewiki-20200701-pages-articles-multistream.xml.bz2 from https://dumps.wikimedia.org/hewiki/20200701/ <br>
|
||||
XML has been converted to plain text using Wikipedia Extractor http://medialab.di.unipi.it/wiki/Wikipedia_Extractor <br>
|
||||
I then added <|startoftext|> and <|endoftext|> markers and deleted empty lines. <br>
|
||||
|
||||
#### How to use
|
||||
|
||||
```python
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from transformers import GPT2Tokenizer, GPT2LMHeadModel
|
||||
|
||||
tokenizer = GPT2Tokenizer.from_pretrained("Norod78/hewiki-articles-distilGPT2py-il")
|
||||
model = GPT2LMHeadModel.from_pretrained("Norod78/hewiki-articles-distilGPT2py-il").eval()
|
||||
|
||||
bos_token = tokenizer.bos_token #Beginning of sentace
|
||||
eos_token = tokenizer.eos_token #End of sentence
|
||||
|
||||
def generate_word(model, tokens_tensor, temperature=1.0):
|
||||
"""
|
||||
Sample a word given a tensor of tokens of previous words from a model. Given
|
||||
the words we have, sample a plausible word. Temperature is used for
|
||||
controlling randomness. If using temperature==0 we simply use a greedy arg max.
|
||||
Else, we sample from a multinomial distribution using a lower inverse
|
||||
temperature to allow for more randomness to escape repetitions.
|
||||
"""
|
||||
with torch.no_grad():
|
||||
outputs = model(tokens_tensor)
|
||||
predictions = outputs[0]
|
||||
if temperature>0:
|
||||
# Make the distribution more or less skewed based on the temperature
|
||||
predictions = outputs[0]/temperature
|
||||
# Sample from the distribution
|
||||
softmax = nn.Softmax(dim=0)
|
||||
predicted_index = torch.multinomial(softmax(predictions[0,-1,:]),1).item()
|
||||
# Simply take the arg-max of the distribution
|
||||
else:
|
||||
predicted_index = torch.argmax(predictions[0, -1, :]).item()
|
||||
# Decode the encoding to the corresponding word
|
||||
predicted_text = tokenizer.decode([predicted_index])
|
||||
return predicted_text
|
||||
|
||||
def generate_sentence(model, tokenizer, initial_text, temperature=1.0):
|
||||
""" Generate a sentence given some initial text using a model and a tokenizer.
|
||||
Returns the new sentence. """
|
||||
|
||||
# Encode a text inputs
|
||||
text = ""
|
||||
sentence = text
|
||||
|
||||
# We avoid an infinite loop by setting a maximum range
|
||||
for i in range(0,84):
|
||||
indexed_tokens = tokenizer.encode(initial_text + text)
|
||||
|
||||
# Convert indexed tokens in a PyTorch tensor
|
||||
tokens_tensor = torch.tensor([indexed_tokens])
|
||||
|
||||
new_word = generate_word(model, tokens_tensor, temperature=temperature)
|
||||
|
||||
# Here the temperature is slowly decreased with each generated word,
|
||||
# this ensures that the sentence (ending) makes more sense.
|
||||
# We don't decrease to a temperature of 0.0 to leave some randomness in.
|
||||
if temperature<(1-0.008):
|
||||
temperature += 0.008
|
||||
else:
|
||||
temperature = 0.996
|
||||
|
||||
text = text+new_word
|
||||
|
||||
# Stop generating new words when we have reached the end of the line or the poem
|
||||
if eos_token in new_word:
|
||||
# returns new sentence and whether poem is done
|
||||
return (text.replace(eos_token,"").strip(), True)
|
||||
elif '/' in new_word:
|
||||
return (text.strip(), False)
|
||||
elif bos_token in new_word:
|
||||
return (text.replace(bos_token,"").strip(), False)
|
||||
|
||||
return (text, True)
|
||||
|
||||
for output_num in range(1,5):
|
||||
init_text = "בוקר טוב"
|
||||
text = bos_token + init_text
|
||||
for i in range(0,84):
|
||||
sentence = generate_sentence(model, tokenizer, text, temperature=0.9)
|
||||
text = init_text + sentence[0]
|
||||
print(text)
|
||||
if (sentence[1] == True):
|
||||
break
|
||||
```
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: ukrainian
|
||||
language: uk
|
||||
---
|
||||
|
||||
Note: **default code snippet above won't work** because we are using `AlbertTokenizer` with `GPT2LMHeadModel`, see [issue](https://github.com/huggingface/transformers/issues/4285).
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: finnish
|
||||
language: fi
|
||||
---
|
||||
|
||||
## Quickstart
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: finnish
|
||||
language: fi
|
||||
---
|
||||
|
||||
## Quickstart
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: norwegian
|
||||
language: no
|
||||
thumbnail: https://i.imgur.com/QqSEC5I.png
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
language: "en"
|
||||
tags:
|
||||
- exbert
|
||||
- commonsense
|
||||
- semeval2020
|
||||
- comve
|
||||
license: "mit"
|
||||
datasets:
|
||||
- ComVE
|
||||
metrics:
|
||||
- bleu
|
||||
widget:
|
||||
- text: "Chicken can swim in water. <|continue|>"
|
||||
---
|
||||
|
||||
# ComVE-distilgpt2
|
||||
|
||||
## Model description
|
||||
|
||||
Finetuned model on Commonsense Validation and Explanation (ComVE) dataset introduced in [SemEval2020 Task4](https://competitions.codalab.org/competitions/21080) using a causal language modeling (CLM) objective.
|
||||
The model is able to generate a reason why a given natural language statement is against commonsense.
|
||||
|
||||
## Intended uses & limitations
|
||||
|
||||
You can use the raw model for text generation to generate reasons why natural language statements are against commonsense.
|
||||
|
||||
#### How to use
|
||||
|
||||
You can use this model directly to generate reasons why the given statement is against commonsense using [`generate.sh`](https://github.com/AliOsm/SemEval2020-Task4-ComVE/tree/master/TaskC-Generation) script.
|
||||
|
||||
*Note:* make sure that you are using version `2.4.1` of `transformers` package. Newer versions has some issue in text generation and the model repeats the last token generated again and again.
|
||||
|
||||
#### Limitations and bias
|
||||
|
||||
The model biased to negate the entered sentence usually instead of producing a factual reason.
|
||||
|
||||
## Training data
|
||||
|
||||
The model is initialized from the [distilgpt2](https://github.com/huggingface/transformers/blob/master/model_cards/distilgpt2-README.md) model and finetuned using [ComVE](https://github.com/wangcunxiang/SemEval2020-Task4-Commonsense-Validation-and-Explanation) dataset which contains 10K against commonsense sentences, each of them is paired with three reference reasons.
|
||||
|
||||
## Training procedure
|
||||
|
||||
Each natural language statement that against commonsense is concatenated with its reference reason with `<|continue|>` as a separator, then the model finetuned using CLM objective.
|
||||
The model trained on Nvidia Tesla P100 GPU from Google Colab platform with 5e-5 learning rate, 15 epochs, 128 maximum sequence length and 64 batch size.
|
||||
|
||||
<center>
|
||||
<img src="https://i.imgur.com/xKbrwBC.png">
|
||||
</center>
|
||||
|
||||
## Eval results
|
||||
|
||||
The model achieved 13.7582/13.8026 BLEU scores on SemEval2020 Task4: Commonsense Validation and Explanation development and testing dataset.
|
||||
|
||||
### BibTeX entry and citation info
|
||||
|
||||
```bibtex
|
||||
@article{fadel2020justers,
|
||||
title={JUSTers at SemEval-2020 Task 4: Evaluating Transformer Models Against Commonsense Validation and Explanation},
|
||||
author={Fadel, Ali and Al-Ayyoub, Mahmoud and Cambria, Erik},
|
||||
year={2020}
|
||||
}
|
||||
```
|
||||
|
||||
<a href="https://huggingface.co/exbert/?model=aliosm/ComVE-distilgpt2">
|
||||
<img width="300px" src="https://hf-dinosaur.huggingface.co/exbert/button.png">
|
||||
</a>
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
language: "en"
|
||||
tags:
|
||||
- gpt2
|
||||
- exbert
|
||||
- commonsense
|
||||
- semeval2020
|
||||
- comve
|
||||
license: "mit"
|
||||
datasets:
|
||||
- https://github.com/wangcunxiang/SemEval2020-Task4-Commonsense-Validation-and-Explanation
|
||||
metrics:
|
||||
- bleu
|
||||
widget:
|
||||
- text: "Chicken can swim in water. <|continue|>"
|
||||
---
|
||||
|
||||
# ComVE-gpt2-large
|
||||
|
||||
## Model description
|
||||
|
||||
Finetuned model on Commonsense Validation and Explanation (ComVE) dataset introduced in [SemEval2020 Task4](https://competitions.codalab.org/competitions/21080) using a causal language modeling (CLM) objective.
|
||||
The model is able to generate a reason why a given natural language statement is against commonsense.
|
||||
|
||||
## Intended uses & limitations
|
||||
|
||||
You can use the raw model for text generation to generate reasons why natural language statements are against commonsense.
|
||||
|
||||
#### How to use
|
||||
|
||||
You can use this model directly to generate reasons why the given statement is against commonsense using [`generate.sh`](https://github.com/AliOsm/SemEval2020-Task4-ComVE/tree/master/TaskC-Generation) script.
|
||||
|
||||
*Note:* make sure that you are using version `2.4.1` of `transformers` package. Newer versions has some issue in text generation and the model repeats the last token generated again and again.
|
||||
|
||||
#### Limitations and bias
|
||||
|
||||
The model biased to negate the entered sentence usually instead of producing a factual reason.
|
||||
|
||||
## Training data
|
||||
|
||||
The model is initialized from the [gpt2-large](https://github.com/huggingface/transformers/blob/master/model_cards/gpt2-README.md) model and finetuned using [ComVE](https://github.com/wangcunxiang/SemEval2020-Task4-Commonsense-Validation-and-Explanation) dataset which contains 10K against commonsense sentences, each of them is paired with three reference reasons.
|
||||
|
||||
## Training procedure
|
||||
|
||||
Each natural language statement that against commonsense is concatenated with its reference reason with `<|conteniue|>` as a separator, then the model finetuned using CLM objective.
|
||||
The model trained on Nvidia Tesla P100 GPU from Google Colab platform with 5e-5 learning rate, 5 epochs, 128 maximum sequence length and 64 batch size.
|
||||
|
||||
<center>
|
||||
<img src="https://i.imgur.com/xKbrwBC.png">
|
||||
</center>
|
||||
|
||||
## Eval results
|
||||
|
||||
The model achieved 16.5110/15.9299 BLEU scores on SemEval2020 Task4: Commonsense Validation and Explanation development and testing dataset.
|
||||
|
||||
### BibTeX entry and citation info
|
||||
|
||||
```bibtex
|
||||
@article{fadel2020justers,
|
||||
title={JUSTers at SemEval-2020 Task 4: Evaluating Transformer Models Against Commonsense Validation and Explanation},
|
||||
author={Fadel, Ali and Al-Ayyoub, Mahmoud and Cambria, Erik},
|
||||
year={2020}
|
||||
}
|
||||
```
|
||||
|
||||
<a href="https://huggingface.co/exbert/?model=aliosm/ComVE-gpt2-large">
|
||||
<img width="300px" src="https://hf-dinosaur.huggingface.co/exbert/button.png">
|
||||
</a>
|
||||
@@ -0,0 +1,82 @@
|
||||
---
|
||||
language: "en"
|
||||
tags:
|
||||
- gpt2
|
||||
- exbert
|
||||
- commonsense
|
||||
- semeval2020
|
||||
- comve
|
||||
license: "mit"
|
||||
datasets:
|
||||
- ComVE
|
||||
metrics:
|
||||
- bleu
|
||||
widget:
|
||||
- text: "Chicken can swim in water. <|continue|>"
|
||||
---
|
||||
|
||||
# ComVE-gpt2-medium
|
||||
|
||||
## Model description
|
||||
|
||||
Finetuned model on Commonsense Validation and Explanation (ComVE) dataset introduced in [SemEval2020 Task4](https://competitions.codalab.org/competitions/21080) using a causal language modeling (CLM) objective.
|
||||
The model is able to generate a reason why a given natural language statement is against commonsense.
|
||||
|
||||
## Intended uses & limitations
|
||||
|
||||
You can use the raw model for text generation to generate reasons why natural language statements are against commonsense.
|
||||
|
||||
#### How to use
|
||||
|
||||
You can use this model directly to generate reasons why the given statement is against commonsense using [`generate.sh`](https://github.com/AliOsm/SemEval2020-Task4-ComVE/tree/master/TaskC-Generation) script.
|
||||
|
||||
*Note:* make sure that you are using version `2.4.1` of `transformers` package. Newer versions has some issue in text generation and the model repeats the last token generated again and again.
|
||||
|
||||
#### Limitations and bias
|
||||
|
||||
The model biased to negate the entered sentence usually instead of producing a factual reason.
|
||||
|
||||
## Training data
|
||||
|
||||
The model is initialized from the [gpt2-medium](https://github.com/huggingface/transformers/blob/master/model_cards/gpt2-README.md) model and finetuned using [ComVE](https://github.com/wangcunxiang/SemEval2020-Task4-Commonsense-Validation-and-Explanation) dataset which contains 10K against commonsense sentences, each of them is paired with three reference reasons.
|
||||
|
||||
## Training procedure
|
||||
|
||||
Each natural language statement that against commonsense is concatenated with its reference reason with `<|continue|>` as a separator, then the model finetuned using CLM objective.
|
||||
The model trained on Nvidia Tesla P100 GPU from Google Colab platform with 5e-5 learning rate, 5 epochs, 128 maximum sequence length and 64 batch size.
|
||||
|
||||
<center>
|
||||
<img src="https://i.imgur.com/xKbrwBC.png">
|
||||
</center>
|
||||
|
||||
## Eval results
|
||||
|
||||
The model achieved fifth place with 16.7153/16.1187 BLEU scores and third place with 1.94 Human Evaluation score on SemEval2020 Task4: Commonsense Validation and Explanation development and testing dataset.
|
||||
|
||||
These are some examples generated by the model:
|
||||
| Against Commonsense Statement | Generated Reason |
|
||||
|:-----------------------------------------------------:|:--------------------------------------------:|
|
||||
| Chicken can swim in water. | Chicken can't swim. |
|
||||
| shoes can fly | Shoes are not able to fly. |
|
||||
| Chocolate can be used to make a coffee pot | Chocolate is not used to make coffee pots. |
|
||||
| you can also buy tickets online with an identity card | You can't buy tickets with an identity card. |
|
||||
| a ball is square and can roll | A ball is round and cannot roll. |
|
||||
| You can use detergent to dye your hair. | Detergent is used to wash clothes. |
|
||||
| you can eat mercury | mercury is poisonous |
|
||||
| A gardener can follow a suspect | gardener is not a police officer |
|
||||
| cars can float in the ocean just like a boat | Cars are too heavy to float in the ocean. |
|
||||
| I am going to work so I can lose money. | Working is not a way to lose money. |
|
||||
|
||||
### BibTeX entry and citation info
|
||||
|
||||
```bibtex
|
||||
@article{fadel2020justers,
|
||||
title={JUSTers at SemEval-2020 Task 4: Evaluating Transformer Models Against Commonsense Validation and Explanation},
|
||||
author={Fadel, Ali and Al-Ayyoub, Mahmoud and Cambria, Erik},
|
||||
year={2020}
|
||||
}
|
||||
```
|
||||
|
||||
<a href="https://huggingface.co/exbert/?model=aliosm/ComVE-gpt2-medium">
|
||||
<img width="300px" src="https://hf-dinosaur.huggingface.co/exbert/button.png">
|
||||
</a>
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
language: "en"
|
||||
tags:
|
||||
- exbert
|
||||
- commonsense
|
||||
- semeval2020
|
||||
- comve
|
||||
license: "mit"
|
||||
datasets:
|
||||
- ComVE
|
||||
metrics:
|
||||
- bleu
|
||||
widget:
|
||||
- text: "Chicken can swim in water. <|continue|>"
|
||||
---
|
||||
|
||||
# ComVE-gpt2
|
||||
|
||||
## Model description
|
||||
|
||||
Finetuned model on Commonsense Validation and Explanation (ComVE) dataset introduced in [SemEval2020 Task4](https://competitions.codalab.org/competitions/21080) using a causal language modeling (CLM) objective.
|
||||
The model is able to generate a reason why a given natural language statement is against commonsense.
|
||||
|
||||
## Intended uses & limitations
|
||||
|
||||
You can use the raw model for text generation to generate reasons why natural language statements are against commonsense.
|
||||
|
||||
#### How to use
|
||||
|
||||
You can use this model directly to generate reasons why the given statement is against commonsense using [`generate.sh`](https://github.com/AliOsm/SemEval2020-Task4-ComVE/tree/master/TaskC-Generation) script.
|
||||
|
||||
*Note:* make sure that you are using version `2.4.1` of `transformers` package. Newer versions has some issue in text generation and the model repeats the last token generated again and again.
|
||||
|
||||
#### Limitations and bias
|
||||
|
||||
The model biased to negate the entered sentence usually instead of producing a factual reason.
|
||||
|
||||
## Training data
|
||||
|
||||
The model is initialized from the [gpt2](https://github.com/huggingface/transformers/blob/master/model_cards/gpt2-README.md) model and finetuned using [ComVE](https://github.com/wangcunxiang/SemEval2020-Task4-Commonsense-Validation-and-Explanation) dataset which contains 10K against commonsense sentences, each of them is paired with three reference reasons.
|
||||
|
||||
## Training procedure
|
||||
|
||||
Each natural language statement that against commonsense is concatenated with its reference reason with `<|continue|>` as a separator, then the model finetuned using CLM objective.
|
||||
The model trained on Nvidia Tesla P100 GPU from Google Colab platform with 5e-5 learning rate, 5 epochs, 128 maximum sequence length and 64 batch size.
|
||||
|
||||
<center>
|
||||
<img src="https://i.imgur.com/xKbrwBC.png">
|
||||
</center>
|
||||
|
||||
## Eval results
|
||||
|
||||
The model achieved 14.0547/13.6534 BLEU scores on SemEval2020 Task4: Commonsense Validation and Explanation development and testing dataset.
|
||||
|
||||
### BibTeX entry and citation info
|
||||
|
||||
```bibtex
|
||||
@article{fadel2020justers,
|
||||
title={JUSTers at SemEval-2020 Task 4: Evaluating Transformer Models Against Commonsense Validation and Explanation},
|
||||
author={Fadel, Ali and Al-Ayyoub, Mahmoud and Cambria, Erik},
|
||||
year={2020}
|
||||
}
|
||||
```
|
||||
|
||||
<a href="https://huggingface.co/exbert/?model=aliosm/ComVE-gpt2">
|
||||
<img width="300px" src="https://hf-dinosaur.huggingface.co/exbert/button.png">
|
||||
</a>
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: polish
|
||||
language: pl
|
||||
---
|
||||
|
||||
# HerBERT tokenizer
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: polish
|
||||
language: pl
|
||||
---
|
||||
|
||||
# HerBERT
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: arabic
|
||||
language: ar
|
||||
---
|
||||
|
||||
# Arabic BERT Model
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: arabic
|
||||
language: ar
|
||||
---
|
||||
|
||||
# Arabic BERT Large Model
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: arabic
|
||||
language: ar
|
||||
---
|
||||
|
||||
# Arabic BERT Medium Model
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: arabic
|
||||
language: ar
|
||||
datasets:
|
||||
- oscar
|
||||
- wikipedia
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: arabic
|
||||
language: ar
|
||||
---
|
||||
|
||||
# AraBERT : Pre-training BERT for Arabic Language Understanding
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: arabic
|
||||
language: ar
|
||||
---
|
||||
|
||||
# AraBERT : Pre-training BERT for Arabic Language Understanding
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
language: ar
|
||||
thumbnail: https://raw.githubusercontent.com/mawdoo3/Multi-dialect-Arabic-BERT/master/multidialct_arabic_bert.png
|
||||
datasets:
|
||||
- nadi
|
||||
---
|
||||
# Multi-dialect-Arabic-BERT
|
||||
This is a repository of Multi-dialect Arabic BERT model.
|
||||
|
||||
By [Mawdoo3-AI](https://ai.mawdoo3.com/).
|
||||
|
||||
<p align="center">
|
||||
<br>
|
||||
<img src="https://raw.githubusercontent.com/mawdoo3/Multi-dialect-Arabic-BERT/master/multidialct_arabic_bert.png" alt="Background reference: http://www.qfi.org/wp-content/uploads/2018/02/Qfi_Infographic_Mother-Language_Final.pdf" width="500"/>
|
||||
<br>
|
||||
<p>
|
||||
|
||||
|
||||
|
||||
### About our Multi-dialect-Arabic-BERT model
|
||||
Instead of training the Multi-dialect Arabic BERT model from scratch, we initialized the weights of the model using [Arabic-BERT](https://github.com/alisafaya/Arabic-BERT) and trained it on 10M arabic tweets from the unlabled data of [The Nuanced Arabic Dialect Identification (NADI) shared task](https://sites.google.com/view/nadi-shared-task).
|
||||
|
||||
### To cite this work
|
||||
|
||||
```
|
||||
@misc{talafha2020multidialect,
|
||||
title={Multi-Dialect Arabic BERT for Country-Level Dialect Identification},
|
||||
author={Bashar Talafha and Mohammad Ali and Muhy Eddin Za'ter and Haitham Seelawi and Ibraheem Tuffaha and Mostafa Samir and Wael Farhan and Hussein T. Al-Natsheh},
|
||||
year={2020},
|
||||
eprint={2007.05612},
|
||||
archivePrefix={arXiv},
|
||||
primaryClass={cs.CL}
|
||||
}
|
||||
```
|
||||
|
||||
### Usage
|
||||
The model weights can be loaded using `transformers` library by HuggingFace.
|
||||
|
||||
```python
|
||||
from transformers import AutoTokenizer, AutoModel
|
||||
|
||||
tokenizer = AutoTokenizer.from_pretrained("bashar-talafha/multi-dialect-bert-base-arabic")
|
||||
model = AutoModel.from_pretrained("bashar-talafha/multi-dialect-bert-base-arabic")
|
||||
```
|
||||
|
||||
Example using `pipeline`:
|
||||
|
||||
```python
|
||||
from transformers import pipeline
|
||||
|
||||
fill_mask = pipeline(
|
||||
"fill-mask",
|
||||
model="bashar-talafha/multi-dialect-bert-base-arabic ",
|
||||
tokenizer="bashar-talafha/multi-dialect-bert-base-arabic "
|
||||
)
|
||||
|
||||
fill_mask(" سافر الرحالة من مطار [MASK] ")
|
||||
```
|
||||
```
|
||||
[{'sequence': '[CLS] سافر الرحالة من مطار الكويت [SEP]', 'score': 0.08296813815832138, 'token': 3226},
|
||||
{'sequence': '[CLS] سافر الرحالة من مطار دبي [SEP]', 'score': 0.05123933032155037, 'token': 4747},
|
||||
{'sequence': '[CLS] سافر الرحالة من مطار مسقط [SEP]', 'score': 0.046838656067848206, 'token': 13205},
|
||||
{'sequence': '[CLS] سافر الرحالة من مطار القاهرة [SEP]', 'score': 0.03234650194644928, 'token': 4003},
|
||||
{'sequence': '[CLS] سافر الرحالة من مطار الرياض [SEP]', 'score': 0.02606341242790222, 'token': 2200}]
|
||||
```
|
||||
### Repository
|
||||
Please check the [original repository](https://github.com/mawdoo3/Multi-dialect-Arabic-BERT) for more information.
|
||||
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
---
|
||||
language: mn
|
||||
---
|
||||
|
||||
# ALBERT-Mongolian
|
||||
[pretraining repo link](https://github.com/bayartsogt-ya/albert-mongolian)
|
||||
## Model description
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: english
|
||||
language: en
|
||||
tags:
|
||||
- exbert
|
||||
license: apache-2.0
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
---
|
||||
language: chinese
|
||||
language: zh
|
||||
---
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: german
|
||||
language: de
|
||||
thumbnail: https://static.tildacdn.com/tild6438-3730-4164-b266-613634323466/german_bert.png
|
||||
tags:
|
||||
- exbert
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
---
|
||||
language: german
|
||||
language: de
|
||||
license: mit
|
||||
---
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
---
|
||||
language: german
|
||||
language: de
|
||||
license: mit
|
||||
---
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: english
|
||||
language: en
|
||||
license: apache-2.0
|
||||
datasets:
|
||||
- wikipedia
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: english
|
||||
language: en
|
||||
tags:
|
||||
- exbert
|
||||
license: apache-2.0
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: french
|
||||
language: fr
|
||||
|
||||
license: mit
|
||||
---
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: french
|
||||
language: fr
|
||||
---
|
||||
|
||||
# CamemBERT: a Tasty French Language Model
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: french
|
||||
language: fr
|
||||
---
|
||||
|
||||
# CamemBERT: a Tasty French Language Model
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: french
|
||||
language: fr
|
||||
---
|
||||
|
||||
# CamemBERT: a Tasty French Language Model
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: french
|
||||
language: fr
|
||||
---
|
||||
|
||||
# CamemBERT: a Tasty French Language Model
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: french
|
||||
language: fr
|
||||
---
|
||||
|
||||
# CamemBERT: a Tasty French Language Model
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
## RuDR-BERT
|
||||
|
||||
RuDR-BERT - Multilingual, Cased, which pretrained on the raw part of the RuDReC corpus (1.4M reviews). Pre-training was based on the [original BERT code](https://github.com/google-research/bert) provided by Google. In particular, Multi-BERT was for used for initialization; vocabulary of Russian subtokens and parameters are the same as in Multi-BERT. Training details are described in our paper. \
|
||||
link: https://yadi.sk/d/-PTn0xhk1PqvgQ
|
||||
|
||||
|
||||
## Citing & Authors
|
||||
|
||||
If you find this repository helpful, feel free to cite our publication:
|
||||
|
||||
[1] https://arxiv.org/abs/2004.03659
|
||||
```
|
||||
@misc{tutubalina2020russian,
|
||||
title={The Russian Drug Reaction Corpus and Neural Models for Drug Reactions and Effectiveness Detection in User Reviews},
|
||||
author={Elena Tutubalina and Ilseyar Alimova and Zulfat Miftahutdinov and Andrey Sakhovskiy and Valentin Malykh and Sergey Nikolenko},
|
||||
year={2020},
|
||||
eprint={2004.03659},
|
||||
archivePrefix={arXiv},
|
||||
primaryClass={cs.CL}
|
||||
}
|
||||
```
|
||||
[2] Tutubalina, EV and Miftahutdinov, Z Sh and Nugmanov, RI and Madzhidov, TI and Nikolenko, SI and Alimova, IS and Tropsha, AE Using semantic analysis of texts for the identification of drugs with similar therapeutic effects.
|
||||
[link to paper](https://www.researchgate.net/profile/Elena_Tutubalina/publication/323751823_Using_semantic_analysis_of_texts_for_the_identification_of_drugs_with_similar_therapeutic_effects/links/5bf7cfc3299bf1a0202cbc1f/Using-semantic-analysis-of-texts-for-the-identification-of-drugs-with-similar-therapeutic-effects.pdf)
|
||||
```
|
||||
@article{tutubalina2017using,
|
||||
title={Using semantic analysis of texts for the identification of drugs with similar therapeutic effects},
|
||||
author={Tutubalina, EV and Miftahutdinov, Z Sh and Nugmanov, RI and Madzhidov, TI and Nikolenko, SI and Alimova, IS and Tropsha, AE},
|
||||
journal={Russian Chemical Bulletin},
|
||||
volume={66},
|
||||
number={11},
|
||||
pages={2180--2189},
|
||||
year={2017},
|
||||
publisher={Springer}
|
||||
}
|
||||
```
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: chinese
|
||||
language: zh
|
||||
---
|
||||
|
||||
## albert_chinese_small
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: chinese
|
||||
language: zh
|
||||
---
|
||||
|
||||
## albert_chinese_tiny
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: chinese
|
||||
language: zh
|
||||
---
|
||||
|
||||
# Introduction
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: chinese
|
||||
language: zh
|
||||
---
|
||||
|
||||
## roberta_chinese_base
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: chinese
|
||||
language: zh
|
||||
---
|
||||
|
||||
## roberta_chinese_large
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
language: chinese
|
||||
language: zh
|
||||
---
|
||||
|
||||
## xlnet_chinese_large
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user