diff --git a/nlp/text_classification/bert/pytorch/README.md b/nlp/text_summarisation/bert/pytorch/README.md similarity index 49% rename from nlp/text_classification/bert/pytorch/README.md rename to nlp/text_summarisation/bert/pytorch/README.md index c82b996d19e04b68a6c9e98d74af3b18315f4ff1..29b3079d25c4494b16066b2afbc7a422ac47e0a3 100644 --- a/nlp/text_classification/bert/pytorch/README.md +++ b/nlp/text_summarisation/bert/pytorch/README.md @@ -1,15 +1,13 @@ -# Text Classification - -# Bert-base WNLI +# Bert-base summarization ## Model description -Bert-base WNLI task Fine-tuning +Bert-base summarization task Fine-tuning ## Step 1: Installing packages ``` shell -cd /nlp/text_classification/bert/pytorch +cd /nlp/ner/bert/pytorch pip3 install -r requirements.txt ``` @@ -28,10 +26,10 @@ bash train_dist.sh ``` ## Results on BI-V100 -| GPUs | Samples/s | Loss | -|------|-----------|------| -| 1x1 | 144.5 | 0.74 | -| 1x8 | 322.74 | 0.71 | +| GPUs | Samples/s | Loss | +|------|-----------|--------| +| 1x1 | 1834.099 | 0.0281 | +| 1x8 | 6229.625 | 0.0278 | ## Reference -https://github.com/huggingface/ +https://github.com/huggingface/ \ No newline at end of file diff --git a/nlp/text_summarisation/bert/pytorch/cnn_dailymail.py b/nlp/text_summarisation/bert/pytorch/cnn_dailymail.py new file mode 100644 index 0000000000000000000000000000000000000000..5d80cf06663b4d195185a116229d0f7d783d1cb2 --- /dev/null +++ b/nlp/text_summarisation/bert/pytorch/cnn_dailymail.py @@ -0,0 +1,250 @@ +# coding=utf-8 +# Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors. +# +# 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. + +# Lint as: python3 +"""CNN/DailyMail Summarization dataset, non-anonymized version.""" + +import hashlib +import os + +import datasets + + +logger = datasets.logging.get_logger(__name__) + + +_HOMEPAGE = "https://github.com/abisee/cnn-dailymail" + +_DESCRIPTION = """\ +CNN/DailyMail non-anonymized summarization dataset. + +There are two features: + - article: text of news article, used as the document to be summarized + - highlights: joined text of highlights with and around each + highlight, which is the target summary +""" + +# The second citation introduces the source data, while the first +# introduces the specific form (non-anonymized) we use here. +_CITATION = """\ +@article{DBLP:journals/corr/SeeLM17, + author = {Abigail See and + Peter J. Liu and + Christopher D. Manning}, + title = {Get To The Point: Summarization with Pointer-Generator Networks}, + journal = {CoRR}, + volume = {abs/1704.04368}, + year = {2017}, + url = {http://arxiv.org/abs/1704.04368}, + archivePrefix = {arXiv}, + eprint = {1704.04368}, + timestamp = {Mon, 13 Aug 2018 16:46:08 +0200}, + biburl = {https://dblp.org/rec/bib/journals/corr/SeeLM17}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} + +@inproceedings{hermann2015teaching, + title={Teaching machines to read and comprehend}, + author={Hermann, Karl Moritz and Kocisky, Tomas and Grefenstette, Edward and Espeholt, Lasse and Kay, Will and Suleyman, Mustafa and Blunsom, Phil}, + booktitle={Advances in neural information processing systems}, + pages={1693--1701}, + year={2015} +} +""" + +_DL_URLS = { + "cnn_stories": "https://huggingface.co/datasets/cnn_dailymail/resolve/11343c3752184397d56efc19a8a7cceb68089318/data/cnn_stories.tgz", + "dm_stories": "https://huggingface.co/datasets/cnn_dailymail/resolve/11343c3752184397d56efc19a8a7cceb68089318/data/dailymail_stories.tgz", + "train": "https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_train.txt", + "validation": "https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_val.txt", + "test": "https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_test.txt", +} + +_HIGHLIGHTS = "highlights" +_ARTICLE = "article" + +_SUPPORTED_VERSIONS = [ + # Using cased version. + datasets.Version("3.0.0", "Using cased version."), + # Same data as 0.0.2 + datasets.Version("1.0.0", ""), + # Having the model predict newline separators makes it easier to evaluate + # using summary-level ROUGE. + datasets.Version("2.0.0", "Separate target sentences with newline."), +] + + +_DEFAULT_VERSION = datasets.Version("3.0.0", "Using cased version.") + + +class CnnDailymailConfig(datasets.BuilderConfig): + """BuilderConfig for CnnDailymail.""" + + def __init__(self, **kwargs): + """BuilderConfig for CnnDailymail. + + Args: + + **kwargs: keyword arguments forwarded to super. + """ + super(CnnDailymailConfig, self).__init__(**kwargs) + + +def _get_url_hashes(path): + """Get hashes of urls in file.""" + urls = _read_text_file_path(path) + + def url_hash(u): + h = hashlib.sha1() + try: + u = u.encode("utf-8") + except UnicodeDecodeError: + logger.error("Cannot hash url: %s", u) + h.update(u) + return h.hexdigest() + + return {url_hash(u) for u in urls} + + +def _get_hash_from_path(p): + """Extract hash from path.""" + return os.path.splitext(os.path.basename(p))[0] + + +DM_SINGLE_CLOSE_QUOTE = "\u2019" # unicode +DM_DOUBLE_CLOSE_QUOTE = "\u201d" +# acceptable ways to end a sentence +END_TOKENS = [".", "!", "?", "...", "'", "`", '"', DM_SINGLE_CLOSE_QUOTE, DM_DOUBLE_CLOSE_QUOTE, ")"] + + +def _read_text_file_path(path): + with open(path, "r", encoding="utf-8") as f: + lines = [line.strip() for line in f] + return lines + + +def _read_text_file(file): + return [line.decode("utf-8").strip() for line in file] + + +def _get_art_abs(story_file, tfds_version): + """Get abstract (highlights) and article from a story file path.""" + # Based on https://github.com/abisee/cnn-dailymail/blob/master/ + # make_datafiles.py + + lines = _read_text_file(story_file) + + # The github code lowercase the text and we removed it in 3.0.0. + + # Put periods on the ends of lines that are missing them + # (this is a problem in the dataset because many image captions don't end in + # periods; consequently they end up in the body of the article as run-on + # sentences) + def fix_missing_period(line): + """Adds a period to a line that is missing a period.""" + if "@highlight" in line: + return line + if not line: + return line + if line[-1] in END_TOKENS: + return line + return line + " ." + + lines = [fix_missing_period(line) for line in lines] + + # Separate out article and abstract sentences + article_lines = [] + highlights = [] + next_is_highlight = False + for line in lines: + if not line: + continue # empty line + elif line.startswith("@highlight"): + next_is_highlight = True + elif next_is_highlight: + highlights.append(line) + else: + article_lines.append(line) + + # Make article into a single string + article = " ".join(article_lines) + + if tfds_version >= "2.0.0": + abstract = "\n".join(highlights) + else: + abstract = " ".join(highlights) + + return article, abstract + + +class CnnDailymail(datasets.GeneratorBasedBuilder): + """CNN/DailyMail non-anonymized summarization dataset.""" + + BUILDER_CONFIGS = [ + CnnDailymailConfig(name=str(version), description="Plain text", version=version) + for version in _SUPPORTED_VERSIONS + ] + + def _info(self): + return datasets.DatasetInfo( + description=_DESCRIPTION, + features=datasets.Features( + { + _ARTICLE: datasets.Value("string"), + _HIGHLIGHTS: datasets.Value("string"), + "id": datasets.Value("string"), + } + ), + supervised_keys=None, + homepage=_HOMEPAGE, + citation=_CITATION, + ) + + def _vocab_text_gen(self, paths): + for _, ex in self._generate_examples(paths): + yield " ".join([ex[_ARTICLE], ex[_HIGHLIGHTS]]) + + def _split_generators(self, dl_manager): + dl_paths = dl_manager.download(_DL_URLS) + return [ + datasets.SplitGenerator( + name=split, + gen_kwargs={ + "urls_file": dl_paths[split], + "files_per_archive": [ + dl_manager.iter_archive(dl_paths["cnn_stories"]), + dl_manager.iter_archive(dl_paths["dm_stories"]), + ], + }, + ) + for split in [datasets.Split.TRAIN, datasets.Split.VALIDATION, datasets.Split.TEST] + ] + + def _generate_examples(self, urls_file, files_per_archive): + urls = _get_url_hashes(urls_file) + idx = 0 + for files in files_per_archive: + for path, file in files: + hash_from_path = _get_hash_from_path(path) + if hash_from_path in urls: + article, highlights = _get_art_abs(file, self.config.version) + if not article or not highlights: + continue + yield idx, { + _ARTICLE: article, + _HIGHLIGHTS: highlights, + "id": hash_from_path, + } + idx += 1 diff --git a/nlp/text_summarisation/bert/pytorch/dataset_infos.json b/nlp/text_summarisation/bert/pytorch/dataset_infos.json new file mode 100644 index 0000000000000000000000000000000000000000..3269f76cdb538b920f2931269590549b587e5aae --- /dev/null +++ b/nlp/text_summarisation/bert/pytorch/dataset_infos.json @@ -0,0 +1 @@ +{"3.0.0": {"description": "CNN/DailyMail non-anonymized summarization dataset.\n\nThere are two features:\n - article: text of news article, used as the document to be summarized\n - highlights: joined text of highlights with and around each\n highlight, which is the target summary\n", "citation": "@article{DBLP:journals/corr/SeeLM17,\n author = {Abigail See and\n Peter J. Liu and\n Christopher D. Manning},\n title = {Get To The Point: Summarization with Pointer-Generator Networks},\n journal = {CoRR},\n volume = {abs/1704.04368},\n year = {2017},\n url = {http://arxiv.org/abs/1704.04368},\n archivePrefix = {arXiv},\n eprint = {1704.04368},\n timestamp = {Mon, 13 Aug 2018 16:46:08 +0200},\n biburl = {https://dblp.org/rec/bib/journals/corr/SeeLM17},\n bibsource = {dblp computer science bibliography, https://dblp.org}\n}\n\n@inproceedings{hermann2015teaching,\n title={Teaching machines to read and comprehend},\n author={Hermann, Karl Moritz and Kocisky, Tomas and Grefenstette, Edward and Espeholt, Lasse and Kay, Will and Suleyman, Mustafa and Blunsom, Phil},\n booktitle={Advances in neural information processing systems},\n pages={1693--1701},\n year={2015}\n}\n", "homepage": "https://github.com/abisee/cnn-dailymail", "license": "", "features": {"article": {"dtype": "string", "id": null, "_type": "Value"}, "highlights": {"dtype": "string", "id": null, "_type": "Value"}, "id": {"dtype": "string", "id": null, "_type": "Value"}}, "post_processed": null, "supervised_keys": null, "task_templates": null, "builder_name": "cnn_dailymail", "config_name": "3.0.0", "version": {"version_str": "3.0.0", "description": "Using cased version.", "major": 3, "minor": 0, "patch": 0}, "splits": {"train": {"name": "train", "num_bytes": 1261704133, "num_examples": 287113, "dataset_name": "cnn_dailymail"}, "validation": {"name": "validation", "num_bytes": 57732436, "num_examples": 13368, "dataset_name": "cnn_dailymail"}, "test": {"name": "test", "num_bytes": 49925756, "num_examples": 11490, "dataset_name": "cnn_dailymail"}}, "download_checksums": {"https://huggingface.co/datasets/cnn_dailymail/resolve/11343c3752184397d56efc19a8a7cceb68089318/data/cnn_stories.tgz": {"num_bytes": 158577824, "checksum": "e8fbc0027e54e0a916abd9c969eb35f708ed1467d7ef4e3b17a56739d65cb200"}, "https://huggingface.co/datasets/cnn_dailymail/resolve/11343c3752184397d56efc19a8a7cceb68089318/data/dailymail_stories.tgz": {"num_bytes": 375893739, "checksum": "ad69010002210b7c406718248ee66e65868b9f6820f163aa966369878d14147e"}, "https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_train.txt": {"num_bytes": 46424688, "checksum": "a5cee49f3a6c862c26ce29308236d2a99625ab6c86a43be22d5206b2790d8029"}, "https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_val.txt": {"num_bytes": 2433674, "checksum": "81887e982b045083409c6ee838aede8ff4b97291605bcfb21bffc456a16991db"}, "https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_test.txt": {"num_bytes": 2109547, "checksum": "c4f5efb5ec2126430a5c156efbd13d0e9c4cb490169e552c38b4a51981a009bd"}}, "download_size": 585439472, "post_processing_size": null, "dataset_size": 1369362325, "size_in_bytes": 1954801797}, "1.0.0": {"description": "CNN/DailyMail non-anonymized summarization dataset.\n\nThere are two features:\n - article: text of news article, used as the document to be summarized\n - highlights: joined text of highlights with and around each\n highlight, which is the target summary\n", "citation": "@article{DBLP:journals/corr/SeeLM17,\n author = {Abigail See and\n Peter J. Liu and\n Christopher D. Manning},\n title = {Get To The Point: Summarization with Pointer-Generator Networks},\n journal = {CoRR},\n volume = {abs/1704.04368},\n year = {2017},\n url = {http://arxiv.org/abs/1704.04368},\n archivePrefix = {arXiv},\n eprint = {1704.04368},\n timestamp = {Mon, 13 Aug 2018 16:46:08 +0200},\n biburl = {https://dblp.org/rec/bib/journals/corr/SeeLM17},\n bibsource = {dblp computer science bibliography, https://dblp.org}\n}\n\n@inproceedings{hermann2015teaching,\n title={Teaching machines to read and comprehend},\n author={Hermann, Karl Moritz and Kocisky, Tomas and Grefenstette, Edward and Espeholt, Lasse and Kay, Will and Suleyman, Mustafa and Blunsom, Phil},\n booktitle={Advances in neural information processing systems},\n pages={1693--1701},\n year={2015}\n}\n", "homepage": "https://github.com/abisee/cnn-dailymail", "license": "", "features": {"article": {"dtype": "string", "id": null, "_type": "Value"}, "highlights": {"dtype": "string", "id": null, "_type": "Value"}, "id": {"dtype": "string", "id": null, "_type": "Value"}}, "post_processed": null, "supervised_keys": null, "task_templates": null, "builder_name": "cnn_dailymail", "config_name": "1.0.0", "version": {"version_str": "1.0.0", "description": "", "major": 1, "minor": 0, "patch": 0}, "splits": {"train": {"name": "train", "num_bytes": 1261704133, "num_examples": 287113, "dataset_name": "cnn_dailymail"}, "validation": {"name": "validation", "num_bytes": 57732436, "num_examples": 13368, "dataset_name": "cnn_dailymail"}, "test": {"name": "test", "num_bytes": 49925756, "num_examples": 11490, "dataset_name": "cnn_dailymail"}}, "download_checksums": {"https://huggingface.co/datasets/cnn_dailymail/resolve/11343c3752184397d56efc19a8a7cceb68089318/data/cnn_stories.tgz": {"num_bytes": 158577824, "checksum": "e8fbc0027e54e0a916abd9c969eb35f708ed1467d7ef4e3b17a56739d65cb200"}, "https://huggingface.co/datasets/cnn_dailymail/resolve/11343c3752184397d56efc19a8a7cceb68089318/data/dailymail_stories.tgz": {"num_bytes": 375893739, "checksum": "ad69010002210b7c406718248ee66e65868b9f6820f163aa966369878d14147e"}, "https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_train.txt": {"num_bytes": 46424688, "checksum": "a5cee49f3a6c862c26ce29308236d2a99625ab6c86a43be22d5206b2790d8029"}, "https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_val.txt": {"num_bytes": 2433674, "checksum": "81887e982b045083409c6ee838aede8ff4b97291605bcfb21bffc456a16991db"}, "https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_test.txt": {"num_bytes": 2109547, "checksum": "c4f5efb5ec2126430a5c156efbd13d0e9c4cb490169e552c38b4a51981a009bd"}}, "download_size": 585439472, "post_processing_size": null, "dataset_size": 1369362325, "size_in_bytes": 1954801797}, "2.0.0": {"description": "CNN/DailyMail non-anonymized summarization dataset.\n\nThere are two features:\n - article: text of news article, used as the document to be summarized\n - highlights: joined text of highlights with and around each\n highlight, which is the target summary\n", "citation": "@article{DBLP:journals/corr/SeeLM17,\n author = {Abigail See and\n Peter J. Liu and\n Christopher D. Manning},\n title = {Get To The Point: Summarization with Pointer-Generator Networks},\n journal = {CoRR},\n volume = {abs/1704.04368},\n year = {2017},\n url = {http://arxiv.org/abs/1704.04368},\n archivePrefix = {arXiv},\n eprint = {1704.04368},\n timestamp = {Mon, 13 Aug 2018 16:46:08 +0200},\n biburl = {https://dblp.org/rec/bib/journals/corr/SeeLM17},\n bibsource = {dblp computer science bibliography, https://dblp.org}\n}\n\n@inproceedings{hermann2015teaching,\n title={Teaching machines to read and comprehend},\n author={Hermann, Karl Moritz and Kocisky, Tomas and Grefenstette, Edward and Espeholt, Lasse and Kay, Will and Suleyman, Mustafa and Blunsom, Phil},\n booktitle={Advances in neural information processing systems},\n pages={1693--1701},\n year={2015}\n}\n", "homepage": "https://github.com/abisee/cnn-dailymail", "license": "", "features": {"article": {"dtype": "string", "id": null, "_type": "Value"}, "highlights": {"dtype": "string", "id": null, "_type": "Value"}, "id": {"dtype": "string", "id": null, "_type": "Value"}}, "post_processed": null, "supervised_keys": null, "task_templates": null, "builder_name": "cnn_dailymail", "config_name": "2.0.0", "version": {"version_str": "2.0.0", "description": "Separate target sentences with newline.", "major": 2, "minor": 0, "patch": 0}, "splits": {"train": {"name": "train", "num_bytes": 1261704133, "num_examples": 287113, "dataset_name": "cnn_dailymail"}, "validation": {"name": "validation", "num_bytes": 57732436, "num_examples": 13368, "dataset_name": "cnn_dailymail"}, "test": {"name": "test", "num_bytes": 49925756, "num_examples": 11490, "dataset_name": "cnn_dailymail"}}, "download_checksums": {"https://huggingface.co/datasets/cnn_dailymail/resolve/11343c3752184397d56efc19a8a7cceb68089318/data/cnn_stories.tgz": {"num_bytes": 158577824, "checksum": "e8fbc0027e54e0a916abd9c969eb35f708ed1467d7ef4e3b17a56739d65cb200"}, "https://huggingface.co/datasets/cnn_dailymail/resolve/11343c3752184397d56efc19a8a7cceb68089318/data/dailymail_stories.tgz": {"num_bytes": 375893739, "checksum": "ad69010002210b7c406718248ee66e65868b9f6820f163aa966369878d14147e"}, "https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_train.txt": {"num_bytes": 46424688, "checksum": "a5cee49f3a6c862c26ce29308236d2a99625ab6c86a43be22d5206b2790d8029"}, "https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_val.txt": {"num_bytes": 2433674, "checksum": "81887e982b045083409c6ee838aede8ff4b97291605bcfb21bffc456a16991db"}, "https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_test.txt": {"num_bytes": 2109547, "checksum": "c4f5efb5ec2126430a5c156efbd13d0e9c4cb490169e552c38b4a51981a009bd"}}, "download_size": 585439472, "post_processing_size": null, "dataset_size": 1369362325, "size_in_bytes": 1954801797}} \ No newline at end of file diff --git a/nlp/text_classification/bert/pytorch/requirements.txt b/nlp/text_summarisation/bert/pytorch/requirements.txt similarity index 71% rename from nlp/text_classification/bert/pytorch/requirements.txt rename to nlp/text_summarisation/bert/pytorch/requirements.txt index dbfdb439fa1cccd3afa51a40bc677f4590480c1e..b2aa71666c240c8c0f44e411bd5e5ea457f95818 100644 --- a/nlp/text_classification/bert/pytorch/requirements.txt +++ b/nlp/text_summarisation/bert/pytorch/requirements.txt @@ -1,10 +1,10 @@ accelerate >= 0.12.0 datasets >= 1.8.0 sentencepiece != 0.1.92 -scipy -scikit-learn protobuf -# torch >= 1.3 +rouge-score +nltk +py7zr +numpy==1.23.4 evaluate -numpy == 1.23.4 git+https://github.com/huggingface/transformers \ No newline at end of file diff --git a/nlp/text_classification/bert/pytorch/run_glue.py b/nlp/text_summarisation/bert/pytorch/run_summarization.py similarity index 38% rename from nlp/text_classification/bert/pytorch/run_glue.py rename to nlp/text_summarisation/bert/pytorch/run_summarization.py index e8ede80ea021a445683e46d72c26aec8138c2e67..9318df5d9ec0172e9e404cf455ddd9ac60095e60 100644 --- a/nlp/text_classification/bert/pytorch/run_glue.py +++ b/nlp/text_summarisation/bert/pytorch/run_summarization.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # coding=utf-8 -# Copyright 2020 The HuggingFace Inc. team. All rights reserved. +# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,82 +13,161 @@ # 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. -""" Finetuning the library models for sequence classification on GLUE.""" -# You can also adapt this script on your own text classification task. Pointers for this are left as comments. +""" +Fine-tuning the library models for sequence to sequence. +""" +# You can also adapt this script on your own sequence to sequence task. Pointers for this are left as comments. import logging import os -import random +import pdb import sys from dataclasses import dataclass, field from typing import Optional import datasets import evaluate +import nltk # Here to have a nice missing dependency error message early on import numpy as np from datasets import load_dataset +from filelock import FileLock import transformers from transformers import ( AutoConfig, - AutoModelForSequenceClassification, + AutoModelForSeq2SeqLM, AutoTokenizer, - DataCollatorWithPadding, - EvalPrediction, + DataCollatorForSeq2Seq, HfArgumentParser, - PretrainedConfig, - Trainer, - TrainingArguments, - default_data_collator, + MBart50Tokenizer, + MBart50TokenizerFast, + MBartTokenizer, + MBartTokenizerFast, + Seq2SeqTrainer, + Seq2SeqTrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint -from transformers.utils import check_min_version, send_example_telemetry +from transformers.utils import check_min_version, is_offline_mode, send_example_telemetry from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.27.0.dev0") -require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt") - -task_to_keys = { - "cola": ("sentence", None), - "mnli": ("premise", "hypothesis"), - "mrpc": ("sentence1", "sentence2"), - "qnli": ("question", "sentence"), - "qqp": ("question1", "question2"), - "rte": ("sentence1", "sentence2"), - "sst2": ("sentence", None), - "stsb": ("sentence1", "sentence2"), - "wnli": ("sentence1", "sentence2"), -} +require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/summarization/requirements.txt") logger = logging.getLogger(__name__) +try: + nltk.data.find("punkt") +except (LookupError, OSError): + if is_offline_mode(): + raise LookupError( + "Offline mode: run this script without TRANSFORMERS_OFFLINE first to download nltk data files" + ) + with FileLock(".lock") as lock: + nltk.download("punkt", quiet=True) + +# A list of all multilingual tokenizer which require lang attribute. +MULTILINGUAL_TOKENIZERS = [MBartTokenizer, MBartTokenizerFast, MBart50Tokenizer, MBart50TokenizerFast] + @dataclass -class DataTrainingArguments: +class ModelArguments: """ - Arguments pertaining to what data we are going to input our model for training and eval. - - Using `HfArgumentParser` we can turn this class - into argparse arguments to be able to specify them on - the command line. + Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. """ - task_name: Optional[str] = field( + model_name_or_path: str = field( + metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} + ) + config_name: Optional[str] = field( + default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} + ) + tokenizer_name: Optional[str] = field( + default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} + ) + cache_dir: Optional[str] = field( + default=None, + metadata={"help": "Where to store the pretrained models downloaded from huggingface.co"}, + ) + use_fast_tokenizer: bool = field( + default=True, + metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."}, + ) + model_revision: str = field( + default="main", + metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}, + ) + use_auth_token: bool = field( + default=False, + metadata={ + "help": ( + "Will use the token generated when running `huggingface-cli login` (necessary to use this script " + "with private models)." + ) + }, + ) + resize_position_embeddings: Optional[bool] = field( default=None, - metadata={"help": "The name of the task to train on: " + ", ".join(task_to_keys.keys())}, + metadata={ + "help": ( + "Whether to automatically resize the position embeddings if `max_source_length` exceeds " + "the model's position embeddings." + ) + }, ) + + +@dataclass +class DataTrainingArguments: + """ + Arguments pertaining to what data we are going to input our model for training and eval. + """ + + lang: Optional[str] = field(default=None, metadata={"help": "Language id for summarization."}) + dataset_name: Optional[str] = field( default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."} ) dataset_config_name: Optional[str] = field( default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) - max_seq_length: int = field( - default=128, + text_column: Optional[str] = field( + default=None, + metadata={"help": "The name of the column in the datasets containing the full texts (for summarization)."}, + ) + summary_column: Optional[str] = field( + default=None, + metadata={"help": "The name of the column in the datasets containing the summaries (for summarization)."}, + ) + train_file: Optional[str] = field( + default=None, metadata={"help": "The input training data file (a jsonlines or csv file)."} + ) + validation_file: Optional[str] = field( + default=None, + metadata={ + "help": ( + "An optional input evaluation data file to evaluate the metrics (rouge) on (a jsonlines or csv file)." + ) + }, + ) + test_file: Optional[str] = field( + default=None, + metadata={ + "help": "An optional input test data file to evaluate the metrics (rouge) on (a jsonlines or csv file)." + }, + ) + overwrite_cache: bool = field( + default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} + ) + preprocessing_num_workers: Optional[int] = field( + default=None, + metadata={"help": "The number of processes to use for the preprocessing."}, + ) + max_source_length: Optional[int] = field( + default=1024, metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " @@ -96,15 +175,33 @@ class DataTrainingArguments: ) }, ) - overwrite_cache: bool = field( - default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."} + max_target_length: Optional[int] = field( + default=128, + metadata={ + "help": ( + "The maximum total sequence length for target text after tokenization. Sequences longer " + "than this will be truncated, sequences shorter will be padded." + ) + }, + ) + val_max_target_length: Optional[int] = field( + default=None, + metadata={ + "help": ( + "The maximum total sequence length for validation target text after tokenization. Sequences longer " + "than this will be truncated, sequences shorter will be padded. Will default to `max_target_length`." + "This argument is also used to override the ``max_length`` param of ``model.generate``, which is used " + "during ``evaluate`` and ``predict``." + ) + }, ) pad_to_max_length: bool = field( - default=True, + default=False, metadata={ "help": ( - "Whether to pad all samples to `max_seq_length`. " - "If False, will pad the samples dynamically when batching to the maximum length in the batch." + "Whether to pad all samples to model maximum sentence length. " + "If False, will pad the samples dynamically when batching to the maximum length in the batch. More " + "efficient on GPU but very bad for TPU." ) }, ) @@ -135,72 +232,64 @@ class DataTrainingArguments: ) }, ) - train_file: Optional[str] = field( - default=None, metadata={"help": "A csv or a json file containing the training data."} - ) - validation_file: Optional[str] = field( - default=None, metadata={"help": "A csv or a json file containing the validation data."} - ) - test_file: Optional[str] = field(default=None, metadata={"help": "A csv or a json file containing the test data."}) - - def __post_init__(self): - if self.task_name is not None: - self.task_name = self.task_name.lower() - if self.task_name not in task_to_keys.keys(): - raise ValueError("Unknown task, you should pick one in " + ",".join(task_to_keys.keys())) - elif self.dataset_name is not None: - pass - elif self.train_file is None or self.validation_file is None: - raise ValueError("Need either a GLUE task, a training/validation file or a dataset name.") - else: - train_extension = self.train_file.split(".")[-1] - assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file." - validation_extension = self.validation_file.split(".")[-1] - assert ( - validation_extension == train_extension - ), "`validation_file` should have the same extension (csv or json) as `train_file`." - - -@dataclass -class ModelArguments: - """ - Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. - """ - - model_name_or_path: str = field( - metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} - ) - config_name: Optional[str] = field( - default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} - ) - tokenizer_name: Optional[str] = field( - default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} - ) - cache_dir: Optional[str] = field( + num_beams: Optional[int] = field( default=None, - metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, + metadata={ + "help": ( + "Number of beams to use for evaluation. This argument will be passed to ``model.generate``, " + "which is used during ``evaluate`` and ``predict``." + ) + }, ) - use_fast_tokenizer: bool = field( + ignore_pad_token_for_loss: bool = field( default=True, - metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."}, + metadata={ + "help": "Whether to ignore the tokens corresponding to padded labels in the loss computation or not." + }, ) - model_revision: str = field( - default="main", - metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}, + source_prefix: Optional[str] = field( + default="", metadata={"help": "A prefix to add before every source text (useful for T5 models)."} ) - use_auth_token: bool = field( - default=False, + + forced_bos_token: Optional[str] = field( + default=None, metadata={ "help": ( - "Will use the token generated when running `huggingface-cli login` (necessary to use this script " - "with private models)." + "The token to force as the first generated token after the decoder_start_token_id." + "Useful for multilingual models like mBART where the first generated token" + "needs to be the target language token (Usually it is the target language token)" ) }, ) - ignore_mismatched_sizes: bool = field( - default=False, - metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."}, - ) + + def __post_init__(self): + if self.dataset_name is None and self.train_file is None and self.validation_file is None: + raise ValueError("Need either a dataset name or a training/validation file.") + else: + if self.train_file is not None: + extension = self.train_file.split(".")[-1] + assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." + if self.validation_file is not None: + extension = self.validation_file.split(".")[-1] + assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." + if self.val_max_target_length is None: + self.val_max_target_length = self.max_target_length + + +summarization_name_mapping = { + "amazon_reviews_multi": ("review_body", "review_title"), + "big_patent": ("description", "abstract"), + "cnn_dailymail": ("article", "highlights"), + "orange_sum": ("text", "summary"), + "pn_summary": ("article", "summary"), + "psc": ("extract_text", "summary_text"), + "samsum": ("dialogue", "summary"), + "thaisum": ("body", "summary"), + "xglue": ("news_body", "news_title"), + "xsum": ("document", "summary"), + "wiki_summary": ("article", "highlights"), + "multi_news": ("document", "summary"), +} def main(): @@ -208,7 +297,7 @@ def main(): # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. - parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) + parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. @@ -218,7 +307,7 @@ def main(): # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. - send_example_telemetry("run_glue", model_args, data_args) + send_example_telemetry("run_summarization", model_args, data_args) # Setup logging logging.basicConfig( @@ -226,7 +315,6 @@ def main(): datefmt="%m/%d/%Y %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout)], ) - log_level = training_args.get_process_log_level() logger.setLevel(log_level) datasets.utils.logging.set_verbosity(log_level) @@ -241,6 +329,18 @@ def main(): ) logger.info(f"Training/evaluation parameters {training_args}") + if data_args.source_prefix is None and model_args.model_name_or_path in [ + "t5-small", + "t5-base", + "t5-large", + "t5-3b", + "t5-11b", + ]: + logger.warning( + "You're running a t5 model but didn't provide a source prefix, which is the expected, e.g. with " + "`--source_prefix 'summarize: ' `" + ) + # Detecting last checkpoint. last_checkpoint = None if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: @@ -260,101 +360,49 @@ def main(): set_seed(training_args.seed) # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below) - # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub). - # - # For CSV/JSON files, this script will use as labels the column called 'label' and as pair of sentences the - # sentences in columns called 'sentence1' and 'sentence2' if such column exists or the first two columns not named - # label if at least two columns are provided. + # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ + # (the dataset will be downloaded automatically from the datasets Hub). # - # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this - # single column. You can easily tweak this behavior (see below) + # For CSV/JSON files this script will use the first column for the full texts and the second column for the + # summaries (unless you specify column names for this with the `text_column` and `summary_column` arguments). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. - if data_args.task_name is not None: + if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. raw_datasets = load_dataset( - "glue", - data_args.task_name, + data_args.dataset_name, + data_args.dataset_config_name, cache_dir=model_args.cache_dir, use_auth_token=True if model_args.use_auth_token else None, ) - elif data_args.dataset_name is not None: - # Downloading and loading a dataset from the hub. + else: + data_files = {} + if data_args.train_file is not None: + data_files["train"] = data_args.train_file + extension = data_args.train_file.split(".")[-1] + if data_args.validation_file is not None: + data_files["validation"] = data_args.validation_file + extension = data_args.validation_file.split(".")[-1] + if data_args.test_file is not None: + data_files["test"] = data_args.test_file + extension = data_args.test_file.split(".")[-1] raw_datasets = load_dataset( - data_args.dataset_name, - data_args.dataset_config_name, + extension, + data_files=data_files, cache_dir=model_args.cache_dir, use_auth_token=True if model_args.use_auth_token else None, ) - else: - # Loading a dataset from your local files. - # CSV/JSON training and evaluation files are needed. - data_files = {"train": data_args.train_file, "validation": data_args.validation_file} - - # Get the test dataset: you can provide your own CSV/JSON test file (see below) - # when you use `do_predict` without specifying a GLUE benchmark task. - if training_args.do_predict: - if data_args.test_file is not None: - train_extension = data_args.train_file.split(".")[-1] - test_extension = data_args.test_file.split(".")[-1] - assert ( - test_extension == train_extension - ), "`test_file` should have the same extension (csv or json) as `train_file`." - data_files["test"] = data_args.test_file - else: - raise ValueError("Need either a GLUE task or a test file for `do_predict`.") - - for key in data_files.keys(): - logger.info(f"load a local file for {key}: {data_files[key]}") - - if data_args.train_file.endswith(".csv"): - # Loading a dataset from local csv files - raw_datasets = load_dataset( - "csv", - data_files=data_files, - cache_dir=model_args.cache_dir, - use_auth_token=True if model_args.use_auth_token else None, - ) - else: - # Loading a dataset from local json files - raw_datasets = load_dataset( - "json", - data_files=data_files, - cache_dir=model_args.cache_dir, - use_auth_token=True if model_args.use_auth_token else None, - ) - # See more about loading any type of standard or custom dataset at + # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. - # Labels - if data_args.task_name is not None: - is_regression = data_args.task_name == "stsb" - if not is_regression: - label_list = raw_datasets["train"].features["label"].names - num_labels = len(label_list) - else: - num_labels = 1 - else: - # Trying to have good defaults here, don't hesitate to tweak to your needs. - is_regression = raw_datasets["train"].features["label"].dtype in ["float32", "float64"] - if is_regression: - num_labels = 1 - else: - # A useful fast method: - # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.unique - label_list = raw_datasets["train"].unique("label") - label_list.sort() # Let's sort it for determinism - num_labels = len(label_list) - # Load pretrained model and tokenizer # - # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently + # Distributed training: + # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. config = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, - num_labels=num_labels, - finetuning_task=data_args.task_name, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, @@ -366,90 +414,133 @@ def main(): revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) - model = AutoModelForSequenceClassification.from_pretrained( + model = AutoModelForSeq2SeqLM.from_pretrained( model_args.model_name_or_path, from_tf=bool(".ckpt" in model_args.model_name_or_path), config=config, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, - ignore_mismatched_sizes=model_args.ignore_mismatched_sizes, ) - # Preprocessing the raw_datasets - if data_args.task_name is not None: - sentence1_key, sentence2_key = task_to_keys[data_args.task_name] - else: - # Again, we try to have some nice defaults but don't hesitate to tweak to your use case. - non_label_column_names = [name for name in raw_datasets["train"].column_names if name != "label"] - if "sentence1" in non_label_column_names and "sentence2" in non_label_column_names: - sentence1_key, sentence2_key = "sentence1", "sentence2" + # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch + # on a small vocab and want a smaller embedding size, remove this test. + embedding_size = model.get_input_embeddings().weight.shape[0] + if len(tokenizer) > embedding_size: + model.resize_token_embeddings(len(tokenizer)) + + if model.config.decoder_start_token_id is None and isinstance(tokenizer, (MBartTokenizer, MBartTokenizerFast)): + if isinstance(tokenizer, MBartTokenizer): + model.config.decoder_start_token_id = tokenizer.lang_code_to_id[data_args.lang] else: - if len(non_label_column_names) >= 2: - sentence1_key, sentence2_key = non_label_column_names[:2] - else: - sentence1_key, sentence2_key = non_label_column_names[0], None - - # Padding strategy - if data_args.pad_to_max_length: - padding = "max_length" - else: - # We will pad later, dynamically at batch creation, to the max sequence length in each batch - padding = False + model.config.decoder_start_token_id = tokenizer.convert_tokens_to_ids(data_args.lang) + + if model.config.decoder_start_token_id is None: + raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined") - # Some models have set the order of the labels to use, so let's make sure we do use it. - label_to_id = None if ( - model.config.label2id != PretrainedConfig(num_labels=num_labels).label2id - and data_args.task_name is not None - and not is_regression + hasattr(model.config, "max_position_embeddings") + and model.config.max_position_embeddings < data_args.max_source_length ): - # Some have all caps in their config, some don't. - label_name_to_id = {k.lower(): v for k, v in model.config.label2id.items()} - if list(sorted(label_name_to_id.keys())) == list(sorted(label_list)): - label_to_id = {i: int(label_name_to_id[label_list[i]]) for i in range(num_labels)} - else: + if model_args.resize_position_embeddings is None: logger.warning( - "Your model seems to have been trained with labels, but they don't match the dataset: ", - f"model labels: {list(sorted(label_name_to_id.keys()))}, dataset labels: {list(sorted(label_list))}." - "\nIgnoring the model labels as a result.", + "Increasing the model's number of position embedding vectors from" + f" {model.config.max_position_embeddings} to {data_args.max_source_length}." ) - elif data_args.task_name is None and not is_regression: - label_to_id = {v: i for i, v in enumerate(label_list)} + model.resize_position_embeddings(data_args.max_source_length) + elif model_args.resize_position_embeddings: + model.resize_position_embeddings(data_args.max_source_length) + else: + raise ValueError( + f"`--max_source_length` is set to {data_args.max_source_length}, but the model only has" + f" {model.config.max_position_embeddings} position encodings. Consider either reducing" + f" `--max_source_length` to {model.config.max_position_embeddings} or to automatically resize the" + " model's position encodings by passing `--resize_position_embeddings`." + ) + + prefix = data_args.source_prefix if data_args.source_prefix is not None else "" + + # Preprocessing the datasets. + # We need to tokenize inputs and targets. + if training_args.do_train: + column_names = raw_datasets["train"].column_names + elif training_args.do_eval: + column_names = raw_datasets["validation"].column_names + elif training_args.do_predict: + column_names = raw_datasets["test"].column_names + else: + logger.info("There is nothing to do. Please pass `do_train`, `do_eval` and/or `do_predict`.") + return + + if isinstance(tokenizer, tuple(MULTILINGUAL_TOKENIZERS)): + assert ( + data_args.lang is not None + ), f"{tokenizer.__class__.__name__} is a multilingual tokenizer which requires --lang argument" + + tokenizer.src_lang = data_args.lang + tokenizer.tgt_lang = data_args.lang - if label_to_id is not None: - model.config.label2id = label_to_id - model.config.id2label = {id: label for label, id in config.label2id.items()} - elif data_args.task_name is not None and not is_regression: - model.config.label2id = {l: i for i, l in enumerate(label_list)} - model.config.id2label = {id: label for label, id in config.label2id.items()} + # For multilingual translation models like mBART-50 and M2M100 we need to force the target language token + # as the first generated token. We ask the user to explicitly provide this as --forced_bos_token argument. + forced_bos_token_id = ( + tokenizer.lang_code_to_id[data_args.forced_bos_token] if data_args.forced_bos_token is not None else None + ) + model.config.forced_bos_token_id = forced_bos_token_id - if data_args.max_seq_length > tokenizer.model_max_length: + # Get the column names for input/target. + dataset_columns = summarization_name_mapping.get(data_args.dataset_name, None) + if data_args.text_column is None: + text_column = dataset_columns[0] if dataset_columns is not None else column_names[0] + else: + text_column = data_args.text_column + if text_column not in column_names: + raise ValueError( + f"--text_column' value '{data_args.text_column}' needs to be one of: {', '.join(column_names)}" + ) + if data_args.summary_column is None: + summary_column = dataset_columns[1] if dataset_columns is not None else column_names[1] + else: + summary_column = data_args.summary_column + if summary_column not in column_names: + raise ValueError( + f"--summary_column' value '{data_args.summary_column}' needs to be one of: {', '.join(column_names)}" + ) + + # Temporarily set max_target_length for training. + max_target_length = data_args.max_target_length + padding = "max_length" if data_args.pad_to_max_length else False + + if training_args.label_smoothing_factor > 0 and not hasattr(model, "prepare_decoder_input_ids_from_labels"): logger.warning( - f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the" - f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}." + "label_smoothing is enabled but the `prepare_decoder_input_ids_from_labels` method is not defined for" + f"`{model.__class__.__name__}`. This will lead to loss being calculated twice and will take up more memory" ) - max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length) def preprocess_function(examples): - # Tokenize the texts - args = ( - (examples[sentence1_key],) if sentence2_key is None else (examples[sentence1_key], examples[sentence2_key]) - ) - result = tokenizer(*args, padding=padding, max_length=max_seq_length, truncation=True) + # remove pairs where at least one record is None - # Map labels to IDs (not necessary for GLUE tasks) - if label_to_id is not None and "label" in examples: - result["label"] = [(label_to_id[l] if l != -1 else -1) for l in examples["label"]] - return result + inputs, targets = [], [] + for i in range(len(examples[text_column])): + if examples[text_column][i] and examples[summary_column][i]: + inputs.append(examples[text_column][i]) + targets.append(examples[summary_column][i]) + + inputs = [prefix + inp for inp in inputs] + model_inputs = tokenizer(inputs, max_length=data_args.max_source_length, padding=padding, truncation=True) + + # Tokenize targets with the `text_target` keyword argument + labels = tokenizer(text_target=targets, max_length=max_target_length, padding=padding, truncation=True) + + # If we are padding here, replace all tokenizer.pad_token_id in the labels by -100 when we want to ignore + # padding in the loss. + if padding == "max_length" and data_args.ignore_pad_token_for_loss: + labels["input_ids"] = [ + [(l if l != tokenizer.pad_token_id else -100) for l in label] for label in labels["input_ids"] + ] + + model_inputs["labels"] = labels["input_ids"] + return model_inputs - with training_args.main_process_first(desc="dataset map pre-processing"): - raw_datasets = raw_datasets.map( - preprocess_function, - batched=True, - load_from_cache_file=not data_args.overwrite_cache, - desc="Running tokenizer on dataset", - ) if training_args.do_train: if "train" not in raw_datasets: raise ValueError("--do_train requires a train dataset") @@ -457,67 +548,102 @@ def main(): if data_args.max_train_samples is not None: max_train_samples = min(len(train_dataset), data_args.max_train_samples) train_dataset = train_dataset.select(range(max_train_samples)) + with training_args.main_process_first(desc="train dataset map pre-processing"): + train_dataset = train_dataset.map( + preprocess_function, + batched=True, + num_proc=data_args.preprocessing_num_workers, + remove_columns=column_names, + load_from_cache_file=not data_args.overwrite_cache, + desc="Running tokenizer on train dataset", + ) if training_args.do_eval: - if "validation" not in raw_datasets and "validation_matched" not in raw_datasets: + max_target_length = data_args.val_max_target_length + if "validation" not in raw_datasets: raise ValueError("--do_eval requires a validation dataset") - eval_dataset = raw_datasets["validation_matched" if data_args.task_name == "mnli" else "validation"] + eval_dataset = raw_datasets["validation"] if data_args.max_eval_samples is not None: max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples) eval_dataset = eval_dataset.select(range(max_eval_samples)) + with training_args.main_process_first(desc="validation dataset map pre-processing"): + eval_dataset = eval_dataset.map( + preprocess_function, + batched=True, + num_proc=data_args.preprocessing_num_workers, + remove_columns=column_names, + load_from_cache_file=not data_args.overwrite_cache, + desc="Running tokenizer on validation dataset", + ) - if training_args.do_predict or data_args.task_name is not None or data_args.test_file is not None: - if "test" not in raw_datasets and "test_matched" not in raw_datasets: + if training_args.do_predict: + max_target_length = data_args.val_max_target_length + if "test" not in raw_datasets: raise ValueError("--do_predict requires a test dataset") - predict_dataset = raw_datasets["test_matched" if data_args.task_name == "mnli" else "test"] + predict_dataset = raw_datasets["test"] if data_args.max_predict_samples is not None: max_predict_samples = min(len(predict_dataset), data_args.max_predict_samples) predict_dataset = predict_dataset.select(range(max_predict_samples)) + with training_args.main_process_first(desc="prediction dataset map pre-processing"): + predict_dataset = predict_dataset.map( + preprocess_function, + batched=True, + num_proc=data_args.preprocessing_num_workers, + remove_columns=column_names, + load_from_cache_file=not data_args.overwrite_cache, + desc="Running tokenizer on prediction dataset", + ) - # Log a few random samples from the training set: - if training_args.do_train: - for index in random.sample(range(len(train_dataset)), 3): - logger.info(f"Sample {index} of the training set: {train_dataset[index]}.") + # Data collator + label_pad_token_id = -100 if data_args.ignore_pad_token_for_loss else tokenizer.pad_token_id + data_collator = DataCollatorForSeq2Seq( + tokenizer, + model=model, + label_pad_token_id=label_pad_token_id, + pad_to_multiple_of=8 if training_args.fp16 else None, + ) - # Get the metric function - if data_args.task_name is not None: - metric = evaluate.load("glue", data_args.task_name) - else: - metric = evaluate.load("accuracy") - - # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a - # predictions and label_ids field) and has to return a dictionary string to float. - def compute_metrics(p: EvalPrediction): - preds = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions - preds = np.squeeze(preds) if is_regression else np.argmax(preds, axis=1) - if data_args.task_name is not None: - result = metric.compute(predictions=preds, references=p.label_ids) - if len(result) > 1: - result["combined_score"] = np.mean(list(result.values())).item() - return result - elif is_regression: - return {"mse": ((preds - p.label_ids) ** 2).mean().item()} - else: - return {"accuracy": (preds == p.label_ids).astype(np.float32).mean().item()} - - # Data collator will default to DataCollatorWithPadding when the tokenizer is passed to Trainer, so we change it if - # we already did the padding. - if data_args.pad_to_max_length: - data_collator = default_data_collator - elif training_args.fp16: - data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8) - else: - data_collator = None + # Metric + metric = evaluate.load("rouge") + + def postprocess_text(preds, labels): + preds = [pred.strip() for pred in preds] + labels = [label.strip() for label in labels] + + # rougeLSum expects newline after each sentence + preds = ["\n".join(nltk.sent_tokenize(pred)) for pred in preds] + labels = ["\n".join(nltk.sent_tokenize(label)) for label in labels] + + return preds, labels + + def compute_metrics(eval_preds): + preds, labels = eval_preds + if isinstance(preds, tuple): + preds = preds[0] + decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True) + if data_args.ignore_pad_token_for_loss: + # Replace -100 in the labels as we can't decode them. + labels = np.where(labels != -100, labels, tokenizer.pad_token_id) + decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True) + + # Some simple post-processing + decoded_preds, decoded_labels = postprocess_text(decoded_preds, decoded_labels) + + result = metric.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=True) + result = {k: round(v * 100, 4) for k, v in result.items()} + prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in preds] + result["gen_len"] = np.mean(prediction_lens) + return result # Initialize our Trainer - trainer = Trainer( + trainer = Seq2SeqTrainer( model=model, args=training_args, train_dataset=train_dataset if training_args.do_train else None, eval_dataset=eval_dataset if training_args.do_eval else None, - compute_metrics=compute_metrics, tokenizer=tokenizer, data_collator=data_collator, + compute_metrics=compute_metrics if training_args.predict_with_generate else None, ) # Training @@ -528,90 +654,79 @@ def main(): elif last_checkpoint is not None: checkpoint = last_checkpoint train_result = trainer.train(resume_from_checkpoint=checkpoint) + trainer.save_model() # Saves the tokenizer too for easy upload + metrics = train_result.metrics max_train_samples = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset) ) metrics["train_samples"] = min(max_train_samples, len(train_dataset)) - trainer.save_model() # Saves the tokenizer too for easy upload - trainer.log_metrics("train", metrics) trainer.save_metrics("train", metrics) trainer.save_state() # Evaluation + results = {} + max_length = ( + training_args.generation_max_length + if training_args.generation_max_length is not None + else data_args.val_max_target_length + ) + num_beams = data_args.num_beams if data_args.num_beams is not None else training_args.generation_num_beams if training_args.do_eval: logger.info("*** Evaluate ***") + metrics = trainer.evaluate(max_length=max_length, num_beams=num_beams, metric_key_prefix="eval") + max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset) + metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset)) - # Loop to handle MNLI double evaluation (matched, mis-matched) - tasks = [data_args.task_name] - eval_datasets = [eval_dataset] - if data_args.task_name == "mnli": - tasks.append("mnli-mm") - valid_mm_dataset = raw_datasets["validation_mismatched"] - if data_args.max_eval_samples is not None: - max_eval_samples = min(len(valid_mm_dataset), data_args.max_eval_samples) - valid_mm_dataset = valid_mm_dataset.select(range(max_eval_samples)) - eval_datasets.append(valid_mm_dataset) - combined = {} - - for eval_dataset, task in zip(eval_datasets, tasks): - metrics = trainer.evaluate(eval_dataset=eval_dataset) - - max_eval_samples = ( - data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset) - ) - metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset)) - - if task == "mnli-mm": - metrics = {k + "_mm": v for k, v in metrics.items()} - if task is not None and "mnli" in task: - combined.update(metrics) - - trainer.log_metrics("eval", metrics) - trainer.save_metrics("eval", combined if task is not None and "mnli" in task else metrics) + trainer.log_metrics("eval", metrics) + trainer.save_metrics("eval", metrics) if training_args.do_predict: logger.info("*** Predict ***") - # Loop to handle MNLI double evaluation (matched, mis-matched) - tasks = [data_args.task_name] - predict_datasets = [predict_dataset] - if data_args.task_name == "mnli": - tasks.append("mnli-mm") - predict_datasets.append(raw_datasets["test_mismatched"]) - - for predict_dataset, task in zip(predict_datasets, tasks): - # Removing the `label` columns because it contains -1 and Trainer won't like that. - predict_dataset = predict_dataset.remove_columns("label") - predictions = trainer.predict(predict_dataset, metric_key_prefix="predict").predictions - predictions = np.squeeze(predictions) if is_regression else np.argmax(predictions, axis=1) - - output_predict_file = os.path.join(training_args.output_dir, f"predict_results_{task}.txt") - if trainer.is_world_process_zero(): - with open(output_predict_file, "w") as writer: - logger.info(f"***** Predict results {task} *****") - writer.write("index\tprediction\n") - for index, item in enumerate(predictions): - if is_regression: - writer.write(f"{index}\t{item:3.3f}\n") - else: - item = label_list[item] - writer.write(f"{index}\t{item}\n") - - kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "text-classification"} - if data_args.task_name is not None: - kwargs["language"] = "en" - kwargs["dataset_tags"] = "glue" - kwargs["dataset_args"] = data_args.task_name - kwargs["dataset"] = f"GLUE {data_args.task_name.upper()}" + predict_results = trainer.predict( + predict_dataset, metric_key_prefix="predict", max_length=max_length, num_beams=num_beams + ) + metrics = predict_results.metrics + max_predict_samples = ( + data_args.max_predict_samples if data_args.max_predict_samples is not None else len(predict_dataset) + ) + metrics["predict_samples"] = min(max_predict_samples, len(predict_dataset)) + + trainer.log_metrics("predict", metrics) + trainer.save_metrics("predict", metrics) + + if trainer.is_world_process_zero(): + if training_args.predict_with_generate: + predictions = tokenizer.batch_decode( + predict_results.predictions, skip_special_tokens=True, clean_up_tokenization_spaces=True + ) + predictions = [pred.strip() for pred in predictions] + output_prediction_file = os.path.join(training_args.output_dir, "generated_predictions.txt") + with open(output_prediction_file, "w") as writer: + writer.write("\n".join(predictions)) + + kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "summarization"} + if data_args.dataset_name is not None: + kwargs["dataset_tags"] = data_args.dataset_name + if data_args.dataset_config_name is not None: + kwargs["dataset_args"] = data_args.dataset_config_name + kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}" + else: + kwargs["dataset"] = data_args.dataset_name + + if data_args.lang is not None: + kwargs["language"] = data_args.lang if training_args.push_to_hub: trainer.push_to_hub(**kwargs) else: trainer.create_model_card(**kwargs) + return results + def _mp_fn(index): # For xla_spawn (TPUs) diff --git a/nlp/text_summarisation/bert/pytorch/train.sh b/nlp/text_summarisation/bert/pytorch/train.sh new file mode 100644 index 0000000000000000000000000000000000000000..7bf430596a5a79a39bf5c543885b2618137e6020 --- /dev/null +++ b/nlp/text_summarisation/bert/pytorch/train.sh @@ -0,0 +1,26 @@ +# Copyright (c) 2023, Shanghai Iluvatar CoreX Semiconductor Co., Ltd. +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +python3 run_summarization.py \ + --model_name_or_path t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --predict_with_generate diff --git a/nlp/text_summarisation/bert/pytorch/train_dist.sh b/nlp/text_summarisation/bert/pytorch/train_dist.sh new file mode 100644 index 0000000000000000000000000000000000000000..38ae69c4c559e980869a680dc4779bb700fd65a2 --- /dev/null +++ b/nlp/text_summarisation/bert/pytorch/train_dist.sh @@ -0,0 +1,27 @@ +# Copyright (c) 2023, Shanghai Iluvatar CoreX Semiconductor Co., Ltd. +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +python3 -m torch.distributed.launch --nproc_per_node=8 --master_port 12333 \ + run_summarization.py \ + --model_name_or_path t5-small \ + --do_train \ + --do_eval \ + --dataset_name cnn_dailymail \ + --dataset_config "3.0.0" \ + --source_prefix "summarize: " \ + --output_dir /tmp/tst-summarization \ + --per_device_train_batch_size=4 \ + --per_device_eval_batch_size=4 \ + --predict_with_generate