Skip to content

[WIP] Squad refactor - #1984

Merged
thomwolf merged 27 commits into
masterfrom
squad-refactor
Dec 10, 2019
Merged

thomwolf merged 27 commits into
masterfrom
squad-refactor

Conversation

@LysandreJik

@LysandreJik LysandreJik commented Nov 28, 2019 •

Copy link
Copy Markdown
Member

This PR aims to refactor SQuAD to make it usable with all models with question answering heads, and without having to build the entire tokenization pipeline as it is currently done.

  • It is based on processors that manage data, similarly to the GLUE processors. The two new processors are SquadV1Processor and SquadV2Processor. They'll probably be merged into a single SquadProcessor as the difference between the two versions is minimal.
  • It leverages powerful abstractions made for the run_glue refactor a few months ago that greatly simplified the tokenization pipeline
  • It can be interfaced with the package tensorflow_datasets.
  • It better respects the library-wide naming, with attention_mask instead of input_mask and token_type_ids instead of segment_ids, among others.
  • Introduces padding to encode and encode_plus, alongside tests.

It is still a work on progress but some aspects of it are working.

Left to do

  • Add the processors to __init__.py
  • Patch the evaluation so that it leverages the current interface
  • Patch the evaluation so that it may work with tfds
  • Modify the run arguments to reflect the changes
  • Remove the only_first argument which would only be used for testing
  • Update tests running the run_squad.py script
  • Include the padding location in the tokenizers and reflect the changes in the feature converter
  • Test that all current models can train and evaluate (BERT, RoBERTa, XLNet, XLM)
  • Add the last models (DistilBERT, ALBERT, ...)
  • Return datasets (maybe only pytorch TensorDataset for now)
  • Documentation
  • Short examples showcasing the simply usage in the processors section.
  • Patch the evaluation for impossible questions

Running sample

Here's the major difference from the user's perspective. Initially, to obtain the examples which were then converted to features, the user had to do as follows (taken from the current run_squad.py), which only works for BERT/XLNet/DistilBERT/ALBERT:

examples = read_squad_examples(
    input_file=input_file,
    is_training=not evaluate,
    version_2_with_negative=args.version_2_with_negative
)
     
features = convert_examples_to_features(
    examples=examples,
    tokenizer=tokenizer,
    max_seq_length=args.max_seq_length,
    doc_stride=args.doc_stride,
    max_query_length=args.max_query_length,
    is_training=not evaluate,
    cls_token_segment_id=2 if args.model_type in ['xlnet'] else 0,
    pad_token_segment_id=3 if args.model_type in ['xlnet'] else 0,
    cls_token_at_end=True if args.model_type in ['xlnet'] else False,
    sequence_a_is_doc=True if args.model_type in ['xlnet'] else False
)

In order to obtain the exact same results, the user now has to do as follows, which will be completely model independant once the sequence_a_is_doc is integrated in our sequence pair tokenization methods:

processor = SquadV1Processor()
examples = processor.get_dev_examples("examples/squad") if evaluate else processor.get_train_examples("examples/squad")
features = squad_convert_examples_to_features(
    examples=examples,
    tokenizer=tokenizer,
    max_seq_length=args.max_seq_length,
    doc_stride=args.doc_stride,
    max_query_length=args.max_query_length,
    is_training=not evaluate,
    sequence_a_is_doc=True if args.model_type in ['xlnet'] else False
)

The same can be done by using TFDS instead, removing the need to specify a file. The two initial lines now become:

tfds_examples = tensorflow_datasets.load("squad")["validation"] if evaluate else tensorflow_datasets.load("squad")["train"] 
examples = SquadV1Processor().get_examples_from_dataset(tfds_examples)

Comment thread transformers/tokenization_utils.py Outdated
- 'only_second': Only truncate the second sequence
- 'do_not_truncate': Does not truncate (raise an error if the input sequence is longer than max_length)
padding_strategy: if set to a strategy, the returned sequences will be padded according to the model's
padding index, up to their max length. If no max length is specified, no padding is done.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the most general case for the user, we may want to allow passing a batch of sequence and just have them padded to the maximal sequence length in the batch (or probably the min between the model's max length and the maximal sequence length in the batch).
Should we prepare for that?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel like we should do padding up to self.max_length if padding is asked even when no explicit max_length is provided to the method.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regarding the first comment, we don't currently manage sequence batching so it would require implementing an encode_batch method or similar beforehand, wouldn't it? As of right now, it shouldn't be too hard for the user to identify the longer sequence in its batches, but it would be a good idea to ease the process of tokenizing batches.

Totally agree with your second comment, this makes sense!

Comment thread transformers/tokenization_utils.py Outdated

@property
def pad_token_type_id(self):
""" Id of the padding token in the vocabulary. Log an error if used while not having been set. """

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can remove Log an error if used while not having been set I think

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very true!

@thomwolf thomwolf left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's really a lot cleaner, I like it very much.
Great work @LysandreJik!

Comment thread docs/source/main_classes/processors.rst Outdated

An example using these processors is given in the
`run_glue.py <https://github.com/huggingface/pytorch-transformers/blob/master/examples/run_glue.py>`__ script. No newline at end of file
`run_glue.py <https://github.com/huggingface/pytorch-transformers/blob/master/examples/run_glue.py>`__ script.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
`run_glue.py <https://github.com/huggingface/pytorch-transformers/blob/master/examples/run_glue.py>`__ script.
`run_glue.py <https://github.com/huggingface/transformers/blob/master/examples/run_glue.py>`__ script.

Comment thread docs/source/main_classes/processors.rst Outdated


Another example using these processors is given in the
`run_squad.py <https://github.com/huggingface/pytorch-transformers/blob/master/examples/run_squad.py>`__ script. No newline at end of file

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
`run_squad.py <https://github.com/huggingface/pytorch-transformers/blob/master/examples/run_squad.py>`__ script.
`run_squad.py <https://github.com/huggingface/transformers/blob/master/examples/run_squad.py>`__ script.

Improve global visibility on the run_squad script, remove unused files and fixes related to XLNet.
@codecov-io

codecov-io commented Dec 5, 2019 •

Copy link
Copy Markdown

Codecov Report

Merging #1984 into master will decrease coverage by 3.11%.
The diff coverage is 17.42%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #1984      +/-   ##
==========================================
- Coverage   82.67%   79.56%   -3.12%     
==========================================
  Files         111      113       +2     
  Lines       16162    16969     +807     
==========================================
+ Hits        13362    13501     +139     
- Misses       2800     3468     +668
Impacted Files Coverage Δ
transformers/data/metrics/squad_metrics.py 0% <0%> (ø)
transformers/tests/tokenization_tests_commons.py 100% <100%> (ø) ⬆️
transformers/data/__init__.py 100% <100%> (ø) ⬆️
transformers/tokenization_xlnet.py 90.4% <100%> (+0.15%) ⬆️
transformers/data/processors/__init__.py 100% <100%> (ø) ⬆️
transformers/tokenization_utils.py 91.02% <100%> (+0.55%) ⬆️
transformers/data/processors/squad.py 14.7% <14.7%> (ø)

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 0cb1638...2a4ef09. Read the comment docs.

@LysandreJik

LysandreJik commented Dec 5, 2019 •

Copy link
Copy Markdown
Member Author

Should be about ready to merge now. I'm reproducing the results paper results on XLNet, BERT, XLM, RoBERTa, DistilBERT and ALBERT to make sure it works as expected, then I'll rebase and call for review.

I made sure that I obtain somewhat the same results with fine-tuning + evaluating models with the old and new scripts. I could confirm it is the case for DistilBERT, BERT and XLNet.


self.max_len = max_len if max_len is not None else int(1e12)

# Padding side is right by default and over-riden in subclsses. If specified in the kwargs, it is changed.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 nice

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's add it to the class docstring later to have it in the doc as well.

)

if pad_to_max_length and max_length is None and self.max_len > 10000:
logger.warning("Sequence can't be padded as the maximum ")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning seems incomplete

@thomwolf

Copy link
Copy Markdown
Member

Ok this is great, merging!

@LysandreJik do you want to have a quick look at the two comments I wrote about doc/docstring and the incomplete warning?

Merging now because these are small tweak and @mfuntowicz need this PR for his PR so I'll let you push a doc commit on master directly maybe.

@thomwolf
thomwolf merged commit e57d00e into master Dec 10, 2019
Comment on lines +760 to +762
pad_to_max_length: if set to True, the returned sequences will be padded according to the model's padding side and
padding index, up to their max length. If no max length is specified, the padding is done up to the model's max length.
The tokenizer padding sides are handled by the following strings:

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@thomwolf Is that what you meant by class substring?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants