diff --git "a/train-dataset.json" "b/train-dataset.json" new file mode 100644--- /dev/null +++ "b/train-dataset.json" @@ -0,0 +1,179 @@ +[ + { + "repo": "NVIDIA/NeMo", + "pull_number": 891, + "instance_id": "NVIDIA__NeMo-891", + "issue_numbers": [ + "2" + ], + "base_commit": "d30c5489d73f4e9275f9e628aeb6aa2cc01d6f70", + "patch": "diff --git a/nemo/collections/common/tokenizers/bert_tokenizer.py b/nemo/collections/common/tokenizers/bert_tokenizer.py\n--- a/nemo/collections/common/tokenizers/bert_tokenizer.py\n+++ b/nemo/collections/common/tokenizers/bert_tokenizer.py\n@@ -76,7 +76,9 @@ def __init__(self, pretrained_model=None, vocab_file=None, bert_derivative='bert\n logging.info(f'Deriving bert model type from pretrained model name.')\n if bert_derivative in TOKENIZERS:\n tokenizer_cls = TOKENIZERS[bert_derivative]\n- logging.info(f'Using {tokenizer_cls.__name__} tokenizer')\n+ logging.info(\n+ f'Using {tokenizer_cls.__name__} tokenizer for {bert_derivative}, lower_case: {do_lower_case}'\n+ )\n else:\n raise ValueError(\n f\"Bert_derivative value {bert_derivative} is not currently supported\"\ndiff --git a/nemo/collections/common/tokenizers/tokenizer_utils.py b/nemo/collections/common/tokenizers/tokenizer_utils.py\n--- a/nemo/collections/common/tokenizers/tokenizer_utils.py\n+++ b/nemo/collections/common/tokenizers/tokenizer_utils.py\n@@ -101,7 +101,17 @@ def get_tokenizer(\n if pretrained_model_name:\n model_type = pretrained_model_name.split('-')[0]\n \n- if tokenizer_name == 'nemobert':\n+ if 'megatron' in pretrained_model_name:\n+ do_lower_case = nemo.collections.nlp.modules.common.megatron.megatron_utils.is_lower_cased_megatron(\n+ pretrained_model_name\n+ )\n+ vocab_file = nemo.collections.nlp.modules.common.megatron.megatron_utils.get_megatron_vocab_file(\n+ pretrained_model_name\n+ )\n+ tokenizer = nemo.collections.common.tokenizers.bert_tokenizer.NemoBertTokenizer(\n+ bert_derivative='bert', vocab_file=vocab_file, do_lower_case=do_lower_case\n+ )\n+ elif tokenizer_name == 'nemobert':\n tokenizer = nemo.collections.common.tokenizers.bert_tokenizer.NemoBertTokenizer(\n pretrained_model=pretrained_model_name, vocab_file=vocab_file, do_lower_case=do_lower_case\n )\ndiff --git a/nemo/collections/nlp/modules/__init__.py b/nemo/collections/nlp/modules/__init__.py\n--- a/nemo/collections/nlp/modules/__init__.py\n+++ b/nemo/collections/nlp/modules/__init__.py\n@@ -12,4 +12,13 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n-from nemo.collections.nlp.modules.common import *\n+\n+from nemo.collections.nlp.modules.common import (\n+ AlbertEncoder,\n+ BertEncoder,\n+ DistilBertEncoder,\n+ MegatronBertEncoder,\n+ RobertaEncoder,\n+ get_pretrained_lm_model,\n+ get_pretrained_lm_models_list,\n+)\ndiff --git a/nemo/collections/nlp/modules/common/__init__.py b/nemo/collections/nlp/modules/common/__init__.py\n--- a/nemo/collections/nlp/modules/common/__init__.py\n+++ b/nemo/collections/nlp/modules/common/__init__.py\n@@ -21,8 +21,7 @@\n BertEncoder,\n DistilBertEncoder,\n RobertaEncoder,\n- get_huggingface_lm_model,\n- get_huggingface_lm_models_list,\n )\n+from nemo.collections.nlp.modules.common.megatron import MegatronBertEncoder\n from nemo.collections.nlp.modules.common.sequence_classifier import SequenceClassifier\n from nemo.collections.nlp.modules.common.token_classifier import BertPretrainingTokenClassifier, TokenClassifier\ndiff --git a/nemo/collections/nlp/modules/common/bert_module.py b/nemo/collections/nlp/modules/common/bert_module.py\n--- a/nemo/collections/nlp/modules/common/bert_module.py\n+++ b/nemo/collections/nlp/modules/common/bert_module.py\n@@ -37,8 +37,17 @@ def input_types(self) -> Optional[Dict[str, NeuralType]]:\n def output_types(self) -> Optional[Dict[str, NeuralType]]:\n return {\"last_hidden_states\": NeuralType(('B', 'T', 'D'), ChannelType())}\n \n+ @classmethod\n+ def restore_from(cls, restore_path: str):\n+ \"\"\"Restores module/model with weights\"\"\"\n+ pass\n+\n+ @classmethod\n def save_to(self, save_path: str):\n+ \"\"\"Saves module/model with weights\"\"\"\n pass\n \n- def restore_from(self, restore_path: str):\n- self.load_state_dict(torch.load(restore_path))\n+ def restore_weights(self, restore_path: str):\n+ \"\"\"Restores module/model's weights\"\"\"\n+ state_dict = torch.load(restore_path)\n+ self.load_state_dict(state_dict)\ndiff --git a/nemo/collections/nlp/modules/common/common_utils.py b/nemo/collections/nlp/modules/common/common_utils.py\n--- a/nemo/collections/nlp/modules/common/common_utils.py\n+++ b/nemo/collections/nlp/modules/common/common_utils.py\n@@ -21,6 +21,10 @@\n get_huggingface_lm_model,\n get_huggingface_lm_models_list,\n )\n+from nemo.collections.nlp.modules.common.megatron.megatron_utils import (\n+ get_megatron_lm_model,\n+ get_megatron_lm_models_list,\n+)\n \n __all__ = ['get_pretrained_lm_models_list', 'get_pretrained_lm_model']\n \n@@ -29,7 +33,7 @@ def get_pretrained_lm_models_list() -> List[str]:\n '''\n Returns the list of support pretrained models\n '''\n- return get_huggingface_lm_models_list()\n+ return get_huggingface_lm_models_list() + get_megatron_lm_models_list()\n \n \n def get_pretrained_lm_model(\n@@ -48,9 +52,17 @@ def get_pretrained_lm_model(\n if pretrained_model_name in get_huggingface_lm_models_list():\n model = get_huggingface_lm_model(config_file=config_file, pretrained_model_name=pretrained_model_name)\n else:\n- raise ValueError(f'{pretrained_model_name} is not supported')\n+ if pretrained_model_name in get_megatron_lm_models_list():\n+ model, default_checkpoint_file = get_megatron_lm_model(\n+ config_file=config_file, pretrained_model_name=pretrained_model_name\n+ )\n+ if not checkpoint_file:\n+ checkpoint_file = default_checkpoint_file\n+ else:\n+ raise ValueError(f'{pretrained_model_name} is not supported')\n \n if checkpoint_file:\n- model.restore_from(checkpoint_file)\n- logging.info(f\"{pretrained_model_name} model restored from {checkpoint_file}\")\n+ model.restore_weights(restore_path=checkpoint_file)\n+ logging.info(f\"{pretrained_model_name} weights restored from {checkpoint_file}\")\n+\n return model\ndiff --git a/nemo/collections/nlp/modules/common/megatron/__init__.py b/nemo/collections/nlp/modules/common/megatron/__init__.py\nnew file mode 100644\n--- /dev/null\n+++ b/nemo/collections/nlp/modules/common/megatron/__init__.py\n@@ -0,0 +1,16 @@\n+# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+from nemo.collections.nlp.modules.common.megatron.megatron_bert import MegatronBertEncoder\n+from nemo.collections.nlp.modules.common.megatron.megatron_utils import get_megatron_checkpoint\ndiff --git a/nemo/collections/nlp/modules/common/megatron/megatron_bert.py b/nemo/collections/nlp/modules/common/megatron/megatron_bert.py\nnew file mode 100644\n--- /dev/null\n+++ b/nemo/collections/nlp/modules/common/megatron/megatron_bert.py\n@@ -0,0 +1,123 @@\n+# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n+# Copyright 2018 The Google AI Language Team Authors and\n+# The HuggingFace Inc. team.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+import os\n+\n+import torch\n+from megatron.initialize import initialize_megatron\n+from megatron.model.bert_model import bert_attention_mask_func, bert_extended_attention_mask, bert_position_ids\n+from megatron.model.language_model import get_language_model\n+from megatron.model.utils import init_method_normal, scaled_init_method_normal\n+from transformers import BertConfig\n+\n+from nemo.collections.nlp.modules.common.bert_module import BertModule\n+from nemo.core.classes import typecheck\n+from nemo.utils.decorators import experimental\n+\n+__all__ = ['MegatronBertEncoder']\n+\n+\n+@experimental\n+class MegatronBertEncoder(BertModule):\n+ \"\"\"\n+ MegatronBERT wraps around the Megatron Language model\n+ from https://github.com/NVIDIA/Megatron-LM\n+\n+ Args:\n+ config_file (str): path to model configuration file.\n+ vocab_file (str): path to vocabulary file.\n+ tokenizer_type (str): tokenizer type, currently only 'BertWordPieceLowerCase' supported.\n+ \"\"\"\n+\n+ def __init__(\n+ self,\n+ model_name,\n+ vocab_file,\n+ hidden_size=1024,\n+ num_attention_heads=16,\n+ num_layers=24,\n+ max_seq_length=512,\n+ tokenizer_type='BertWordPieceLowerCase',\n+ init_method_std=0.02,\n+ num_tokentypes=2,\n+ ):\n+\n+ super().__init__()\n+\n+ if not os.path.exists(vocab_file):\n+ raise ValueError(f'Vocab file not found at {vocab_file}')\n+\n+ megatron_args = {\n+ \"num_layers\": num_layers,\n+ \"hidden_size\": hidden_size,\n+ \"num_attention_heads\": num_attention_heads,\n+ \"max_position_embeddings\": max_seq_length,\n+ \"tokenizer_type\": tokenizer_type,\n+ \"vocab_file\": vocab_file,\n+ }\n+\n+ self.config = BertConfig(\n+ num_layers=num_layers,\n+ hidden_size=hidden_size,\n+ num_attention_heads=num_attention_heads,\n+ tokenizer_type=tokenizer_type,\n+ vocab_file=vocab_file,\n+ )\n+\n+ initialize_megatron(None, megatron_args, ignore_unknown_args=True)\n+ init_method = init_method_normal(init_method_std)\n+\n+ self.language_model, self._language_model_key = get_language_model(\n+ attention_mask_func=bert_attention_mask_func,\n+ num_tokentypes=num_tokentypes,\n+ add_pooler=False,\n+ init_method=init_method,\n+ scaled_init_method=scaled_init_method_normal(init_method_std, num_layers),\n+ )\n+\n+ self._hidden_size = self.language_model.hidden_size\n+\n+ @property\n+ def hidden_size(self):\n+ \"\"\"\n+ Property returning hidden size.\n+\n+ Returns:\n+ Hidden size.\n+ \"\"\"\n+ return self._hidden_size\n+\n+ @typecheck()\n+ def forward(self, input_ids, attention_mask, token_type_ids):\n+ extended_attention_mask = bert_extended_attention_mask(\n+ attention_mask, next(self.language_model.parameters()).dtype\n+ )\n+ position_ids = bert_position_ids(input_ids)\n+\n+ sequence_output = self.language_model(\n+ input_ids, position_ids, extended_attention_mask, tokentype_ids=token_type_ids\n+ )\n+ return sequence_output\n+\n+ def restore_weights(self, restore_path: str):\n+ \"\"\"Restores module/model's weights\"\"\"\n+ state_dict = torch.load(restore_path)\n+\n+ # to load from Megatron pretrained checkpoint\n+ if 'model' in state_dict:\n+ self.language_model.load_state_dict(state_dict['model'][self._language_model_key])\n+ else:\n+ self.load_state_dict(state_dict)\ndiff --git a/nemo/collections/nlp/modules/common/megatron/megatron_utils.py b/nemo/collections/nlp/modules/common/megatron/megatron_utils.py\nnew file mode 100644\n--- /dev/null\n+++ b/nemo/collections/nlp/modules/common/megatron/megatron_utils.py\n@@ -0,0 +1,160 @@\n+# Copyright 2020 NVIDIA. All Rights Reserved.\n+# Copyright 2020 The HuggingFace Inc. team.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+import os\n+from typing import List, Optional\n+\n+import torch\n+import wget\n+from transformers import TRANSFORMERS_CACHE, cached_path\n+\n+from nemo.collections.nlp.modules.common.megatron.megatron_bert import MegatronBertEncoder\n+\n+__all__ = [\n+ 'get_megatron_lm_model',\n+ 'get_megatron_lm_models_list',\n+ 'get_megatron_checkpoint',\n+ 'is_lower_cased_megatron',\n+]\n+\n+\n+MEGATRON_CACHE = os.path.join(os.path.dirname(str(TRANSFORMERS_CACHE)), 'megatron')\n+\n+CONFIGS = {'345m': {\"hidden-size\": 1024, \"num-attention-heads\": 16, \"num-layers\": 24, \"max-seq-length\": 512}}\n+\n+MEGATRON_CONFIG_MAP = {\n+ 'megatron-bert-345m-uncased': {\n+ 'config': CONFIGS['345m'],\n+ 'checkpoint': 'https://api.ngc.nvidia.com/v2/models/nvidia/megatron_bert_345m/versions/v0.0/files/release/mp_rank_00/model_optim_rng.pt',\n+ 'vocab': 'https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt',\n+ 'do_lower_case': True,\n+ },\n+ 'megatron-bert-345m-cased': {\n+ 'config': CONFIGS['345m'],\n+ 'checkpoint': 'https://api.ngc.nvidia.com/v2/models/nvidia/megatron_bert_345m/versions/v0.1_cased/files/release/mp_rank_00/model_optim_rng.pt',\n+ 'vocab': 'https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txt',\n+ 'do_lower_case': False,\n+ },\n+ 'megatron-bert-uncased': {\n+ 'config': None,\n+ 'checkpoint': None,\n+ 'vocab': 'https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt',\n+ 'do_lower_case': True,\n+ },\n+ 'megatron-bert-cased': {\n+ 'config': None,\n+ 'vocab': 'https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txt',\n+ 'do_lower_case': False,\n+ },\n+}\n+\n+\n+def get_megatron_lm_model(pretrained_model_name: str, config_file: Optional[str] = None):\n+ '''\n+ Returns the dict of special tokens associated with the model.\n+ Args:\n+ pretrained_mode_name ('str'): name of the pretrained model from the hugging face list,\n+ for example: bert-base-cased\n+ config_file: path to model configuration file.\n+ '''\n+\n+ if pretrained_model_name == 'megatron-bert-cased' or pretrained_model_name == 'megatron-bert-uncased':\n+ if not (config_file):\n+ raise ValueError(f'Config file is required for {pretrained_model_name}')\n+\n+ config = get_megatron_config(pretrained_model_name)\n+ if config_file:\n+ with open(config_file) as f:\n+ config = json.load(f)\n+\n+ checkpoint_file = get_megatron_checkpoint(pretrained_model_name)\n+\n+ vocab = get_megatron_vocab_file(pretrained_model_name)\n+\n+ model = MegatronBertEncoder(\n+ model_name=pretrained_model_name,\n+ vocab_file=vocab,\n+ hidden_size=config['hidden-size'],\n+ num_attention_heads=config['num-attention-heads'],\n+ num_layers=config['num-layers'],\n+ max_seq_length=config['max-seq-length'],\n+ )\n+\n+ return model, checkpoint_file\n+\n+\n+def get_megatron_lm_models_list() -> List[str]:\n+ '''\n+ Return the list of support Megatron models\n+ '''\n+ return list(MEGATRON_CONFIG_MAP.keys())\n+\n+\n+def get_megatron_config(pretrained_model_name):\n+ '''\n+ Returns model config file\n+ Args:\n+ pretrained_model_name (str): pretrained model name\n+ Returns:\n+ config (dict): contains model configuration: number of hidden layers, number of attention heads, etc\n+ '''\n+ return MEGATRON_CONFIG_MAP[pretrained_model_name]['config']\n+\n+\n+def get_megatron_vocab_file(pretrained_model_name):\n+ '''\n+ Gets vocabulary file from cache or downloads it\n+ Args:\n+ pretrained_model_name (str): pretrained model name\n+ Returns:\n+ path (str): path to the vocab file \n+ '''\n+ url = MEGATRON_CONFIG_MAP[pretrained_model_name]['vocab']\n+ path = cached_path(url, cache_dir=MEGATRON_CACHE)\n+ return path\n+\n+\n+def get_megatron_checkpoint(pretrained_model_name):\n+ '''\n+ Gets checkpoint file from cache or downloads it\n+ Args:\n+ pretrained_model_name (str): pretrained model name\n+ Returns:\n+ path (str): path to model checkpoint\n+ '''\n+ url = MEGATRON_CONFIG_MAP[pretrained_model_name]['checkpoint']\n+ path = os.path.join(MEGATRON_CACHE, pretrained_model_name)\n+\n+ if not os.path.exists(path):\n+ master_device = not torch.distributed.is_initialized() or torch.distributed.get_rank() == 0\n+ if not os.path.exists(path):\n+ if master_device:\n+ wget.download(url, path)\n+ # wait until the master process downloads the file and writes it to the cache dir\n+ if torch.distributed.is_initialized():\n+ torch.distributed.barrier()\n+\n+ return path\n+\n+\n+def is_lower_cased_megatron(pretrained_model_name):\n+ '''\n+ Returns if the megatron is cased or uncased\n+ Args:\n+ pretrained_model_name (str): pretrained model name\n+ Returns:\n+ do_lower_cased (bool): whether the model uses lower cased data\n+ '''\n+ return MEGATRON_CONFIG_MAP[pretrained_model_name]['do_lower_case']\n", + "test_patch": "diff --git a/tests/collections/nlp/test_megatron.py b/tests/collections/nlp/test_megatron.py\nnew file mode 100644\n--- /dev/null\n+++ b/tests/collections/nlp/test_megatron.py\n@@ -0,0 +1,38 @@\n+# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+from unittest import TestCase\n+\n+import pytest\n+\n+import nemo.collections.nlp as nemo_nlp\n+\n+\n+class TestMegatron(TestCase):\n+ @pytest.mark.unit\n+ def test_list_pretrained_models(self):\n+ pretrained_lm_models = nemo_nlp.modules.get_pretrained_lm_models_list()\n+ self.assertTrue(len(pretrained_lm_models) > 0)\n+\n+ @pytest.mark.unit\n+ def test_get_pretrained_bert_345m_uncased_model(self):\n+ model = nemo_nlp.modules.get_pretrained_lm_model('megatron-bert-345m-uncased')\n+ assert isinstance(model, nemo_nlp.modules.MegatronBertEncoder)\n+\n+\n+# With Megatron 1.1, still fails\n+# @pytest.mark.unit\n+# def test_get_pretrained_bert_345m_cased_model(self):\n+# model = nemo_nlp.modules.get_pretrained_lm_model('megatron-bert-345m-cased')\n+# assert isinstance(model, nemo_nlp.modules.MegatronBertEncoder)\n", + "problem_statement": "Unidecode module error when unit-testing\nAfter installing dependencies, including apex then the reinstall.sh script, but upon trying out the unit tests, I received an error for missing module *unidecode*. A simple `pip install unidecode` solved this, with all tests subsequently running successfully. The error prior to successful tests is attached, and computer details for completeness below. \r\n\r\nIs this issue something to be ameliorated in the install procedure or setup file?\r\n\r\n\r\nCentOS Linux release 7.5.1804 (Core)\r\nLinux version 3.10.0-862.14.4.el7.x86_64 (mockbuild@kbuilder.bsys.centos.org) (gcc version 4.8.5 20150623 (Red Hat 4.8.5-28) (GCC) ) #1 SMP Wed Sep 26 15:12:11 UTC 2018\r\n \r\n[Unidecode_Error.txt](https://github.com/moconnor725/NeMo/files/3543309/Unidecode_Error.txt)\r\n\n", + "hints_text": "which Python version are you using? I thought Python 3.6 and 3.7 come with unicode.\r\nAnother difference with our specified requirements is that you use CentOS instead of Ubuntu, but I doubt that it the source of this particular issue.\nI am using Python 3.6.5, and yes, unfortunately the setup is CentOS :( \r\nI just made a virtualenv, then ran the reinstall script which should have installed things appropriately via the setup.py script, right? That is, after installing PyTorch and apex of course.\nyes, vitualenv should do the trick. But again, we only tested on Ubutntu. \r\nA more stable route might be using our latest Pytorch docker container from https://ngc.nvidia.com ", + "created_at": "2020-07-22T09:49:49Z", + "version": "1.0" + }, + { + "repo": "NVIDIA/NeMo", + "pull_number": 1323, + "instance_id": "NVIDIA__NeMo-1323", + "issue_numbers": [ + "1297" + ], + "base_commit": "5cf042856bf718d27233a7538e0b094ce576d5c4", + "patch": "diff --git a/examples/asr/speech_to_text_infer.py b/examples/asr/speech_to_text_infer.py\n--- a/examples/asr/speech_to_text_infer.py\n+++ b/examples/asr/speech_to_text_infer.py\n@@ -56,12 +56,10 @@ def main():\n \n if args.asr_model.endswith('.nemo'):\n logging.info(f\"Using local ASR model from {args.asr_model}\")\n- # TODO: Remove strict, when lightning has persistent parameter support for add_state()\n- asr_model = EncDecCTCModel.restore_from(restore_path=args.asr_model, strict=False)\n+ asr_model = EncDecCTCModel.restore_from(restore_path=args.asr_model)\n else:\n logging.info(f\"Using NGC cloud ASR model {args.asr_model}\")\n- # TODO: Remove strict, when lightning has persistent parameter support for add_state()\n- asr_model = EncDecCTCModel.from_pretrained(model_name=args.asr_model, strict=False)\n+ asr_model = EncDecCTCModel.from_pretrained(model_name=args.asr_model)\n asr_model.setup_test_data(\n test_data_config={\n 'sample_rate': 16000,\ndiff --git a/examples/nlp/token_classification/punctuation_capitalization.py b/examples/nlp/token_classification/punctuation_capitalization.py\n--- a/examples/nlp/token_classification/punctuation_capitalization.py\n+++ b/examples/nlp/token_classification/punctuation_capitalization.py\n@@ -49,8 +49,7 @@ def main(cfg: DictConfig) -> None:\n model = PunctuationCapitalizationModel(cfg.model, trainer=trainer)\n else:\n logging.info(f'Loading pretrained model {cfg.pretrained_model}')\n- # TODO: Remove strict, when lightning has persistent parameter support for add_state()\n- model = PunctuationCapitalizationModel.from_pretrained(cfg.pretrained_model, strict=False)\n+ model = PunctuationCapitalizationModel.from_pretrained(cfg.pretrained_model)\n data_dir = cfg.model.dataset.get('data_dir', None)\n if data_dir:\n # we can also do finetunining of the pretrained model but it will require\ndiff --git a/examples/nlp/token_classification/token_classification.py b/examples/nlp/token_classification/token_classification.py\n--- a/examples/nlp/token_classification/token_classification.py\n+++ b/examples/nlp/token_classification/token_classification.py\n@@ -85,8 +85,7 @@ def main(cfg: DictConfig) -> None:\n model = TokenClassificationModel(cfg.model, trainer=trainer)\n else:\n logging.info(f'Loading pretrained model {cfg.pretrained_model}')\n- # TODO: Remove strict, when lightning has persistent parameter support for add_state()\n- model = TokenClassificationModel.from_pretrained(cfg.pretrained_model, strict=False)\n+ model = TokenClassificationModel.from_pretrained(cfg.pretrained_model)\n \n data_dir = cfg.model.dataset.get('data_dir', None)\n if data_dir:\ndiff --git a/nemo/collections/asr/metrics/wer.py b/nemo/collections/asr/metrics/wer.py\n--- a/nemo/collections/asr/metrics/wer.py\n+++ b/nemo/collections/asr/metrics/wer.py\n@@ -111,8 +111,8 @@ def __init__(\n self.ctc_decode = ctc_decode\n self.log_prediction = log_prediction\n \n- self.add_state(\"scores\", default=torch.tensor(0), dist_reduce_fx='sum')\n- self.add_state(\"words\", default=torch.tensor(0), dist_reduce_fx='sum')\n+ self.add_state(\"scores\", default=torch.tensor(0), dist_reduce_fx='sum', persistent=False)\n+ self.add_state(\"words\", default=torch.tensor(0), dist_reduce_fx='sum', persistent=False)\n \n def ctc_decoder_predictions_tensor(self, predictions: torch.Tensor) -> List[str]:\n \"\"\"\ndiff --git a/nemo/collections/asr/metrics/wer_bpe.py b/nemo/collections/asr/metrics/wer_bpe.py\n--- a/nemo/collections/asr/metrics/wer_bpe.py\n+++ b/nemo/collections/asr/metrics/wer_bpe.py\n@@ -74,8 +74,8 @@ def __init__(\n self.ctc_decode = ctc_decode\n self.log_prediction = log_prediction\n \n- self.add_state(\"scores\", default=torch.tensor(0), dist_reduce_fx='sum')\n- self.add_state(\"words\", default=torch.tensor(0), dist_reduce_fx='sum')\n+ self.add_state(\"scores\", default=torch.tensor(0), dist_reduce_fx='sum', persistent=False)\n+ self.add_state(\"words\", default=torch.tensor(0), dist_reduce_fx='sum', persistent=False)\n \n def ctc_decoder_predictions_tensor(self, predictions: torch.Tensor) -> List[str]:\n \"\"\"\ndiff --git a/nemo/collections/common/metrics/classification_accuracy.py b/nemo/collections/common/metrics/classification_accuracy.py\n--- a/nemo/collections/common/metrics/classification_accuracy.py\n+++ b/nemo/collections/common/metrics/classification_accuracy.py\n@@ -63,8 +63,10 @@ def __init__(self, top_k=None, dist_sync_on_step=False):\n top_k = [1]\n \n self.top_k = top_k\n- self.add_state(\"correct_counts_k\", default=torch.zeros(len(self.top_k)), dist_reduce_fx='sum')\n- self.add_state(\"total_counts_k\", default=torch.zeros(len(self.top_k)), dist_reduce_fx='sum')\n+ self.add_state(\n+ \"correct_counts_k\", default=torch.zeros(len(self.top_k)), dist_reduce_fx='sum', persistent=False\n+ )\n+ self.add_state(\"total_counts_k\", default=torch.zeros(len(self.top_k)), dist_reduce_fx='sum', persistent=False)\n \n def update(self, logits: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:\n with torch.no_grad():\ndiff --git a/nemo/collections/nlp/metrics/classification_report.py b/nemo/collections/nlp/metrics/classification_report.py\n--- a/nemo/collections/nlp/metrics/classification_report.py\n+++ b/nemo/collections/nlp/metrics/classification_report.py\n@@ -76,10 +76,12 @@ def __init__(\n self.ids_to_labels = None\n self.mode = mode\n \n- self.add_state(\"tp\", default=torch.zeros(num_classes), dist_reduce_fx='sum')\n- self.add_state(\"fn\", default=torch.zeros(num_classes), dist_reduce_fx='sum')\n- self.add_state(\"fp\", default=torch.zeros(num_classes), dist_reduce_fx='sum')\n- self.add_state(\"num_examples_per_class\", default=torch.zeros(num_classes), dist_reduce_fx='sum')\n+ self.add_state(\"tp\", default=torch.zeros(num_classes), dist_reduce_fx='sum', persistent=False)\n+ self.add_state(\"fn\", default=torch.zeros(num_classes), dist_reduce_fx='sum', persistent=False)\n+ self.add_state(\"fp\", default=torch.zeros(num_classes), dist_reduce_fx='sum', persistent=False)\n+ self.add_state(\n+ \"num_examples_per_class\", default=torch.zeros(num_classes), dist_reduce_fx='sum', persistent=False\n+ )\n \n def update(self, predictions: torch.Tensor, labels: torch.Tensor):\n TP = []\ndiff --git a/nemo/collections/nlp/metrics/perplexity.py b/nemo/collections/nlp/metrics/perplexity.py\n--- a/nemo/collections/nlp/metrics/perplexity.py\n+++ b/nemo/collections/nlp/metrics/perplexity.py\n@@ -29,7 +29,7 @@ class Perplexity(Metric):\n \n def __init__(self, dist_sync_on_step=False):\n super().__init__(dist_sync_on_step=dist_sync_on_step)\n- self.add_state('perplexity', default=torch.tensor(0), dist_reduce_fx='mean')\n+ self.add_state('perplexity', default=torch.tensor(0), dist_reduce_fx='mean', persistent=False)\n \n def update(self, loss: torch.Tensor):\n self.perplexity = torch.exp(loss)\n", + "test_patch": "diff --git a/examples/tts/test_tts_infer.py b/examples/tts/test_tts_infer.py\n--- a/examples/tts/test_tts_infer.py\n+++ b/examples/tts/test_tts_infer.py\n@@ -75,8 +75,7 @@ def main():\n logging.set_verbosity(logging.DEBUG)\n \n logging.info(f\"Using NGC cloud ASR model {args.asr_model}\")\n- # TODO: Remove strict, when lightning has persistent parameter support for add_state()\n- asr_model = EncDecCTCModel.from_pretrained(model_name=args.asr_model, strict=False)\n+ asr_model = EncDecCTCModel.from_pretrained(model_name=args.asr_model)\n logging.info(f\"Using NGC cloud TTS Spectrogram Generator model {args.tts_model_spec}\")\n tts_model_spec = SpectrogramGenerator.from_pretrained(model_name=args.tts_model_spec)\n logging.info(f\"Using NGC cloud TTS Vocoder model {args.tts_model_vocoder}\")\n", + "problem_statement": "Loading NLP and ASR models might result in `Missing key(s) in state_dict` error\n**Describe the bug**\r\n\r\nAfter #1278 is merged, any model that uses Metrics (WERBPE, WER, TopKClassificationAccuracy, ClassificationReport, Perplexity) might throw an error like:\r\n```\r\nRuntimeError: Error(s) in loading state_dict for PunctuationCapitalizationModel:\r\n\r\n\tMissing key(s) in state_dict: \"punct_class_report.tp\", \"punct_class_report.fn\", \"punct_class_report.fp\", \"capit_class_report.tp\", \"capit_class_report.fn\", \"capit_class_report.fp\". \r\n```\r\n\r\n**Steps/Code to reproduce bug**\r\n\r\nN/A\r\n\r\n**Expected behavior**\r\n\r\nN/A\r\n\r\n**Environment overview (please complete the following information)**\r\n\r\nN/A\r\n\r\n**Environment details**\r\n\r\nN/A\r\n\r\n**Additional context**\r\n\r\nThe current work-around is to pass strict=False to either\r\nNeMo's Model.from_pretrained(..., strict=False)\r\nNeMo's ModelPT.load_from_checkpoint(..., strict=False)\r\nLightnings's LightningModule.load_from_checkpoint(..., strict=False)\r\nTorch's Module.load_state_dict(..., strict=False)\r\n\n", + "hints_text": "", + "created_at": "2020-10-21T20:01:26Z", + "version": "1.0" + }, + { + "repo": "NVIDIA/NeMo", + "pull_number": 3159, + "instance_id": "NVIDIA__NeMo-3159", + "issue_numbers": [ + "3125" + ], + "base_commit": "c607061264713c9f4c35d1fbc5afaaf41471317e", + "patch": "diff --git a/examples/nlp/token_classification/data/create_punctuation_capitalization_tarred_dataset.py b/examples/nlp/token_classification/data/create_punctuation_capitalization_tarred_dataset.py\nnew file mode 100644\n--- /dev/null\n+++ b/examples/nlp/token_classification/data/create_punctuation_capitalization_tarred_dataset.py\n@@ -0,0 +1,331 @@\n+# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+import argparse\n+import multiprocessing as mp\n+from pathlib import Path\n+\n+from nemo.collections.nlp.data.token_classification.punctuation_capitalization_tarred_dataset import (\n+ DEFAULT_CAPIT_LABEL_VOCAB_FILE_NAME,\n+ DEFAULT_PUNCT_LABEL_VOCAB_FILE_NAME,\n+ METADATA_CAPIT_LABEL_VOCAB_KEY,\n+ METADATA_PUNCT_LABEL_VOCAB_KEY,\n+ build_label_ids_from_list_of_labels,\n+ check_labels_for_being_unique_before_building_label_ids,\n+ create_tarred_dataset,\n+)\n+\n+\n+\"\"\"\n+A tarred dataset allows to train on large amounts without storing it all into memory simultaneously. In case of\n+punctuation and capitalization model, tarred dataset is a directory which contains metadata file, tar files with\n+batches, punct_label_vocab.csv and capit_label_vocab.csv files.\n+\n+A metadata file is a JSON file with 4 fields: 'num_batches', 'tar_files', 'punct_label_vocab_file',\n+'capit_label_vocab_file'. 'num_batches' (int) is a total number of batches in tarred dataset. 'tar_files' is a list of\n+paths to tar files relative to directory containing the metadata file. 'punct_label_vocab_file' and\n+'capit_label_vocab_file' are paths to .csv files containing all unique punctuation and capitalization labels. Each\n+label in these files is written in a separate line. The first labels in both files are equal and serve for padding and\n+as neutral labels.\n+\n+Every tar file contains objects written using `webdataset.TarWriter`. Each object is a dictionary with two items:\n+'__key__' and 'batch.pyd'. '__key__' is a name of a batch and 'batch.pyd' is a pickled dictionary which contains\n+'input_ids', 'subtokens_mask', 'punct_labels', 'capit_labels'. 'input_ids' is an array containing ids of source tokens,\n+'subtokens_mask' is a boolean array showing first tokens in words, 'punct_labels' and 'capit_labels' are arrays with\n+ids of labels. Metadata file should be passed to constructor of\n+`nemo.collections.nlp.data.token_classification.PunctuationCapitalizationTarredDataset` and the instance of \n+the class will handle iteration and constructing masks and token types for BERT model.\n+\n+Example of usage:\n+\n+python create_punctuation_capitalization_tarred_dataset.py \\\n+ --text \\\n+ --labels \\\n+ --output_dir \\\n+ --lines_per_dataset_fragment 10000 \\\n+ --tokens_in_batch 8000 \\\n+ --num_batches_per_tarfile 5 \\\n+ --tokenizer_name char \\\n+ --vocab_file \n+\"\"\"\n+\n+\n+def get_args() -> argparse.Namespace:\n+ parser = argparse.ArgumentParser(\n+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n+ description=f\"A tarred dataset allows to train on large amounts without storing it all into memory \"\n+ f\"simultaneously. In case of punctuation and capitalization model, tarred dataset is a directory which \"\n+ f\"contains metadata file, tar files with batches, {DEFAULT_PUNCT_LABEL_VOCAB_FILE_NAME} and \"\n+ f\"{DEFAULT_CAPIT_LABEL_VOCAB_FILE_NAME} files. A metadata file is a JSON file with 4 fields: 'num_batches', \"\n+ f\"'tar_files', '{METADATA_PUNCT_LABEL_VOCAB_KEY}', '{METADATA_CAPIT_LABEL_VOCAB_KEY}'. 'num_batches' (int) is \"\n+ f\"a total number of batches in tarred dataset. 'tar_files' is a list of paths to tar files relative \"\n+ f\"to directory containing the metadata file. '{METADATA_PUNCT_LABEL_VOCAB_KEY}' and \"\n+ f\"'{METADATA_CAPIT_LABEL_VOCAB_KEY}' are paths to .csv files containing all unique punctuation and \"\n+ f\"capitalization labels. Each label in these files is written in a separate line. The first labels in both \"\n+ f\"files are equal and serve for padding and as neutral labels. Every tar file contains objects written \"\n+ f\"using `webdataset.TarWriter`. Each object is a dictionary with two items: '__key__' and 'batch.pyd'. \"\n+ f\"'__key__' is a name of a batch and 'batch.pyd' is a pickled dictionary which contains 'input_ids', \"\n+ f\"'subtokens_mask', 'punct_labels', 'capit_labels'. 'input_ids' is an array containing ids of source tokens, \"\n+ f\"'subtokens_mask' is a boolean array showing first tokens in words, 'punct_labels' and 'capit_labels' are \"\n+ f\"arrays with ids of labels. Metadata file should be passed to constructor of \"\n+ \"`nemo.collections.nlp.data.token_classification.PunctuationCapitalizationTarredDataset` and the instance of \"\n+ \"the class will handle iteration and constructing masks and token types for BERT model.\",\n+ )\n+ parser.add_argument(\n+ \"--text\",\n+ \"-t\",\n+ help=\"Path to source lowercased text without punctuation. Number of lines in `--text` file has to be equal \"\n+ \"to number of lines in `--labels` file.\",\n+ type=Path,\n+ required=True,\n+ )\n+ parser.add_argument(\n+ \"--labels\",\n+ \"-L\",\n+ type=Path,\n+ required=True,\n+ help=\"Path to file with labels in the format described here \"\n+ \"https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/main/nlp/punctuation_and_capitalization.html#\"\n+ \"nemo-data-format . Number of lines in `--labels` file has to be equal to the number of lines in `--text` \"\n+ \"file.\",\n+ )\n+ parser.add_argument(\n+ \"--output_dir\",\n+ \"-o\",\n+ type=Path,\n+ required=True,\n+ help=\"Path to directory where .tar files, metadata file, label id files are stored.\",\n+ )\n+ parser.add_argument(\n+ \"--max_seq_length\",\n+ \"-s\",\n+ type=int,\n+ default=512,\n+ help=\"Maximum number of subtokens in an input sequence. A source sequence which contain too many subtokens are \"\n+ \"clipped to `--max_seq_length - 2` subtokens and then [CLS] token is prepended to the clipped sequence and \"\n+ \"[SEP] token is appended to the clipped sequence. The clipping is performed via removal of subtokens in the \"\n+ \"end of a source sequence.\",\n+ )\n+ parser.add_argument(\n+ \"--tokens_in_batch\",\n+ \"-b\",\n+ type=int,\n+ default=15000,\n+ help=\"Maximum number of tokens in a batch including [CLS], [SEP], [UNK], and [PAD] tokens. Before packing into \"\n+ \"batches source sequences are sorted by number of tokens in order to reduce number of pad tokens. So the \"\n+ \"number of sequences in a batch may be different.\",\n+ )\n+ parser.add_argument(\n+ \"--lines_per_dataset_fragment\",\n+ type=int,\n+ default=10 ** 6,\n+ help=\"A number of lines processed by one worker during creation of tarred dataset. A worker tokenizes \"\n+ \"`--lines_per_dataset_fragment` lines and keeps in RAM tokenized text labels before packing them into \"\n+ \"batches. Reducing `--lines_per_dataset_fragment` leads to reducing of the amount of memory required by this \"\n+ \"script.\",\n+ )\n+ parser.add_argument(\n+ \"--num_batches_per_tarfile\",\n+ type=int,\n+ default=1000,\n+ help=\"A number of batches saved in a tar file. If you increase `--num_batches_per_tarfile`, then there will \"\n+ \"be less tar files in the dataset. There cannot be less then `--num_batches_per_tarfile` batches in a tar \"\n+ \"file, and all excess batches are removed. Maximum number of discarded batches is \"\n+ \"`--num_batches_per_tarfile - 1`.\",\n+ )\n+ parser.add_argument(\n+ \"--tokenizer_name\",\n+ \"-T\",\n+ default=\"bert-base-uncased\",\n+ help=\"Name of the tokenizer used for tokenization of source sequences. Possible options are 'sentencepiece', \"\n+ \"'word', 'char', HuggingFace tokenizers. For more options see function \"\n+ \"`nemo.collections.nlp.modules.common.get_tokenizer`. The tokenizer has to have properties `cls_id`, \"\n+ \"`pad_id`, `sep_id`, `unk_id`.\",\n+ )\n+ parser.add_argument(\n+ \"--tokenizer_model\", \"-m\", type=Path, help=\"Path to tokenizer model required for 'sentencepiece' tokenizer.\"\n+ )\n+ parser.add_argument(\n+ \"--vocab_file\",\n+ \"-v\",\n+ type=Path,\n+ help=\"Path to vocabulary file which can be used in 'word', 'char', and HuggingFace tokenizers.\",\n+ )\n+ parser.add_argument(\n+ \"--merges_file\", \"-M\", type=Path, help=\"Path to merges file which can be used in HuggingFace tokenizers.\"\n+ )\n+ parser.add_argument(\n+ \"--special_token_names\",\n+ \"-n\",\n+ nargs=\"+\",\n+ help=\"Names of special tokens which may be passed to constructors of 'char', 'word', 'sentencepiece', and \"\n+ \"HuggingFace tokenizers.\",\n+ )\n+ parser.add_argument(\n+ \"--special_token_values\",\n+ \"-V\",\n+ nargs=\"+\",\n+ help=\"Values of special tokens which may be passed to constructors of 'char', 'word', 'sentencepiece', and \"\n+ \"HuggingFace tokenizers.\",\n+ )\n+ parser.add_argument(\n+ \"--use_fast_tokenizer\", \"-f\", action=\"store_true\", help=\"Whether to use fast HuggingFace tokenizer.\"\n+ )\n+ parser.add_argument(\n+ \"--pad_label\",\n+ \"-P\",\n+ default='O',\n+ help=\"Pad label both for punctuation and capitalization. This label is also is used for marking words which \"\n+ \"do not need punctuation and capitalization. It is also a neutral label used for marking words which do \"\n+ \"not require punctuation and capitalization.\",\n+ )\n+ punct = parser.add_mutually_exclusive_group(required=False)\n+ punct.add_argument(\n+ \"--punct_labels\",\n+ \"-p\",\n+ nargs=\"+\",\n+ help=\"All punctuation labels EXCEPT PAD LABEL. Punctuation labels are strings separated by spaces. \"\n+ \"Alternatively you can use parameter `--punct_label_vocab_file`. If none of parameters `--punct_labels` \"\n+ \"and `--punct_label_vocab_file` are provided, then punctuation label ids will be inferred from `--labels` \"\n+ \"file.\",\n+ )\n+ punct.add_argument(\n+ \"--punct_label_vocab_file\",\n+ type=Path,\n+ help=\"A path to file with punctuation labels. These labels include pad label. Pad label has to be the first \"\n+ \"label in the file. Each label is written on separate line. Alternatively you can use `--punct_labels` \"\n+ \"parameter. If none of parameters `--punct_labels` and `--punct_label_vocab_file` are provided, then \"\n+ \"punctuation label ids will be inferred from `--labels` file.\",\n+ )\n+ capit = parser.add_mutually_exclusive_group(required=False)\n+ capit.add_argument(\n+ \"--capit_labels\",\n+ \"-c\",\n+ nargs=\"+\",\n+ help=\"All capitalization labels EXCEPT PAD LABEL. Capitalization labels are strings separated by spaces. \"\n+ \"Alternatively you can use parameter `--capit_label_vocab_file`. If none of parameters `--capit_labels` \"\n+ \"and `--capit_label_vocab_file` are provided, then capitalization label ids will be inferred from `--labels` \"\n+ \"file.\",\n+ )\n+ capit.add_argument(\n+ \"--capit_label_vocab_file\",\n+ type=Path,\n+ help=\"A path to file with capitalization labels. These labels include pad label. Pad label has to be the \"\n+ \"first label in the file. Each label is written on separate line. Alternatively you can use `--capit_labels` \"\n+ \"parameter. If none of parameters `--capit_labels` and `--capit_label_vocab_file` are provided, then \"\n+ \"capitalization label ids will be inferred from `--labels` file.\",\n+ )\n+ parser.add_argument(\n+ \"--tar_file_prefix\",\n+ \"-x\",\n+ default=\"punctuation_capitalization\",\n+ help=\"A string from which tar file names start.\",\n+ )\n+ parser.add_argument(\n+ \"--n_jobs\",\n+ \"-j\",\n+ type=int,\n+ default=mp.cpu_count(),\n+ help=\"Number of workers for creating tarred dataset. By default it is equal to the number of CPU cores.\",\n+ )\n+ args = parser.parse_args()\n+ for name in [\n+ \"text\",\n+ \"labels\",\n+ \"output_dir\",\n+ \"tokenizer_model\",\n+ \"vocab_file\",\n+ \"merges_file\",\n+ \"punct_label_vocab_file\",\n+ \"capit_label_vocab_file\",\n+ ]:\n+ if getattr(args, name) is not None:\n+ setattr(args, name, getattr(args, name).expanduser())\n+ if args.special_token_names is not None or args.special_token_values is not None:\n+ if args.special_token_names is None:\n+ parser.error(\n+ \"If you provide parameter `--special_token_values` you have to provide parameter \"\n+ \"`--special_token_names`.\"\n+ )\n+ if args.special_token_values is None:\n+ parser.error(\n+ \"If you provide parameter `--special_token_names` you have to provide parameter \"\n+ \"`--special_token_values`.\"\n+ )\n+ if len(args.special_token_names) != len(args.special_token_values):\n+ parser.error(\n+ f\"Parameters `--special_token_names` and `--special_token_values` have to have equal number of values \"\n+ f\"whereas parameter `--special_token_names` has {len(args.special_token_names)} values and parameter \"\n+ f\"`--special_token_values` has {len(args.special_token_values)} values.\"\n+ )\n+ if len(set(args.special_token_names)) != len(args.special_token_names):\n+ for i in range(len(args.special_token_names) - 1):\n+ if args.special_token_names[i] in args.special_token_names[i + 1 :]:\n+ parser.error(\n+ f\"Values of parameter `--special_token_names` has to be unique. Found duplicate value \"\n+ f\"'{args.special_token_names[i]}'.\"\n+ )\n+ if args.punct_labels is not None:\n+ check_labels_for_being_unique_before_building_label_ids(\n+ args.pad_label, args.punct_labels, '--pad_label', '--punct_labels', parser.error\n+ )\n+ check_labels_for_being_unique_before_building_label_ids(\n+ args.pad_label, args.capit_labels, '--pad_label', '--capit_labels', parser.error\n+ )\n+ return args\n+\n+\n+def main() -> None:\n+ args = get_args()\n+ if args.special_token_names is None:\n+ special_tokens = None\n+ else:\n+ special_tokens = dict(zip(args.special_token_names, args.special_token_values))\n+\n+ if args.punct_labels is not None:\n+ punct_label_ids = build_label_ids_from_list_of_labels(args.pad_label, args.punct_labels)\n+ else:\n+ punct_label_ids = None\n+\n+ if args.capit_labels is not None:\n+ capit_label_ids = build_label_ids_from_list_of_labels(args.pad_label, args.capit_labels)\n+ else:\n+ capit_label_ids = None\n+\n+ create_tarred_dataset(\n+ args.text,\n+ args.labels,\n+ args.output_dir,\n+ args.max_seq_length,\n+ args.tokens_in_batch,\n+ args.lines_per_dataset_fragment,\n+ args.num_batches_per_tarfile,\n+ args.tokenizer_name,\n+ tokenizer_model=args.tokenizer_model,\n+ vocab_file=args.vocab_file,\n+ merges_file=args.merges_file,\n+ special_tokens=special_tokens,\n+ use_fast_tokenizer=args.use_fast_tokenizer,\n+ pad_label=args.pad_label,\n+ punct_label_ids=punct_label_ids,\n+ capit_label_ids=capit_label_ids,\n+ punct_label_vocab_file=args.punct_label_vocab_file,\n+ capit_label_vocab_file=args.capit_label_vocab_file,\n+ tar_file_prefix=args.tar_file_prefix,\n+ n_jobs=args.n_jobs,\n+ )\n+\n+\n+if __name__ == \"__main__\":\n+ main()\ndiff --git a/examples/nlp/token_classification/punctuate_capitalize_infer.py b/examples/nlp/token_classification/punctuate_capitalize_infer.py\n--- a/examples/nlp/token_classification/punctuate_capitalize_infer.py\n+++ b/examples/nlp/token_classification/punctuate_capitalize_infer.py\n@@ -15,6 +15,7 @@\n import argparse\n import json\n from pathlib import Path\n+from typing import Dict, List, Union\n \n import torch.cuda\n \n@@ -40,7 +41,7 @@\n \"\"\"\n \n \n-def get_args():\n+def get_args() -> argparse.Namespace:\n default_model_parameter = \"pretrained_name\"\n default_model = \"punctuation_en_bert\"\n parser = argparse.ArgumentParser(\n@@ -166,7 +167,7 @@ def get_args():\n return args\n \n \n-def load_manifest(manifest: Path):\n+def load_manifest(manifest: Path) -> List[Dict[str, Union[str, float]]]:\n result = []\n with manifest.open() as f:\n for i, line in enumerate(f):\n@@ -175,7 +176,7 @@ def load_manifest(manifest: Path):\n return result\n \n \n-def main():\n+def main() -> None:\n args = get_args()\n if args.pretrained_name is None:\n model = PunctuationCapitalizationModel.restore_from(args.model_path)\n@@ -188,7 +189,6 @@ def main():\n model = model.cpu()\n else:\n model = model.to(args.device)\n- model = model.cpu()\n if args.input_manifest is None:\n texts = []\n with args.input_text.open() as f:\ndiff --git a/examples/nlp/token_classification/punctuation_capitalization_evaluate.py b/examples/nlp/token_classification/punctuation_capitalization_evaluate.py\ndeleted file mode 100644\n--- a/examples/nlp/token_classification/punctuation_capitalization_evaluate.py\n+++ /dev/null\n@@ -1,121 +0,0 @@\n-# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.\n-#\n-# Licensed under the Apache License, Version 2.0 (the \"License\");\n-# you may not use this file except in compliance with the License.\n-# You may obtain a copy of the License at\n-#\n-# http://www.apache.org/licenses/LICENSE-2.0\n-#\n-# Unless required by applicable law or agreed to in writing, software\n-# distributed under the License is distributed on an \"AS IS\" BASIS,\n-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-# See the License for the specific language governing permissions and\n-# limitations under the License.\n-\n-import os\n-\n-import pytorch_lightning as pl\n-from omegaconf import DictConfig\n-\n-from nemo.collections.nlp.models import PunctuationCapitalizationModel\n-from nemo.core.config import hydra_runner\n-from nemo.utils import logging\n-from nemo.utils.exp_manager import exp_manager\n-\n-\n-\"\"\"\n-This script shows how to perform evaluation and runs inference of a few examples.\n-\n-More details on the task and data format could be found in tutorials/nlp/Punctuation_and_Capitalization.ipynb\n-\n-*** Setting the configs ***\n-\n-This script uses the `/examples/nlp/token_classification/conf/punctuation_capitalization_config.yaml` config file\n-by default. You may update the config file from the file directly. \n-The other option is to set another config file via command line arguments by `--config-name=CONFIG_FILE_PATH'.\n-\n-For more details about the config files and different ways of model restoration, see tutorials/00_NeMo_Primer.ipynb\n-\n-\n-*** Model Evaluation ***\n-\n- python punctuation_capitalization_evaluate.py \\\n- model.dataset.data_dir= \\\n- pretrained_model=punctuation_en_distilbert \n-\n- - a directory that contains test_ds.text_file and test_ds.labels_file (see the config)\n-pretrained_model - pretrained PunctuationCapitalizationModel model from list_available_models() or \n- path to a .nemo file, for example: punctuation_en_bert or your_model.nemo\n-\n-\"\"\"\n-\n-\n-@hydra_runner(config_path=\"conf\", config_name=\"punctuation_capitalization_config\")\n-def main(cfg: DictConfig) -> None:\n- logging.info(\n- 'During evaluation/testing, it is currently advisable to construct a new Trainer with single GPU and \\\n- no DDP to obtain accurate results'\n- )\n-\n- if not hasattr(cfg.model, 'test_ds'):\n- raise ValueError(f'model.test_ds was not found in the config, skipping evaluation')\n- else:\n- gpu = 1 if cfg.trainer.gpus != 0 else 0\n-\n- trainer = pl.Trainer(gpus=gpu, precision=cfg.trainer.precision, logger=False, checkpoint_callback=False,)\n- exp_dir = exp_manager(trainer, cfg.exp_manager)\n-\n- if not cfg.pretrained_model:\n- raise ValueError(\n- 'To run evaluation and inference script a pre-trained model or .nemo file must be provided.'\n- f'Choose from {PunctuationCapitalizationModel.list_available_models()} or \"pretrained_model\"=\"your_model.nemo\"'\n- )\n-\n- if os.path.exists(cfg.pretrained_model):\n- model = PunctuationCapitalizationModel.restore_from(cfg.pretrained_model)\n- elif cfg.pretrained_model in PunctuationCapitalizationModel.get_available_model_names():\n- model = PunctuationCapitalizationModel.from_pretrained(cfg.pretrained_model)\n- else:\n- raise ValueError(\n- f'Provide path to the pre-trained .nemo file or choose from {PunctuationCapitalizationModel.list_available_models()}'\n- )\n-\n- data_dir = cfg.model.dataset.get('data_dir', None)\n-\n- if data_dir is None:\n- logging.error(\n- 'No dataset directory provided. Skipping evaluation. '\n- 'To run evaluation on a file, specify path to the directory that contains test_ds.text_file and test_ds.labels_file with \"model.dataset.data_dir\" argument.'\n- )\n- elif not os.path.exists(data_dir):\n- logging.error(f'{data_dir} is not found, skipping evaluation on the test set.')\n- else:\n- model.update_data_dir(data_dir=data_dir)\n- model._cfg.dataset = cfg.model.dataset\n-\n- if not hasattr(cfg.model, 'test_ds'):\n- logging.error(f'model.test_ds was not found in the config, skipping evaluation')\n- elif model.prepare_test(trainer):\n- model.setup_test_data(cfg.model.test_ds)\n- trainer.test(model)\n- else:\n- logging.error('Skipping the evaluation. The trainer is not setup properly.')\n-\n- # run an inference on a few examples\n- queries = [\n- 'we bought four shirts one pen and a mug from the nvidia gear store in santa clara',\n- 'what can i do for you today',\n- 'how are you',\n- ]\n-\n- inference_results = model.add_punctuation_capitalization(queries, batch_size=len(queries), max_seq_length=512)\n-\n- for query, result in zip(queries, inference_results):\n- logging.info(f'Query : {query}')\n- logging.info(f'Result: {result.strip()}\\n')\n-\n- logging.info(f'Results are saved at {exp_dir}')\n-\n-\n-if __name__ == '__main__':\n- main()\ndiff --git a/examples/nlp/token_classification/punctuation_capitalization_train.py b/examples/nlp/token_classification/punctuation_capitalization_train_evaluate.py\nsimilarity index 52%\nrename from examples/nlp/token_classification/punctuation_capitalization_train.py\nrename to examples/nlp/token_classification/punctuation_capitalization_train_evaluate.py\n--- a/examples/nlp/token_classification/punctuation_capitalization_train.py\n+++ b/examples/nlp/token_classification/punctuation_capitalization_train_evaluate.py\n@@ -1,4 +1,4 @@\n-# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.\n+# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n #\n # Licensed under the Apache License, Version 2.0 (the \"License\");\n # you may not use this file except in compliance with the License.\n@@ -15,9 +15,13 @@\n import os\n \n import pytorch_lightning as pl\n+import torch\n from omegaconf import DictConfig, OmegaConf\n \n from nemo.collections.nlp.models import PunctuationCapitalizationModel\n+from nemo.collections.nlp.models.token_classification.punctuation_capitalization_config import (\n+ PunctuationCapitalizationConfig,\n+)\n from nemo.core.config import hydra_runner\n from nemo.utils import logging\n from nemo.utils.exp_manager import exp_manager\n@@ -44,25 +48,50 @@\n *** Model training ***\n \n To run this script and train the model from scratch, use:\n- python punctuation_and_capitalization_train.py \\\n- model.dataset.data_dir=\n+ python punctuation_capitalization_train_evaluate.py \\\n+ model.train_ds.ds_item= \\\n+ model.validation_ds.ds_item=\n \n To use one of the pretrained versions of the model and finetune it, run:\n- python punctuation_and_capitalization.py \\\n- pretrained_model=punctuation_en_bert \\\n- model.dataset.data_dir=\n+ python punctuation_capitalization_train_evaluate.py \\\n+ pretrained_model=punctuation_en_bert \\\n+ model.train_ds.ds_item= \\\n+ model.validation_ds.ds_item=\n \n- - a directory that contains test_ds.text_file and test_ds.labels_file (see the config)\n pretrained_model - pretrained PunctuationCapitalization model from list_available_models() or \n- path to a .nemo file, for example: punctuation_en_bert or model.nemo\n+ path to a .nemo file, for example: punctuation_en_bert or model.nemo\n+\n+If you wish to perform testing after training set `do_testing` to `true:\n+ python punctuation_capitalization_train_evaluate.py \\\n+ +do_testing=true \\\n+ pretrained_model=punctuation_en_bert \\\n+ model.train_ds.ds_item= \\\n+ model.validation_ds.ds_item=\n+\n+Set `do_training` to `false` and `do_testing` to `true` to perform evaluation without training:\n+ python punctuation_capitalization_train_evaluate.py \\\n+ +do_testing=true \\\n+ +do_training=false \\\n+ pretrained_model=punctuation_en_bert \\\n+ model.validation_ds.ds_item=\n \n \"\"\"\n \n \n @hydra_runner(config_path=\"conf\", config_name=\"punctuation_capitalization_config\")\n def main(cfg: DictConfig) -> None:\n+ torch.manual_seed(42)\n+ cfg = OmegaConf.merge(OmegaConf.structured(PunctuationCapitalizationConfig()), cfg)\n trainer = pl.Trainer(**cfg.trainer)\n exp_manager(trainer, cfg.get(\"exp_manager\", None))\n+ if not cfg.do_training and not cfg.do_testing:\n+ raise ValueError(\"At least one of config parameters `do_training` and `do_testing` has to `true`.\")\n+ if cfg.do_training:\n+ if cfg.model.get('train_ds') is None:\n+ raise ValueError('`model.train_ds` config section is required if `do_training` config item is `True`.')\n+ if cfg.do_testing:\n+ if cfg.model.get('test_ds') is None:\n+ raise ValueError('`model.test_ds` config section is required if `do_testing` config item is `True`.')\n \n if not cfg.pretrained_model:\n logging.info(f'Config: {OmegaConf.to_yaml(cfg)}')\n@@ -74,27 +103,28 @@ def main(cfg: DictConfig) -> None:\n model = PunctuationCapitalizationModel.from_pretrained(cfg.pretrained_model)\n else:\n raise ValueError(\n- f'Provide path to the pre-trained .nemo file or choose from {PunctuationCapitalizationModel.list_available_models()}'\n+ f'Provide path to the pre-trained .nemo file or choose from '\n+ f'{PunctuationCapitalizationModel.list_available_models()}'\n )\n-\n- data_dir = cfg.model.dataset.get('data_dir', None)\n- if data_dir:\n- if not os.path.exists(data_dir):\n- raise ValueError(f'{data_dir} is not found at')\n-\n- # we can also do finetuning of the pretrained model but we would need to update the data dir\n- model.update_data_dir(data_dir)\n- # setup train and validation Pytorch DataLoaders\n+ model.update_config_after_restoring_from_checkpoint(\n+ class_labels=cfg.model.class_labels,\n+ common_dataset_parameters=cfg.model.common_dataset_parameters,\n+ train_ds=cfg.model.get('train_ds') if cfg.do_training else None,\n+ validation_ds=cfg.model.get('validation_ds') if cfg.do_training else None,\n+ test_ds=cfg.model.get('test_ds') if cfg.do_testing else None,\n+ optim=cfg.model.get('optim') if cfg.do_training else None,\n+ )\n+ model.set_trainer(trainer)\n+ if cfg.do_training:\n model.setup_training_data()\n model.setup_validation_data()\n- logging.info(f'Using config file of the pretrained model')\n+ model.setup_optimization()\n else:\n- raise ValueError(\n- 'Specify a valid dataset directory that contains test_ds.text_file and test_ds.labels_file \\\n- with \"model.dataset.data_dir\" argument'\n- )\n-\n- trainer.fit(model)\n+ model.setup_test_data()\n+ if cfg.do_training:\n+ trainer.fit(model)\n+ if cfg.do_testing:\n+ trainer.test(model)\n \n \n if __name__ == '__main__':\ndiff --git a/nemo/collections/nlp/data/token_classification/punctuation_capitalization_dataset.py b/nemo/collections/nlp/data/token_classification/punctuation_capitalization_dataset.py\n--- a/nemo/collections/nlp/data/token_classification/punctuation_capitalization_dataset.py\n+++ b/nemo/collections/nlp/data/token_classification/punctuation_capitalization_dataset.py\n@@ -12,209 +12,850 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n-__all__ = ['BertPunctuationCapitalizationDataset', 'BertPunctuationCapitalizationInferDataset']\n+__all__ = [\n+ 'BertPunctuationCapitalizationDataset',\n+ 'LABEL_ID_DIR_FOR_NEMO_CHECKPOINT',\n+ 'Progress',\n+ 'PunctuationCapitalizationEvalDataConfig',\n+ 'PunctuationCapitalizationTrainDataConfig',\n+ 'create_label_ids',\n+ 'create_masks_and_segment_ids',\n+ 'is_legacy_data_config',\n+ 'legacy_data_config_to_new_data_config',\n+ 'load_label_ids',\n+ 'raise_not_equal_labels_error',\n+ 'save_label_ids',\n+]\n \n import itertools\n+import multiprocessing as mp\n import os\n import pickle\n-from typing import Dict, List, Optional, Tuple\n+import random\n+from dataclasses import dataclass\n+from math import ceil\n+from pathlib import Path\n+from queue import Empty\n+from time import sleep\n+from typing import Any, Dict, List, Optional, Set, Tuple, Union\n \n import numpy as np\n import torch\n-from torch.nn.utils.rnn import pad_sequence\n+from numpy.typing import ArrayLike\n+from omegaconf import MISSING, DictConfig, OmegaConf\n+from tqdm import tqdm\n \n from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec\n from nemo.collections.nlp.data.data_utils.data_preprocessing import get_label_stats, get_stats\n from nemo.core.classes import Dataset\n-from nemo.core.neural_types import ChannelType, Index, LabelsType, MaskType, NeuralType\n-from nemo.core.neural_types.elements import BoolType\n+from nemo.core.neural_types import ChannelType, LabelsType, MaskType, NeuralType\n from nemo.utils import logging\n \n+MAX_NUM_QUERIES_IN_SPLIT = 10 ** 4\n+TOKENIZATION_PROGRESS_REPORT_PERIOD = 10 ** 3\n+BATCH_MARK_UP_PROGRESS_REPORT_PERIOD = 10 ** 4\n+BATCH_BUILDING_PROGRESS_REPORT_PERIOD = 10 ** 4\n+\n+LABEL_ID_DIR_FOR_NEMO_CHECKPOINT = \"label_id_files_for_nemo_checkpoint\"\n+\n+\n+@dataclass\n+class PunctuationCapitalizationDataConfigBase:\n+ \"\"\"A base class for punctuation and capitalization data configs. This class does not define ``ds_item``\n+ attribute which works differently for train and evaluation data.\"\"\"\n+\n+ #################################################\n+ # COMMON DATASET PARAMETERS\n+ #################################################\n+ use_tarred_dataset: bool = MISSING\n+ \"\"\"Whether to use tarred dataset. If True, then you should provide ``tar_metadata_file``. Otherwise, you should\n+ provide ``text_file``, ``labels_file``, ``tokens_in_batch``.\"\"\"\n+\n+ label_info_save_dir: Optional[str] = None\n+ \"\"\"A path to a directory where files created during dataset processing are stored. These files include label id\n+ files and label stats files. By default, it is a directory containing ``text_file`` or ``tar_metadata_file``.\n+ You may need this parameter if dataset directory is read-only and thus does not allow saving anything near dataset\n+ files\"\"\"\n+\n+ #################################################\n+ # REGULAR DATASET PARAMETERS\n+ #################################################\n+ text_file: Optional[str] = None\n+ \"\"\"A path to a file with source text data without punctuation and capitalization.\"\"\"\n+\n+ labels_file: Optional[str] = None\n+ \"\"\"A path to a file with punctuation and capitalization labels in NeMo format. NeMo format is described in\n+ `documentation \n+ `_\n+ \"\"\"\n+\n+ tokens_in_batch: Optional[int] = None\n+ \"\"\"Number of tokens in a batch including paddings and special tokens ([CLS], [SEP], [UNK]). This config does\n+ not have ``batch_size`` parameter.\"\"\"\n+\n+ max_seq_length: int = 512\n+ \"\"\"Max number of tokens in a source sequence. ``max_seq_length`` includes [CLS] and [SEP] tokens. Sequences\n+ which are too long will be clipped by removal of tokens from the end of a sequence.\"\"\"\n+\n+ num_samples: int = -1\n+ \"\"\"A number of samples loaded from ``text_file`` and ``labels_file`` which are used in the dataset. If this\n+ parameter equals ``-1``, then all samples are used.\"\"\"\n+\n+ use_cache: bool = True\n+ \"\"\"Whether to use pickled features. If pickled features does not exist, then pickled features will be created.\n+ For large regular datasets, pickled features may considerably reduce time for training starting. Tokenization\n+ of source sequences is not fast because sequences are split into words before tokenization. For even larger\n+ datasets (~4M), tarred datasets are recommended.\"\"\"\n+\n+ cache_dir: Optional[str] = None\n+ \"\"\"A path to a directory containing cache or directory where newly created cache is saved. By default, it is\n+ a directory containing ``text_file``. You may need this parameter if cache for a dataset is going to be created\n+ and the dataset directory is read-only.\n+ \n+ ``cache_dir`` and ``label_info_save_dir`` are separate parameters for the case when a cache is ready and this cache\n+ is stored in a read only directory. In this case you will separate ``label_info_save_dir``.\"\"\"\n+\n+ get_label_frequences: bool = False\n+ \"\"\"Whether to show and save label frequencies. Frequencies are showed if ``verbose`` parameter is ``True``. If\n+ ``get_label_frequencies=True``, then frequencies are saved into ``label_info_save_dir``\"\"\"\n+\n+ verbose: bool = True\n+ \"\"\"If ``True`` dataset instance will print progress messages and examples of acquired features.\"\"\"\n+\n+ n_jobs: Optional[int] = 0\n+ \"\"\"Number of workers used for features creation (tokenization, label encoding, and clipping). If 0, then\n+ multiprocessing is not used; if ``None``, then n_jobs is equal to the number of CPU cores.\n+ There can be weird deadlocking errors with some tokenizers (e.g. SentencePiece) if ``n_jobs`` is greater than zero.\n+ \"\"\"\n+\n+ #################################################\n+ # TARRED DATASET PARAMETERS\n+ #################################################\n+ tar_metadata_file: Optional[str] = None\n+ \"\"\"A path to tarred dataset metadata file. Tarred metadata file and other parts of tarred dataset are usually\n+ created by the script\n+ `examples/nlp/token_classification/data/create_punctuation_capitalization_tarred_dataset.py\n+ `_\n+ \"\"\"\n+\n+ tar_shuffle_n: int = 1\n+ \"\"\"The size of shuffle buffer of `webdataset`. The number of batches which are permuted.\"\"\"\n+\n+ #################################################\n+ # PYTORCH DATALOADER PARAMETERS\n+ #################################################\n+ shuffle: bool = True\n+ \"\"\"Shuffle batches every epoch. For regular training datasets, the parameter also activates batch repacking every\n+ epoch. For tarred dataset, it would be only batches permutation.\"\"\"\n+\n+ drop_last: bool = False\n+ \"\"\"In cases when data parallelism is used, ``drop_last`` defines the way data pipeline behaves when some replicas\n+ are out of data and some are not. If ``drop_last`` is ``True``, then epoch ends in the moment when any replica runs\n+ out of data. If ``drop_last`` is ``False``, then the replica will replace missing batch with a batch from a pool of\n+ batches that the replica has already processed. If data parallelism is not used, then parameter ``drop_last`` does\n+ not do anything. For more information see ``torch.utils.data.distributed.DistributedSampler``\"\"\"\n+\n+ pin_memory: bool = True\n+ \"\"\"See ``torch.utils.data.DataLoader`` documentation.\"\"\"\n+\n+ num_workers: int = 8\n+ \"\"\"See ``torch.utils.data.DataLoader`` documentation.\"\"\"\n+\n+ persistent_workers: bool = True\n+ \"\"\"See ``torch.utils.data.DataLoader`` documentation.\"\"\"\n+\n+\n+@dataclass\n+class PunctuationCapitalizationTrainDataConfig(PunctuationCapitalizationDataConfigBase):\n+ ds_item: Optional[str] = MISSING\n+ \"\"\"Path to a directory where `tar_metadata_file` or `text_file` and `labels_file` lay.\"\"\"\n+\n \n-def get_features(\n- queries: List[str],\n+@dataclass\n+class PunctuationCapitalizationEvalDataConfig(PunctuationCapitalizationDataConfigBase):\n+ ds_item: Optional[Any] = MISSING\n+ \"\"\"Path to a directory where `tar_metadata_file` or `text_file` and `labels_file` lay. ``Any`` = ``str`` or\n+ ``List[str]``. If a ``List[str]``, then the model is tested or validated on several datasets.\"\"\"\n+\n+\n+def is_legacy_data_config(ds_section: DictConfig) -> bool:\n+ return 'use_tarred_dataset' not in ds_section\n+\n+\n+def legacy_data_config_to_new_data_config(\n+ ds_section: DictConfig, legacy_dataset_section: DictConfig, train: bool\n+) -> DictConfig:\n+ \"\"\"\n+ Transform old style dataset to new format dataset.\n+ Args:\n+ ds_section: a ds section (``train_ds``, or ``validation_ds``, or ``test_ds``) from old style config. Such\n+ section contain ``batch_size`` parameter.\n+ legacy_dataset_section: a ``model.dataset`` section. ``model.dataset`` section contains ``data_dir`` parameter\n+ train: ``True`` if ``train_ds`` is transformed and ``False`` otherwise\n+\n+ Returns:\n+ New format dataset based on either ``PunctuationCapitalizationTrainDataConfig`` (``train=True``) or\n+ ``PunctuationCapitalizationEvalDataConfig`` (``train=False``)\n+ \"\"\"\n+ if train:\n+ cls = PunctuationCapitalizationTrainDataConfig\n+ ds_item = legacy_dataset_section.get('data_dir')\n+ else:\n+ cls = PunctuationCapitalizationEvalDataConfig\n+ ds_item = ds_section.get('ds_item')\n+ ds_item = legacy_dataset_section.get('data_dir') if ds_item is None else ds_item\n+ if ds_item is None:\n+ raise ValueError(\n+ f\"Data directory was not found in legacy config.\\nspecific dataset configuration:\\n\"\n+ f\"{OmegaConf.to_yaml(ds_section)}\\nmodel.dataset:\\n{OmegaConf.to_yaml(legacy_dataset_section)}\"\n+ )\n+ new_config = OmegaConf.structured(\n+ cls(\n+ use_tarred_dataset=False,\n+ text_file=ds_section.text_file,\n+ labels_file=ds_section.labels_file,\n+ ds_item=ds_item,\n+ max_seq_length=legacy_dataset_section.get(\n+ 'max_seq_length', PunctuationCapitalizationDataConfigBase.max_seq_length\n+ ),\n+ )\n+ )\n+ return new_config\n+\n+\n+def _check_number_of_labels(\n+ words: List[str],\n+ query: str,\n+ qi: int,\n+ split_i: int,\n+ punctuation_labels: List[str],\n+ capitalization_labels: List[str],\n+) -> None:\n+ if len(words) != len(punctuation_labels):\n+ raise ValueError(\n+ f\"Number of punctuation labels for a query number {qi} in a split number {split_i} is not equal to \"\n+ f\"number of words. Number of words: {len(words)}, number of punctuation labels: \"\n+ f\"{len(punctuation_labels)}. First 100 characters of the query: '{query[:100]}', punctuation labels: \"\n+ f\"'{punctuation_labels}'\"\n+ )\n+ if len(words) != len(capitalization_labels):\n+ raise ValueError(\n+ f\"Number of capitalization labels for a query number {qi} in a split number {split_i} is not equal to \"\n+ f\"number of words. Number of words: {len(words)}, number of capitalization labels: \"\n+ f\"{len(capitalization_labels)}. First 100 characters of the query: '{query[:100]}', \"\n+ f\"capitalization labels: '{capitalization_labels}'\"\n+ )\n+\n+\n+def _show_prog(queues: Tuple[mp.Queue, ...], totals: List[int], descriptions: List[str], units: List[str]) -> None:\n+ \"\"\"\n+ Show several ``tqdm`` progress bars.\n+ Args:\n+ queues: a list of queues by which progress is delivered into this function. Each queue is responsible for one\n+ progress bar. ``show_prog`` function extracts integers from ``queues`` elements and adds them to progress\n+ bars. If value extracted from a queue equals ``-1``, then corresponding progress bar is closed. When all\n+ progress bars are closed, this function returns.\n+ totals: list of values 100% of progress bars. See more in a description of ``total`` parameter of\n+ ``tqdm.tqdm`` function\n+ descriptions: list of descriptions of progress bars. See more in a description of ``desc`` parameter of\n+ ``tqdm.tqdm`` function\n+ units: list of progress bar units. See more in a description of ``unit`` parameter of ``tqdm.tqdm`` function\n+ \"\"\"\n+ if not all([len(queues) == len(v) for v in [totals, descriptions, units]]):\n+ raise ValueError(\n+ f\"All of parameters `queues`, `total_num_lines`, `descriptions`, `units` have to have equal lengths. \"\n+ f\"len(queues)={len(queues)}, len(total_num_lines)={len(totals)}, \"\n+ f\"len(descriptions)={len(descriptions)}, len(units)={len(units)}.\"\n+ )\n+ prog = [\n+ tqdm(total=tt, desc=dd, unit=uu, unit_scale=True, position=i)\n+ for i, (tt, dd, uu) in enumerate(zip(totals, descriptions, units))\n+ ]\n+ finished = [False] * len(queues)\n+ while True:\n+ for i, queue in enumerate(queues):\n+ stop = False\n+ to_add = 0\n+ try:\n+ v = queue.get(block=False)\n+ while v != -1:\n+ to_add += v\n+ v = queue.get(block=False)\n+ stop = True\n+ except Empty:\n+ if to_add == 0 and not stop:\n+ continue\n+ prog[i].n += to_add\n+ prog[i].update(0)\n+ if prog[i].n >= totals[i]:\n+ finished[i] = True\n+ prog[i].close()\n+ if stop:\n+ if prog[i].n < totals[i]:\n+ logging.warning(\n+ f\"Progress with description '{descriptions[i]}' terminated before progress bar \"\n+ f\"reached 100%. prog.n={prog[i].n}, total_num_lines={totals[i]}\"\n+ )\n+ finished[i] = True\n+ prog[i].close()\n+ if all(finished):\n+ break\n+ sleep(0.1)\n+\n+\n+class Progress:\n+ \"\"\"\n+ Manages several ``tqdm`` progress bars for multi process tasks. This class can be used as context manager.\n+\n+ The class starts separate process which creates and updates progress bars. Information to progress process is\n+ passed via multiprocessing queues. There is a separate queue for every progress bar.\n+\n+ You can use it as context manager:\n+\n+ .. code-block:: python\n+ with Progress([10, 20], [\"progress bar 1\", \"progress bar 2\"], [\"parrot\", \"frog\"]) as progress_queues:\n+ num_processes = 10\n+ with multiprocessing.Pool(num_processes) as pool:\n+ data = list(zip(my_data, [progress_queues[0]] * num_processes, [progress_queues[1]] * num_processes))\n+ pool.starmap(worker_func, data)\n+\n+ Or without context manager:\n+\n+ .. code-block:: python\n+ progress = Progress([10, 20], [\"progress bar 1\", \"progress bar 2\"], [\"parrot\", \"frog\"])\n+ progress_queues = progress.get_queue()\n+ num_processes = 10\n+ with multiprocessing.Pool(num_processes) as pool:\n+ data = list(zip(my_data, [progress_queues[0]] * num_processes, [progress_queues[1]] * num_processes))\n+ pool.starmap(worker_func, data)\n+ progress.finish()\n+\n+ In a worker function you will have to put number of processed items into the progress queues. For example:\n+\n+ .. code-block:: python\n+ def worker_func(my_datum, parrot_progress_queue, frog_progress_queue):\n+ ...\n+ for i in range(10):\n+ parrot_progress_queue.put(1)\n+ frog_progress_queue.put(2)\n+\n+ Progress bars and progress process are closed when ``finish`` or ``__exit__`` methods are called.\n+ \"\"\"\n+\n+ def __init__(self, total: Union[int, List[int]], desc: Union[str, List[str]], unit: Union[str, List[str]]) -> None:\n+ \"\"\"\n+ Starts progress process and creates queues for passing information to the progress process. Number of progress\n+ bars is equal to the max length of lists ``total``, ``desc``, ``unit``. If none of these parameters is a list,\n+ then 1 progress bar is created.\n+\n+ Args:\n+ total: a list of ``int`` which length is equal to the number of progress bars OR an ``int`` OR a list of\n+ one ``int``. Number which comprises 100% of progress bar. When sum of values passed through the\n+ corresponding queue equals ``total`` corresponding progress bar reaches 100%. If ``total`` is an\n+ ``int`` or a list of one element, then all progress bars have equal ``total`` parameter.\n+ desc: a list of ``str`` which length is equal to the number of progress bars OR a ``str`` OR a list of one\n+ ``str``. Description of a progress bar which is showed as a prefix. See more in description of\n+ parameter ``desc`` of function ``tqdm.tqdm``.\n+ unit: a list of ``str`` which length is equal to the number of progress bars OR a ``str`` OR a list of one\n+ ``str``. A unit of a progress bar. See more in description of parameter ``unit`` of function\n+ ``tqdm.tqdm``.\n+ \"\"\"\n+ if not isinstance(total, list):\n+ total = [total]\n+ if not isinstance(desc, list):\n+ desc = [desc]\n+ if not isinstance(unit, list):\n+ unit = [unit]\n+ num_processes = max([len(total), len(desc), len(unit)])\n+ for param in [total, desc, unit]:\n+ if len(param) not in [num_processes, 1]:\n+ raise ValueError(\n+ f\"If parameter of `Progress.__init__` method is a list, then it has to be the same length as other \"\n+ f\"parameters which are lists\"\n+ )\n+ if len(param) == 1:\n+ param *= num_processes\n+ manager = mp.Manager()\n+ self.progress_queues = tuple(manager.Queue() for _ in range(num_processes))\n+ self.progress_process = mp.Process(target=_show_prog, args=(self.progress_queues, total, desc, unit))\n+ self.progress_process.start()\n+\n+ def __enter__(self) -> Tuple[mp.Queue, ...]:\n+ return self.get_queues()\n+\n+ def __exit__(self, exc_type, exc_val, exc_tb) -> None:\n+ self.finish()\n+\n+ def get_queues(self) -> Tuple[mp.Queue, ...]:\n+ return self.progress_queues\n+\n+ def finish(self) -> None:\n+ for q in self.progress_queues:\n+ q.put(-1)\n+ self.progress_process.join()\n+\n+\n+class TokenizeCreateMasksClipWorker:\n+ \"\"\"A worker for tokenization, encoding labels, creating masks for first token in a word, sequence clipping\"\"\"\n+\n+ def __init__(\n+ self,\n+ max_seq_length: int,\n+ tokenizer: TokenizerSpec,\n+ punct_label_ids: Optional[Dict[str, int]],\n+ capit_label_ids: Optional[Dict[str, int]],\n+ pad_label: str,\n+ verbose: bool,\n+ progress_queue: mp.Queue,\n+ ) -> None:\n+ \"\"\"\n+ Args:\n+ max_seq_length: max number of tokens in an input sequence including [CLS] and [SEP] tokens. If number of\n+ tokens in a sequence exceeds ``max_seq_length``, then excess tokens in the end of the sequence\n+ are removed\n+ tokenizer: a tokenizer instance which has properties ``cls_id``, ``pad_id``, ``sep_id``, ``unk_id``\n+ punct_label_ids: dict to map punctuation labels to label ids. Starts with pad_label->0.\n+ capit_label_ids: dict to map capitalization labels to label ids. Starts with pad_label->0.\n+ pad_label: pad value use for labels. By default, it's the neutral label for punctuation and capitalization.\n+ Its id in ``punct_label_ids`` and ``capit_label_ids`` has to be ``0``\n+ verbose: whether to report when the worker finishes its job\n+ progress_queue: a multiprocessing queue used for reporting progress. Useful for creating tarred dataset\n+ \"\"\"\n+ self.max_seq_length = max_seq_length\n+ self.tokenizer = tokenizer\n+ self.punct_label_ids = punct_label_ids\n+ self.capit_label_ids = capit_label_ids\n+ self.pad_label = pad_label\n+ self.verbose = verbose\n+ self.progress_queue = progress_queue\n+\n+ def _maybe_clip(self, values: List[int], append_value: int) -> List[int]:\n+ if len(values) > self.max_seq_length:\n+ return values[: self.max_seq_length - 1] + [append_value]\n+ return values\n+\n+ def __call__(\n+ self,\n+ queries: List[str],\n+ punct_label_lines: Optional[Union[List[str], Tuple[str, ...]]],\n+ capit_label_lines: Optional[Union[List[str], Tuple[str, ...]]],\n+ split_i: int,\n+ ) -> Tuple[List[ArrayLike], List[ArrayLike], List[ArrayLike], List[ArrayLike]]:\n+ \"\"\"\n+ Tokenize, clip, encode labels, and create masks of first tokens in words.\n+\n+ Args:\n+ queries: text sequences\n+ punct_label_lines: a list or a tuple of labels for every word in a sequence (str)\n+ capit_label_lines: a list of a tuple labels for every word in a sequence (str)\n+ split_i: number of a split which is processed. Used for logging\n+\n+ Returns:\n+ input_ids: a list of 1D int32 arrays. Each array contains token ids of the corresponding query\n+ subtokens_mask: a list of 1D boolean arrays. An array element is ``True`` if corresponding token is the\n+ first token in a word\n+ punct_labels: a list of 1D int32 arrays. Encoded punctuation labels for every token in a query. Tokens in\n+ one word have identical labels\n+ capit_labels: a list of 1D int32 arrays. Encoded capitalization labels for every token in a query. Tokens\n+ in one word have identical labels\n+ \"\"\"\n+ all_input_ids, all_subtokens_mask, punct_all_labels, capit_all_labels = [], [], [], []\n+ progress_made = 0\n+ for i, query in enumerate(queries):\n+ words = query.split()\n+ input_ids, subtokens_mask = [self.tokenizer.cls_id], [0]\n+ _check_number_of_labels(words, query, i, split_i, punct_label_lines[i], capit_label_lines[i])\n+ pad_id = self.punct_label_ids[self.pad_label]\n+ punct_labels = [pad_id]\n+ punct_query_labels = [self.punct_label_ids[lab] for lab in punct_label_lines[i]]\n+ capit_labels = [pad_id]\n+ capit_query_labels = [self.capit_label_ids[lab] for lab in capit_label_lines[i]]\n+ for j, word in enumerate(words):\n+ word_ids = self.tokenizer.text_to_ids(word)\n+ if not word_ids and len(word):\n+ word_ids = [self.tokenizer.unk_id]\n+ input_ids.extend(word_ids)\n+\n+ subtokens_mask.append(1)\n+ subtokens_mask.extend([0] * (len(word_ids) - 1))\n+\n+ punct_labels.extend([punct_query_labels[j]] * len(word_ids))\n+ capit_labels.extend([capit_query_labels[j]] * len(word_ids))\n+\n+ # add eos token\n+ input_ids.append(self.tokenizer.sep_id)\n+ subtokens_mask.append(0)\n+\n+ all_input_ids.append(np.array(self._maybe_clip(input_ids, self.tokenizer.sep_id), dtype=np.int32))\n+ all_subtokens_mask.append(np.array(self._maybe_clip(subtokens_mask, 0), dtype=bool))\n+\n+ punct_labels.append(pad_id)\n+ punct_all_labels.append(np.array(self._maybe_clip(punct_labels, pad_id), dtype=np.int32))\n+ capit_labels.append(pad_id)\n+ capit_all_labels.append(np.array(self._maybe_clip(capit_labels, pad_id), dtype=np.int32))\n+ progress_made += 1\n+ if progress_made >= TOKENIZATION_PROGRESS_REPORT_PERIOD:\n+ self.progress_queue.put(progress_made)\n+ progress_made = 0\n+ self.progress_queue.put(progress_made)\n+ if self.verbose:\n+ logging.info(f\"Finished processing data split number {split_i}\")\n+ return all_input_ids, all_subtokens_mask, punct_all_labels, capit_all_labels\n+\n+\n+def _get_features(\n+ queries: Union[List[str], Tuple[str, ...]],\n+ punct_label_lines: Union[List[str], Tuple[str, ...]],\n+ capit_label_lines: Union[List[str], Tuple[str, ...]],\n max_seq_length: int,\n tokenizer: TokenizerSpec,\n- punct_label_ids: dict = None,\n- capit_label_ids: dict = None,\n+ punct_label_ids: Dict[str, int] = None,\n+ capit_label_ids: Dict[str, int] = None,\n pad_label: str = 'O',\n- punct_labels_lines=None,\n- capit_labels_lines=None,\n- ignore_extra_tokens=False,\n- ignore_start_end: Optional[bool] = False,\n-):\n+ verbose: bool = True,\n+ n_jobs: Optional[int] = 0,\n+ progress_queue: Optional[mp.Queue] = None,\n+) -> Tuple[List[ArrayLike], List[ArrayLike], List[ArrayLike], List[ArrayLike]]:\n \"\"\"\n- Processes the data and returns features.\n+ Tokenizes data, encodes labels, creates masks of first tokens in words, clips sequences by number of tokens.\n \n Args:\n queries: text sequences\n- max_seq_length: max sequence length minus 2 for [CLS] and [SEP]\n- tokenizer: such as AutoTokenizer\n- pad_label: pad value use for labels. By default, it's the neutral label.\n- punct_label_ids: dict to map punctuation labels to label ids.\n- Starts with pad_label->0 and then increases in alphabetical order.\n- Required for training and evaluation, not needed for inference.\n- capit_label_ids: dict to map labels to label ids. Starts\n- with pad_label->0 and then increases in alphabetical order.\n- Required for training and evaluation, not needed for inference.\n- punct_labels: list of labels for every word in a sequence (str)\n- capit_labels: list of labels for every word in a sequence (str)\n- ignore_extra_tokens: whether to ignore extra tokens in the loss_mask\n- ignore_start_end: whether to ignore bos and eos tokens in the loss_mask\n+ max_seq_length: max number of tokens in an input sequence including [CLS] and [SEP] tokens. If number of tokens\n+ in a sequence exceeds ``max_seq_length``, then excess tokens in the end of the sequence are removed\n+ tokenizer: a tokenizer instance which has properties ``cls_id``, ``pad_id``, ``sep_id``, ``unk_id``\n+ punct_label_ids: dict to map punctuation labels to label ids. Starts with pad_label->0.\n+ capit_label_ids: dict to map capitalization labels to label ids. Starts with pad_label->0.\n+ pad_label: pad value use for labels. By default, it's the neutral label for punctuation and capitalization.\n+ Its id in ``punct_label_ids`` and ``capit_label_ids`` has to be ``0``\n+ punct_label_lines: a list of a tuple of labels for every word in a sequence (str)\n+ capit_label_lines: a list or a tuple of labels for every word in a sequence (str)\n+ verbose: whether to show examples of tokenized data and various progress information\n+ n_jobs: a number of workers used for preparing features. If ``n_jobs <= 0``, then do not use multiprocessing\n+ and run features creation in this process. If not set, number of workers will be equal to the number of\n+ CPUs.\n+\n+ !!WARNING!!\n+ There can be deadlocking problems with some tokenizers (e.g. SentencePiece, HuggingFace AlBERT)\n+ if ``n_jobs > 0``.\n+\n+ progress_queue: a multiprocessing queue used for reporting progress. Useful for creating tarred dataset\n \n Returns:\n- all_input_ids: input ids for all tokens\n- all_segment_ids: token type ids\n- all_input_mask: attention mask to use for BERT model\n- all_subtokens_mask: masks out all subwords besides the first one\n- all_loss_mask: loss mask to mask out tokens during training\n- punct_all_labels: all labels for punctuation task (ints)\n- capit_all_labels: all labels for capitalization task (ints)\n- punct_label_ids: label (str) to id (int) map for punctuation task\n- capit_label_ids: label (str) to id (int) map for capitalization task\n+ input_ids: a list of 1D int32 arrays. Each array contains token ids of corresponding query\n+ subtokens_mask: a list of 1D boolean arrays. An array element is ``True`` if corresponding token is the\n+ first token in a word\n+ punct_labels: a list of 1D int32 arrays. Encoded punctuation labels for every token in a query. Tokens in one\n+ word have identical labels.\n+ capit_labels: a list of 1D int32 arrays. Encoded capitalization labels for every token in a query. Tokens in\n+ one word have identical labels\n \"\"\"\n- all_subtokens = []\n- all_loss_mask = []\n- all_subtokens_mask = []\n- all_segment_ids = []\n- all_input_ids = []\n- all_input_mask = []\n- sent_lengths = []\n- punct_all_labels = []\n- capit_all_labels = []\n- with_label = False\n-\n- if punct_labels_lines and capit_labels_lines:\n- with_label = True\n-\n- for i, query in enumerate(queries):\n- words = query.strip().split()\n-\n- # add bos token\n- subtokens = [tokenizer.cls_token]\n- loss_mask = [1 - ignore_start_end]\n- subtokens_mask = [0]\n- if with_label:\n- pad_id = punct_label_ids[pad_label]\n- punct_labels = [pad_id]\n- punct_query_labels = [punct_label_ids[lab] for lab in punct_labels_lines[i]]\n+ if verbose:\n+ logging.info(\"Start initial tokenization.\")\n+ create_progress_process = progress_queue is None\n+ if n_jobs is None:\n+ n_jobs = min(mp.cpu_count(), len(queries))\n+ if verbose:\n+ logging.info(f\"Running tokenization with {n_jobs} jobs.\")\n+\n+ # Number of queries in split\n+ split_size = min(len(queries) // max(n_jobs, 1), MAX_NUM_QUERIES_IN_SPLIT)\n+ n_split = len(queries) // split_size\n+ split_queries = [queries[split_size * i : split_size * (i + 1)] for i in range(n_split - 1)] + [\n+ queries[split_size * (n_split - 1) :]\n+ ]\n+ split_punct_labels_lines = [\n+ punct_label_lines[split_size * i : split_size * (i + 1)] for i in range(n_split - 1)\n+ ] + [punct_label_lines[split_size * (n_split - 1) :]]\n+ split_capit_labels_lines = [\n+ capit_label_lines[split_size * i : split_size * (i + 1)] for i in range(n_split - 1)\n+ ] + [capit_label_lines[split_size * (n_split - 1) :]]\n+ args = list(zip(split_queries, split_punct_labels_lines, split_capit_labels_lines, range(n_split)))\n+ if create_progress_process:\n+ progress = Progress(len(queries), \"Tokenization\", \"query\")\n+ progress_queue = progress.get_queues()[0]\n+ if n_jobs > 0:\n+ with mp.Pool(n_jobs) as pool:\n+ result = pool.starmap(\n+ TokenizeCreateMasksClipWorker(\n+ max_seq_length, tokenizer, punct_label_ids, capit_label_ids, pad_label, verbose, progress_queue\n+ ),\n+ args,\n+ )\n+ else:\n+ result = []\n+ for x in args:\n+ result.append(\n+ TokenizeCreateMasksClipWorker(\n+ max_seq_length, tokenizer, punct_label_ids, capit_label_ids, pad_label, verbose, progress_queue,\n+ )(*x)\n+ )\n+ if create_progress_process:\n+ progress.finish()\n+ input_ids, subtokens_mask, punct_labels, capit_labels = tuple(list(itertools.chain(*e)) for e in zip(*result))\n+ if verbose:\n+ logging.info(\"Finished initial tokenization.\")\n+ get_stats([len(inp) for inp in input_ids])\n+ logging.info(f\"Finished clipping and padding.\")\n+ for i in range(min(len(input_ids), 5)):\n+ logging.info(\"*** Example ***\")\n+ logging.info(\"i: %s\" % (i))\n+ logging.info(\"subtokens: %s\" % \" \".join(list(map(str, input_ids[i]))))\n+ logging.info(\"subtokens_mask: %s\" % \" \".join(list(map(str, subtokens_mask[i]))))\n+ logging.info(\"punct_labels: %s\" % \" \".join(list(map(str, punct_labels[i]))))\n+ logging.info(\"capit_labels: %s\" % \" \".join(list(map(str, capit_labels[i]))))\n+ return input_ids, subtokens_mask, punct_labels, capit_labels\n+\n+\n+def create_masks_and_segment_ids(\n+ input_ids: ArrayLike,\n+ subtokens_mask: ArrayLike,\n+ pad_id: int,\n+ cls_id: int,\n+ sep_id: int,\n+ ignore_start_end: bool,\n+ ignore_extra_tokens: bool,\n+) -> Tuple[ArrayLike, ArrayLike, ArrayLike]:\n+ \"\"\"\n+ Creates segment ids array, input mask, loss mask.\n \n- capit_labels = [pad_id]\n- capit_query_labels = [capit_label_ids[lab] for lab in capit_labels_lines[i]]\n+ Segment ids array is BERT token type ids in HuggingFace terminology. It is a zeros array for punctuation\n+ and capitalization task.\n \n- for j, word in enumerate(words):\n- word_tokens = tokenizer.text_to_tokens(word)\n- subtokens.extend(word_tokens)\n+ Input mask element is ``True`` if an element of ``input_ids`` is not padding and ``False`` otherwise.\n \n- loss_mask.append(1)\n- loss_mask.extend([int(not ignore_extra_tokens)] * (len(word_tokens) - 1))\n+ Loss mask element is ``True`` for the first token in a word. If ``ignore_start_end=False``, then loss mask\n+ element is ``True`` for [CLS] and [SEP] tokens. If ``ignore_extra_tokens=False``, then loss mask element is ``True``\n+ for all word tokens. In all other cases loss mask elements are ``False``.\n \n- subtokens_mask.append(1)\n- subtokens_mask.extend([0] * (len(word_tokens) - 1))\n+ Args:\n+ input_ids: an integer array of shape ``[Batch, Time]`` containing ids of source token ids\n+ subtokens_mask: a boolean array of shape ``[Batch, Time]`` which elements are ``True`` if they correspond to\n+ the first token of some word\n+ pad_id: an id of padding token\n+ cls_id: an id of [CLS] token\n+ sep_id: an id of [SEP] token\n+ ignore_start_end: whether to compute loss for [CLS] and [SEP] tokens\n+ ignore_extra_tokens: whether to compute loss for not first tokens in words\n \n- if with_label:\n- punct_labels.extend([punct_query_labels[j]] * len(word_tokens))\n- capit_labels.extend([capit_query_labels[j]] * len(word_tokens))\n+ Returns:\n+ segment_ids: int8 array of shape [Batch, Time]\n+ input_mask: boolean array of shape [Batch, Time]\n+ loss_mask: boolean array of shape [Batch, Time]\n+ \"\"\"\n+ segment_ids = np.zeros_like(input_ids, dtype=np.int8)\n+ input_mask = np.not_equal(input_ids, pad_id)\n+ special_mask = np.equal(input_ids, cls_id) & np.equal(input_ids, sep_id)\n+ if ignore_start_end:\n+ if ignore_extra_tokens:\n+ loss_mask = subtokens_mask\n+ else:\n+ loss_mask = input_mask & ~special_mask\n+ else:\n+ if ignore_extra_tokens:\n+ loss_mask = subtokens_mask | special_mask\n+ else:\n+ loss_mask = input_mask\n+ return segment_ids, input_mask, loss_mask\n \n- # add eos token\n- subtokens.append(tokenizer.sep_token)\n- loss_mask.append(1 - ignore_start_end)\n- subtokens_mask.append(0)\n- sent_lengths.append(len(subtokens))\n- all_subtokens.append(subtokens)\n- all_loss_mask.append(loss_mask)\n- all_subtokens_mask.append(subtokens_mask)\n- all_input_mask.append([1] * len(subtokens))\n \n- if with_label:\n- punct_labels.append(pad_id)\n- punct_all_labels.append(punct_labels)\n- capit_labels.append(pad_id)\n- capit_all_labels.append(capit_labels)\n-\n- max_seq_length = min(max_seq_length, max(sent_lengths))\n- logging.info(f'Max length: {max_seq_length}')\n- get_stats(sent_lengths)\n- too_long_count = 0\n-\n- for i, subtokens in enumerate(all_subtokens):\n- if len(subtokens) > max_seq_length:\n- subtokens = [tokenizer.cls_token] + subtokens[-max_seq_length + 1 :]\n- all_input_mask[i] = [1] + all_input_mask[i][-max_seq_length + 1 :]\n- all_loss_mask[i] = [int(not ignore_start_end)] + all_loss_mask[i][-max_seq_length + 1 :]\n- all_subtokens_mask[i] = [0] + all_subtokens_mask[i][-max_seq_length + 1 :]\n-\n- if with_label:\n- punct_all_labels[i] = [pad_id] + punct_all_labels[i][-max_seq_length + 1 :]\n- capit_all_labels[i] = [pad_id] + capit_all_labels[i][-max_seq_length + 1 :]\n- too_long_count += 1\n-\n- all_input_ids.append(tokenizer.tokens_to_ids(subtokens))\n-\n- if len(subtokens) < max_seq_length:\n- extra = max_seq_length - len(subtokens)\n- all_input_ids[i] = all_input_ids[i] + [0] * extra\n- all_loss_mask[i] = all_loss_mask[i] + [0] * extra\n- all_subtokens_mask[i] = all_subtokens_mask[i] + [0] * extra\n- all_input_mask[i] = all_input_mask[i] + [0] * extra\n-\n- if with_label:\n- punct_all_labels[i] = punct_all_labels[i] + [pad_id] * extra\n- capit_all_labels[i] = capit_all_labels[i] + [pad_id] * extra\n-\n- all_segment_ids.append([0] * max_seq_length)\n-\n- logging.info(f'{too_long_count} are longer than {max_seq_length}')\n-\n- for i in range(min(len(all_input_ids), 5)):\n- logging.info(\"*** Example ***\")\n- logging.info(\"i: %s\" % (i))\n- logging.info(\"subtokens: %s\" % \" \".join(list(map(str, all_subtokens[i]))))\n- logging.info(\"loss_mask: %s\" % \" \".join(list(map(str, all_loss_mask[i]))))\n- logging.info(\"input_mask: %s\" % \" \".join(list(map(str, all_input_mask[i]))))\n- logging.info(\"subtokens_mask: %s\" % \" \".join(list(map(str, all_subtokens_mask[i]))))\n- if with_label:\n- logging.info(\"punct_labels: %s\" % \" \".join(list(map(str, punct_all_labels[i]))))\n- logging.info(\"capit_labels: %s\" % \" \".join(list(map(str, capit_all_labels[i]))))\n-\n- return (\n- all_input_ids,\n- all_segment_ids,\n- all_input_mask,\n- all_subtokens_mask,\n- all_loss_mask,\n- punct_all_labels,\n- capit_all_labels,\n- punct_label_ids,\n- capit_label_ids,\n- )\n+def create_label_ids(unique_labels: Set[str], pad_label: str) -> Dict[str, int]:\n+ \"\"\"\n+ Returns label ids dictionary. ``pad_label`` always has id ``0``. Other labels are sorted in alphabetical order.\n+ Args:\n+ unique_labels: a set of labels from which label ids dictionary is created. May or may no contain ``pad_label``\n+ pad_label: label used for padding. It is also a neutral label\n+\n+ Returns:\n+ label ids dictionary\n+ \"\"\"\n+ label_ids = {pad_label: 0}\n+ if pad_label in unique_labels:\n+ unique_labels.remove(pad_label)\n+ for label in sorted(unique_labels):\n+ label_ids[label] = len(label_ids)\n+ return label_ids\n+\n+\n+def load_label_ids(file_path: Union[str, os.PathLike]) -> Dict[str, int]:\n+ ids = {}\n+ with open(file_path) as f:\n+ for i, line in enumerate(f):\n+ ids[line.strip()] = i\n+ return ids\n+\n+\n+def save_label_ids(label_ids: Dict[str, int], file_path: Path) -> None:\n+ \"\"\"\n+ Saves label ids map to a file. In each line of a file one label is saved. Labels are saved in the order of\n+ increasing of their ids.\n+\n+ Args:\n+ label_ids: label id dictionary. Pad label has to have id ``0``\n+ file_path: path to a file where labels will be saved\n+ \"\"\"\n+ file_path.parent.mkdir(parents=True, exist_ok=True)\n+ with file_path.open('w') as out:\n+ labels, _ = zip(*sorted(label_ids.items(), key=lambda x: x[1]))\n+ out.write('\\n'.join(labels))\n+\n+\n+def raise_not_equal_labels_error(\n+ first_labels: Dict[str, int], second_labels: Dict[str, int], first_labels_desc: str, second_labels_desc: str\n+) -> None:\n+ \"\"\"\n+ A helper function for raising comprehensible error if labels from 2 sources are different.\n+ Such sources may include:\n+ - labels stored in .nemo checkpoint\n+ - labels stored in tarred dataset\n+ - labels passed in config parameters ``model.common_dataset_parameters.{punct_label_ids,capit_label_ids}``\n+ - labels from files passed in config parameters ``model.class_labels.{punct_labels_file,capit_labels_file}``\n+ - labels in attributes ``PunctuationCapitalizationModel.{punct_label_ids,capit_label_ids}``\n+ - any other source\n+ This function helps to detect configuration early and give error messages that are easy to interpret.\n+ Call this function if ``first_labels != second_labels``.\n+\n+ Args:\n+ first_labels: first dictionary with labels\n+ second_labels: second dictionary with labels\n+ first_labels_desc: a description of first labels\n+ second_labels_desc: a description of second labels\n+ \"\"\"\n+ missing_in_first = {k: second_labels[k] for k in set(second_labels) - set(first_labels)}\n+ missing_in_second = {k: first_labels[k] for k in set(first_labels) - set(second_labels)}\n+ not_equal = {\n+ k: {'FIRST LABELS': first_labels[k], 'SECOND LABELS': second_labels[k]}\n+ for k in set(first_labels) & set(second_labels)\n+ if first_labels[k] != second_labels[k]\n+ }\n+ msg = f\"{first_labels_desc} (FIRST LABELS) are not equal to {second_labels_desc} (SECOND LABELS).\"\n+ if len(missing_in_first) > 0:\n+ msg += f\" Number of SECOND LABELS missing in the FIRST LABELS: {len(missing_in_first)}.\"\n+ if len(missing_in_second) > 0:\n+ msg += f\" Number of FIRST LABELS missing in the SECOND LABELS: {len(missing_in_second)}.\"\n+ if len(not_equal) > 0:\n+ msg += f\" Number of labels which are not equal: {len(not_equal)}.\"\n+ if len(missing_in_first) > 0:\n+ msg += (\n+ f\" Several examples of missing SECONDS LABELS in the FIRST LABELS: \"\n+ f\"{dict(list(missing_in_first.items())[:3])}.\"\n+ )\n+ if len(missing_in_second) > 0:\n+ msg += (\n+ f\" Several examples of missing FIRST LABELS in the SECOND LABELS: \"\n+ f\"{dict(list(missing_in_second.items())[:3])}.\"\n+ )\n+ if len(not_equal) > 0:\n+ msg += f\" Several examples of labels which are not equal: {dict(list(not_equal.items())[:3])}\"\n+ raise ValueError(msg)\n+\n+\n+def pad(vectors: List[ArrayLike], length: int, value: Union[int, float, bool]) -> ArrayLike:\n+ \"\"\"\n+ Pad vectors to length ``length`` and then stack.\n+ Args:\n+ vectors: a list of 1D arrays. Arrays to pad and stack\n+ length: a length of padded sequence. Has to be greater or equal to the maximum length of an element of\n+ ``vectors``.\n+ value: a value used for padding\n+\n+ Returns:\n+ an array of padded vectors\n+ \"\"\"\n+ result = []\n+ for v in vectors:\n+ result.append(np.concatenate([v, np.full([length - v.shape[0]], value, dtype=v.dtype)]))\n+ return np.stack(result)\n \n \n class BertPunctuationCapitalizationDataset(Dataset):\n \"\"\"\n- Creates dataset to use during training for punctuaion and capitalization tasks with a pretrained model.\n- For dataset to use during inference without labels, see BertPunctuationCapitalizationInferDataset.\n+ A dataset to use during training for punctuation and capitalization tasks.\n+ For inference, you will need\n+ :class:`~nemo.collections.nlp.data.token_classification.punctuation_capitalization_infer_dataset.BertPunctuationCapitalizationInferDataset`.\n+ For huge datasets which cannot be loaded into memory simultaneously use\n+ :class:`~nemo.collections.nlp.data.token_classification.punctuation_capitalization_tarred_dataset.BertPunctuationCapitalizationTarredDataset`.\n \n Args:\n- text_file: file to sequences, each line should a sentence, no header.\n- label_file: file to labels, each line corresponds to word labels for a sentence in the text_file. No header.\n- max_seq_length: max sequence length minus 2 for [CLS] and [SEP]\n- tokenizer: such as AutoTokenizer\n- num_samples: number of samples you want to use for the dataset.\n- If -1, use all dataset. Useful for testing.\n- pad_label: pad value use for labels.\n- by default, it's the neutral label.\n- punct_label_ids and capit_label_ids (dict):\n- dict to map labels to label ids.\n- Starts with pad_label->0 and then increases in alphabetical order\n- For dev set use label_ids generated during training to support\n- cases when not all labels are present in the dev set.\n- For training set label_ids should be None or loaded from cache\n- ignore_extra_tokens: whether to ignore extra tokens in the loss_mask\n- ignore_start_end: whether to ignore bos and eos tokens in the loss_mask\n- use_cache: whether to use processed data cache or not\n- get_label_frequencies: whether to generate label frequencies\n- punct_label_ids_file and capit_label_ids_file: name of the files to save in .nemo\n+ text_file (:obj:`Union[str, os.PathLike]`): a path to a file with sequences, each line should contain a text\n+ without punctuation and capitalization\n+ labels_file (:obj:`Union[str, os.PathLike]`): a path to a file with labels, each line corresponds to word\n+ labels for a sentence in the ``text_file``. Labels have to follow format described in this section of\n+ documentation :ref:`NeMo Data Format`.\n+ max_seq_length (:obj:`int`): max number of tokens in a source sequence. ``max_seq_length`` includes for [CLS]\n+ and [SEP] tokens. Sequences which are too long will be clipped by removal of tokens from the end of the\n+ sequence.\n+ tokenizer (:obj:`TokenizerSpec`): a tokenizer instance which has properties ``unk_id``, ``sep_id``, ``bos_id``,\n+ ``eos_id``.\n+ num_samples (:obj:`int`, `optional`, defaults to :obj:`-1`): a number of samples you want to use for the\n+ dataset. If ``-1``, use all dataset. Useful for testing.\n+ tokens_in_batch (:obj:`int`, `optional`, defaults to :obj:`5000`): number of tokens in a batch including\n+ paddings and special tokens ([CLS], [SEP], [UNK]). This class :meth:`__getitem__` method returns not\n+ samples but ready batches. Number of samples in a batch is adjusted for input sequences lengths. If input\n+ sequences are short, then a batch will contain more samples. Before packing into batches, samples are\n+ sorted by number of tokens they contain. Sorting allows to reduce number of pad tokens in a batch\n+ significantly. Regular PyTorch data loader shuffling will only permute batches with changing their content.\n+ Proper shuffling is achieved via calling method :meth:`repack_batches_with_shuffle` every epoch.\n+ pad_label (:obj:`str`, `optional`, defaults to :obj:`'O'`): pad value to use for labels. It's also the neutral\n+ label both for punctuation and capitalization.\n+ punct_label_ids (:obj:`Dict[str, int]`, `optional`): dict to map punctuation labels to label ids. For dev set,\n+ use label ids generated during training to support cases when not all labels are present in the dev set.\n+ For training, it is recommended to set ``punct_label_ids`` to ``None`` or load from cache.\n+ capit_label_ids (:obj:`Dict[str, int]`, `optional`): same ``punct_label_ids`` for capitalization labels.\n+ ignore_extra_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`): whether to compute loss on\n+ tokens which are not first tokens in a word. For example, assume that word ``'tokenization'`` is tokenized\n+ into ``['token', 'ization']``. If ``ignore_extra_tokens=True``, loss mask for the word is\n+ ``[True, False]``, and if ``ignore_extra_tokens=False``, then loss mask is ``[True, True]``.\n+ ignore_start_end (:obj:`bool`, `optional`, defaults to :obj:`True`): whether to ignore [CLS] and [SEP] tokens\n+ in the loss_mask.\n+ use_cache (:obj:`bool`, `optional`, defaults to :obj:`True`): whether to use pickled features or not. If\n+ pickled features does not exist and ``use_cache=True``, then pickled features will be created. Pickled\n+ features are looked for and stored in ``cache_dir``. Pickled features include input ids, subtokens mask\n+ (mask of first tokens in words), encoded punctuation and capitalization labels, label ids. Features\n+ creation consumes considerable time and this ``use_cache=True`` significantly speeds up training starting.\n+\n+ .. warning::\n+ If you spawned more then 1 processes BEFORE dataset creation, then the ``use_cache`` parameter\n+ has to be ``True``. In PyTorch Lightning spawning is performed when `Trainer.fit()\n+ `_ or\n+ `Trainer.test() `_\n+ are called.\n+ cache_dir (:obj:`Union[str, os.PathLike]`, `optional`): a path to a directory where cache (pickled features)\n+ is stored. By default, ``text_file`` parent directory is used. This parameter is useful if dataset\n+ directory is read-only and you wish to pickle features. In such a case specify a path to directory which\n+ allows writing in ``cache_dir`` parameter.\n+ get_label_frequencies (:obj:`bool`, `optional`, defaults to :obj:`False`): whether to print and save label\n+ frequencies. Frequencies are showed if ``verbose`` parameter is ``True``. If\n+ ``get_label_frequencies=True``, then frequencies are saved into ``label_info_save_dir`` directory.\n+ label_info_save_dir (:obj:`Union[str, os.PathLike]`, `optional`): a path to a directory where label frequencies\n+ are saved. Be default a ``text_file`` parent directory is used. When method\n+ :meth:`save_labels_and_get_file_paths` is called label ids are saved into ``label_info_save_dir``\n+ directory. Parameters ``cache_dir`` and ``label_info_save_dir`` are added for cases when directory\n+ containing. This parameter is useful if directory containing ``text_file`` is read-only.\n+ punct_label_vocab_file (:obj:`Union[str, os.PathLike]`, `optional`): a path to a .csv file containing\n+ punctuation label vocabulary. Each line in such a vocabulary file contains exactly one label. The first\n+ line has to contain `pad_label`, otherwise error will be raised.\n+ capit_label_vocab_file (:obj:`Union[str, os.PathLike]`, `optional`): same as ``punct_label_vocab_file`` for\n+ capitalization labels.\n+ add_masks_and_segment_ids_to_batch (:obj:`bool`, `optional`, defaults to :obj:`True`): whether to add\n+ ``'loss_mask'``, ``'input_mask'``, ``'segment_ids'`` items to a batch. Useful for creation of tarred\n+ dataset and can NOT be used during model training and inference.\n+ verbose (:obj:`bool`, `optional`, defaults to :obj:`True`): whether to show data examples, label stats and\n+ other useful information.\n+ n_jobs (:obj:`int`, `optional`, defaults to :obj:`0`): number of workers used for tokenization, encoding\n+ labels, creating \"first token in word\" mask, and clipping. If ``n_jobs <= 0`` data preparation is performed\n+ without multiprocessing. By default ``n_jobs`` is equal to the number of CPUs.\n+\n+ .. warning::\n+ There can be deadlocking problems with some tokenizers (e.g. SentencePiece, HuggingFace AlBERT)\n+ if ``n_jobs > 0``.\n+\n+ tokenization_progress_queue (:obj:`multiprocessing.Queue`, `optional`): a queue for reporting tokenization\n+ progress. Useful for creation of tarred dataset\n+ batch_mark_up_progress_queue (:obj:`multiprocessing.Queue`, `optional`): a queue for reporting progress in\n+ deciding which samples batches will contain. Useful for creation of tarred dataset\n+ batch_building_progress_queue (:obj:`multiprocessing.Queue`, `optional`): a queue for reporting progress in\n+ batch creation (stacking and padding). Useful for creation of tarred dataset\n \"\"\"\n \n @property\n@@ -232,146 +873,101 @@ def output_types(self) -> Optional[Dict[str, NeuralType]]:\n \n def __init__(\n self,\n- text_file: str,\n- label_file: str,\n+ text_file: Union[str, os.PathLike],\n+ labels_file: Union[str, os.PathLike],\n max_seq_length: int,\n tokenizer: TokenizerSpec,\n num_samples: int = -1,\n+ tokens_in_batch: int = 5000,\n pad_label: str = 'O',\n- punct_label_ids: Dict[str, int] = None,\n- capit_label_ids: Dict[str, int] = None,\n+ punct_label_ids: Optional[Dict[str, int]] = None,\n+ capit_label_ids: Optional[Dict[str, int]] = None,\n ignore_extra_tokens: bool = False,\n- ignore_start_end: bool = False,\n+ ignore_start_end: bool = True,\n use_cache: bool = True,\n+ cache_dir: Optional[Union[str, os.PathLike]] = None,\n get_label_frequencies: bool = False,\n- punct_label_ids_file: str = 'punct_label_ids.csv',\n- capit_label_ids_file: str = 'capit_label_ids.csv',\n- ):\n+ label_info_save_dir: Optional[Union[str, os.PathLike]] = None,\n+ punct_label_vocab_file: Optional[Union[str, os.PathLike]] = None,\n+ capit_label_vocab_file: Optional[Union[str, os.PathLike]] = None,\n+ add_masks_and_segment_ids_to_batch: bool = True,\n+ verbose: bool = True,\n+ n_jobs: Optional[int] = 0,\n+ tokenization_progress_queue: Optional[mp.Queue] = None,\n+ batch_mark_up_progress_queue: Optional[mp.Queue] = None,\n+ batch_building_progress_queue: Optional[mp.Queue] = None,\n+ ) -> None:\n \"\"\" Initializes BertPunctuationCapitalizationDataset. \"\"\"\n-\n- if not (os.path.exists(text_file) and os.path.exists(label_file)):\n- raise FileNotFoundError(\n- f'{text_file} or {label_file} not found. The data should be splitted into 2 files: text.txt and \\\n- labels.txt. Each line of the text.txt file contains text sequences, where words are separated with \\\n- spaces. The labels.txt file contains corresponding labels for each word in text.txt, the labels are \\\n- separated with spaces. Each line of the files should follow the format: \\\n- [WORD] [SPACE] [WORD] [SPACE] [WORD] (for text.txt) and \\\n- [LABEL] [SPACE] [LABEL] [SPACE] [LABEL] (for labels.txt).'\n- )\n-\n- # Cache features\n- data_dir = os.path.dirname(text_file)\n- filename = os.path.basename(text_file)\n-\n- if not filename.endswith('.txt'):\n- raise ValueError(\"{text_file} should have extension .txt\")\n-\n- filename = filename[:-4]\n- vocab_size = getattr(tokenizer, \"vocab_size\", 0)\n- features_pkl = os.path.join(\n- data_dir,\n- \"cached_{}_{}_{}_{}_{}\".format(\n- filename, tokenizer.name, str(max_seq_length), str(vocab_size), str(num_samples)\n- ),\n+ self._check_constructor_parameters(\n+ text_file,\n+ labels_file,\n+ punct_label_ids,\n+ capit_label_ids,\n+ punct_label_vocab_file,\n+ capit_label_vocab_file,\n+ num_samples,\n+ use_cache,\n )\n-\n- self.punct_label_ids_file = os.path.join(data_dir, punct_label_ids_file)\n- self.capit_label_ids_file = os.path.join(data_dir, capit_label_ids_file)\n+ if punct_label_vocab_file is not None:\n+ punct_label_vocab_file = Path(punct_label_vocab_file).expanduser()\n+ punct_label_ids = load_label_ids(punct_label_vocab_file)\n+ if capit_label_vocab_file is not None:\n+ capit_label_vocab_file = Path(capit_label_vocab_file).expanduser()\n+ capit_label_ids = load_label_ids(capit_label_vocab_file)\n+ text_file, labels_file = Path(text_file).expanduser(), Path(labels_file).expanduser()\n+ if label_info_save_dir is None:\n+ self.label_info_save_dir = text_file.parent\n+ else:\n+ self.label_info_save_dir = Path(label_info_save_dir).expanduser()\n+\n+ self.tokens_in_batch = tokens_in_batch\n+ self.tokenizer = tokenizer\n+ self.pad_label = pad_label\n+ self.ignore_extra_tokens = ignore_extra_tokens\n+ self.ignore_start_end = ignore_start_end\n+ self.add_masks_and_segment_ids_to_batch = add_masks_and_segment_ids_to_batch\n+ self.verbose = verbose\n+ self.batch_mark_up_progress_queue = batch_mark_up_progress_queue\n+ self.batch_building_progress_queue = batch_building_progress_queue\n \n master_device = not torch.distributed.is_initialized() or torch.distributed.get_rank() == 0\n- cache_files_exist = (\n- os.path.exists(features_pkl)\n- and os.path.exists(self.punct_label_ids_file)\n- and os.path.exists(self.capit_label_ids_file)\n- )\n+ features_pkl = self._get_path_to_pkl_features(text_file, cache_dir, max_seq_length, num_samples)\n features = None\n- if master_device and not (cache_files_exist and use_cache):\n- if num_samples == 0:\n- raise ValueError(\"num_samples has to be positive\", num_samples)\n- logging.info(f'Processing {text_file}')\n- with open(text_file, 'r') as f:\n- text_lines = f.readlines()\n-\n- # Collect all possible labels\n- punct_unique_labels = set()\n- capit_unique_labels = set()\n- punct_labels_lines = []\n- capit_labels_lines = []\n- with open(label_file, 'r') as f:\n- for line in f:\n- line = line.strip().split()\n-\n- # extract punctuation and capitalization labels\n- punct_line, capit_line = zip(*line)\n- punct_labels_lines.append(punct_line)\n- capit_labels_lines.append(capit_line)\n-\n- punct_unique_labels.update(punct_line)\n- capit_unique_labels.update(capit_line)\n-\n- if len(punct_labels_lines) != len(text_lines):\n- raise ValueError(\"Labels file should contain labels for every word\")\n-\n- dataset = list(zip(text_lines, punct_labels_lines, capit_labels_lines))\n-\n- if num_samples > 0:\n- dataset = dataset[:num_samples]\n-\n- dataset = list(zip(*dataset))\n- text_lines = dataset[0]\n- punct_labels_lines = dataset[1]\n- capit_labels_lines = dataset[2]\n-\n- # for dev/test sets use label mapping from training set\n+ if master_device and not (features_pkl.is_file() and use_cache):\n+ if verbose:\n+ logging.info(f'Processing {text_file}')\n+ res = self._read_dataset(text_file, labels_file, num_samples)\n+ text_lines, punct_label_lines, capit_label_lines, punct_unique_labels, capit_unique_labels = res\n if punct_label_ids:\n- if len(punct_label_ids) != len(punct_unique_labels):\n- logging.info(\n- 'Not all labels from the specified'\n- + 'label_ids dictionary are present in the'\n- + 'current dataset. Using the provided'\n- + 'label_ids dictionary.'\n- )\n- else:\n- logging.info('Using the provided label_ids dictionary.')\n+ self._check_label_ids_vs_unique_labels(\n+ punct_label_ids, punct_unique_labels, 'punct', 'punctuation', labels_file\n+ )\n else:\n- logging.info(\n- 'Creating a new label to label_id dictionary.'\n- + ' It\\'s recommended to use label_ids generated'\n- + ' during training for dev/test sets to avoid'\n- + ' errors if some labels are not'\n- + ' present in the dev/test sets.'\n- + ' For training set label_ids should be None.'\n+ punct_label_ids = create_label_ids(punct_unique_labels, self.pad_label)\n+ if capit_label_ids:\n+ self._check_label_ids_vs_unique_labels(\n+ capit_label_ids, capit_unique_labels, 'capit', 'capitalzation', labels_file\n )\n-\n- def create_label_ids(unique_labels, pad_label=pad_label):\n- label_ids = {pad_label: 0}\n- if pad_label in unique_labels:\n- unique_labels.remove(pad_label)\n- for label in sorted(unique_labels):\n- label_ids[label] = len(label_ids)\n- return label_ids\n-\n- punct_label_ids = create_label_ids(punct_unique_labels)\n- capit_label_ids = create_label_ids(capit_unique_labels)\n-\n- self._save_label_ids(punct_label_ids, self.punct_label_ids_file)\n- self._save_label_ids(capit_label_ids, self.capit_label_ids_file)\n-\n- features = get_features(\n+ else:\n+ capit_label_ids = create_label_ids(capit_unique_labels, self.pad_label)\n+ features = _get_features(\n text_lines,\n+ punct_label_lines,\n+ capit_label_lines,\n max_seq_length,\n- tokenizer,\n- pad_label=pad_label,\n- punct_labels_lines=punct_labels_lines,\n- capit_labels_lines=capit_labels_lines,\n+ self.tokenizer,\n+ pad_label=self.pad_label,\n punct_label_ids=punct_label_ids,\n capit_label_ids=capit_label_ids,\n- ignore_extra_tokens=ignore_extra_tokens,\n- ignore_start_end=ignore_start_end,\n+ verbose=self.verbose,\n+ progress_queue=tokenization_progress_queue,\n+ n_jobs=n_jobs,\n )\n-\n- pickle.dump(features, open(features_pkl, \"wb\"))\n- logging.info(f'Features saved to {features_pkl}')\n+ if use_cache:\n+ features_pkl.parent.mkdir(parents=True, exist_ok=True)\n+ pickle.dump(tuple(list(features) + [punct_label_ids, capit_label_ids]), open(features_pkl, \"wb\"))\n+ if self.verbose:\n+ logging.info(f'Features saved to {features_pkl}')\n \n # wait until the master process writes to the processed data files\n if torch.distributed.is_initialized():\n@@ -379,309 +975,489 @@ def create_label_ids(unique_labels, pad_label=pad_label):\n \n if features is None:\n features = pickle.load(open(features_pkl, 'rb'))\n- logging.info(f'Features restored from {features_pkl}')\n-\n- self.all_input_ids = features[0]\n- self.all_segment_ids = features[1]\n- self.all_input_mask = features[2]\n- self.all_subtokens_mask = features[3]\n- self.all_loss_mask = features[4]\n- self.punct_all_labels = features[5]\n- self.capit_all_labels = features[6]\n- self.punct_label_ids = features[7]\n- self.capit_label_ids = features[8]\n+ li = features[-2:]\n+ self._check_label_ids_loaded_from_pkl(\n+ punct_label_ids, capit_label_ids, *li, punct_label_vocab_file, capit_label_vocab_file, features_pkl\n+ )\n+ punct_label_ids, capit_label_ids = li[-2], li[-1]\n+ if tokenization_progress_queue is not None:\n+ tokenization_progress_queue.put(len(features[0]))\n+ if self.verbose:\n+ logging.info(f'Features restored from {features_pkl}')\n+ features = features[:-2]\n+\n+ self.input_ids, self.subtokens_mask, self.punct_labels, self.capit_labels = features\n+ self.punct_label_ids, self.capit_label_ids = punct_label_ids, capit_label_ids\n+ self.batches = self._pack_into_batches(\n+ self.input_ids, self.subtokens_mask, self.punct_labels, self.capit_labels\n+ )\n \n if get_label_frequencies:\n- self.punct_label_frequencies = self._calculate_label_frequencies(self.punct_all_labels, data_dir, 'punct')\n- self.capit_label_frequencies = self._calculate_label_frequencies(self.capit_all_labels, data_dir, 'capit')\n+ self.punct_label_frequencies = self._calculate_and_save_label_frequencies(self.punct_labels, 'punct')\n+ self.capit_label_frequencies = self._calculate_and_save_label_frequencies(self.capit_labels, 'capit')\n+\n+ def _get_path_to_pkl_features(\n+ self, text_file: Path, cache_dir: Optional[Union[str, os.PathLike]], max_seq_length: int, num_samples: int\n+ ) -> Path:\n+ if cache_dir is None:\n+ cache_dir = text_file.parent\n+ else:\n+ cache_dir = Path(cache_dir).expanduser()\n+ vocab_size = getattr(self.tokenizer, \"vocab_size\", 0)\n+ features_pkl = cache_dir / \"cached.{}.{}.max_seq_length{}.vocab{}.{}.punctuation_capitalization.pkl\".format(\n+ text_file.stem,\n+ self.tokenizer.name,\n+ max_seq_length,\n+ vocab_size,\n+ f'num_samples{num_samples}' if num_samples > 0 else 'all_samples',\n+ )\n+ return features_pkl\n+\n+ @staticmethod\n+ def _check_constructor_parameters(\n+ text_file: Union[str, os.PathLike],\n+ labels_file: Union[str, os.PathLike],\n+ punct_label_ids: Optional[Dict[str, int]],\n+ capit_label_ids: Optional[Dict[str, int]],\n+ punct_label_vocab_file: Union[str, os.PathLike],\n+ capit_label_vocab_file: Union[str, os.PathLike],\n+ num_samples: int,\n+ use_cache: bool,\n+ ) -> None:\n+ if torch.distributed.is_initialized() and torch.distributed.get_world_size() > 1 and not use_cache:\n+ raise ValueError(\n+ f\"If you already created process group and the world size is greater than 1, then `use_cache` \"\n+ f\"parameter has to `True`. Only master process prepares features and if `use_cache=False`, then \"\n+ f\"other processes will not be able to obtain features. Alternatively, you may set `use_cache=False` \"\n+ f\"and set up data before spawning processes. Use `cache_dir` dataset directory with \"\n+ f\"`text_file` and `labels_file` is read-only.\"\n+ )\n+ if not (os.path.exists(text_file) and os.path.exists(labels_file)):\n+ raise FileNotFoundError(\n+ f'{text_file} or {labels_file} not found. The data should be split into 2 files: text.txt and'\n+ f'labels.txt. Each line of the text.txt file contains text sequences, where words are separated with'\n+ f'spaces. The labels.txt file contains corresponding labels for each word in text.txt, the labels are'\n+ f'separated with spaces. Each line of the files should follow the format:\\n'\n+ f' [WORD] [SPACE] [WORD] [SPACE] [WORD] (for text.txt) and '\n+ f' [LABEL] [SPACE] [LABEL] [SPACE] [LABEL] (for labels.txt).'\n+ )\n+ if not str(text_file).endswith('.txt'):\n+ raise ValueError(\n+ f\"Parameter `text_file` has to be path to a file with .txt extension, whereas `text_file={text_file}`\"\n+ )\n+ if not str(labels_file).endswith('.txt'):\n+ raise ValueError(\n+ f\"Parameter `labels_file` has to be path to a file with .txt extension, whereas \"\n+ f\"`labels_file={labels_file}`\"\n+ )\n+ if punct_label_ids is not None and punct_label_vocab_file is not None:\n+ punct_label_vocab_file = Path(punct_label_vocab_file).expanduser()\n+ file_punct_label_ids = load_label_ids(punct_label_vocab_file)\n+ if file_punct_label_ids != punct_label_ids:\n+ raise_not_equal_labels_error(\n+ first_labels=punct_label_ids,\n+ second_labels=file_punct_label_ids,\n+ first_labels_desc='Punctuation labels passed to the `PunctuationCapitalizationDataset` '\n+ 'constructor in parameter `punct_label_ids`',\n+ second_labels_desc=f'Punctuation labels loaded from file {punct_label_vocab_file} path to which '\n+ f'is passed in parameter `punct_label_vocab_file`',\n+ )\n+ if capit_label_ids is not None and capit_label_vocab_file is not None:\n+ capit_vocab_file = Path(capit_label_vocab_file).expanduser()\n+ file_capit_label_ids = load_label_ids(capit_vocab_file)\n+ if file_capit_label_ids != capit_label_ids:\n+ raise_not_equal_labels_error(\n+ first_labels=capit_label_ids,\n+ second_labels=file_capit_label_ids,\n+ first_labels_desc='Capitalization labels passed to the `PunctuationCapitalizationDataset` '\n+ 'constructor in parameter `capit_label_ids`',\n+ second_labels_desc=f'Capitalization labels loaded from file {capit_label_vocab_file} path to '\n+ f'which is passed in parameter `capit_label_vocab_file`',\n+ )\n+ if num_samples == 0:\n+ raise ValueError(\n+ f\"Parameter `num_samples` has to be positive or negative whereas `num_samples={num_samples}`. \"\n+ f\"Negative `num_samples` is for using all samples in a dataset.\"\n+ )\n \n- def _calculate_label_frequencies(self, all_labels: List[int], data_dir: str, name: str) -> Dict[str, float]:\n- \"\"\" Calculates labels frequencies \"\"\"\n- merged_labels = itertools.chain.from_iterable(all_labels)\n- logging.info('Three most popular labels')\n- _, label_frequencies, _ = get_label_stats(merged_labels, data_dir + '/label_count_' + name + '.tsv')\n- return label_frequencies\n+ @staticmethod\n+ def _check_label_ids_loaded_from_pkl(\n+ parameter_punct_label_ids: Dict[str, int],\n+ parameter_capit_label_ids: Dict[str, int],\n+ pkl_punct_label_ids: Any,\n+ pkl_capit_label_ids: Any,\n+ punct_label_vocab_file: Optional[Path],\n+ capit_label_vocab_file: Optional[Path],\n+ features_file: Path,\n+ ) -> None:\n+ if not isinstance(pkl_punct_label_ids, dict):\n+ raise ValueError(\n+ f\"Punctuation label ids loaded from features file {features_file} has wrong type \"\n+ f\"{type(pkl_punct_label_ids)}\"\n+ )\n+ if parameter_punct_label_ids is not None:\n+ if parameter_punct_label_ids != pkl_punct_label_ids:\n+ raise_not_equal_labels_error(\n+ first_labels=parameter_punct_label_ids,\n+ second_labels=pkl_punct_label_ids,\n+ first_labels_desc=\"Punctuation labels passed in parameter `punct_label_ids`\"\n+ if punct_label_vocab_file is None\n+ else f\"Punctuation labels loaded from file {punct_label_vocab_file}\",\n+ second_labels_desc=f\"Punctuation label ids loaded from features file {features_file}\",\n+ )\n+ if not isinstance(pkl_capit_label_ids, dict):\n+ raise ValueError(\n+ f\"Capitalization label ids loaded from features file {features_file} has wrong type \"\n+ f\"{type(pkl_capit_label_ids)}\"\n+ )\n+ if parameter_capit_label_ids is not None:\n+ if parameter_capit_label_ids != pkl_capit_label_ids:\n+ raise_not_equal_labels_error(\n+ first_labels=parameter_capit_label_ids,\n+ second_labels=pkl_capit_label_ids,\n+ first_labels_desc=\"Capitalization labels passed in parameter `capit_label_ids`\"\n+ if capit_label_vocab_file is None\n+ else f\"Capitalization labels loaded from file {capit_label_vocab_file}\",\n+ second_labels_desc=f\"Capitalization label ids loaded from features file {features_file}\",\n+ )\n \n- def _save_label_ids(self, label_ids: Dict[str, int], filename: str) -> None:\n- \"\"\" Saves label ids map to a file \"\"\"\n- with open(filename, 'w') as out:\n- labels, _ = zip(*sorted(label_ids.items(), key=lambda x: x[1]))\n- out.write('\\n'.join(labels))\n- logging.info(f'Labels: {label_ids}')\n- logging.info(f'Labels mapping saved to : {out.name}')\n-\n- def __len__(self):\n- return len(self.all_input_ids)\n-\n- def __getitem__(self, idx):\n- return (\n- np.array(self.all_input_ids[idx]),\n- np.array(self.all_segment_ids[idx]),\n- np.array(self.all_input_mask[idx], dtype=np.long),\n- np.array(self.all_subtokens_mask[idx]),\n- np.array(self.all_loss_mask[idx]),\n- np.array(self.punct_all_labels[idx]),\n- np.array(self.capit_all_labels[idx]),\n- )\n+ @staticmethod\n+ def _check_label_ids_vs_unique_labels(\n+ label_ids: Dict[str, int], unique_labels: Set[str], label_type: str, task: str, label_file: Path\n+ ) -> None:\n+ if unique_labels - set(label_ids):\n+ not_present_labels = list(unique_labels - set(label_ids))\n+ raise ValueError(\n+ f\"{len(not_present_labels)} {task} labels found in {label_file} are not present in \"\n+ f\"`{label_type}_label_ids`. Examples of unexpected labels from {label_file}: {not_present_labels[:3]}\"\n+ )\n \n+ @staticmethod\n+ def _read_dataset(\n+ text_file: Path, labels_file: Path, num_samples: int\n+ ) -> Tuple[Tuple[str, ...], Tuple[str, ...], Tuple[str, ...], Set[str], Set[str]]:\n+ with open(text_file, 'r') as f:\n+ text_lines = f.readlines()\n+ punct_unique_labels, capit_unique_labels = set(), set()\n+ punct_labels_lines, capit_labels_lines = [], []\n+ with labels_file.open() as f:\n+ for i, line in enumerate(f):\n+ pairs = line.split()\n+ if not all([len(p) == 2 for p in pairs]):\n+ raise ValueError(\n+ f\"Some label pairs are not pairs but have wrong length (!= 2) in line {i} in label file \"\n+ f\"{labels_file}\"\n+ )\n+ words = text_lines[i].split()\n+ if len(pairs) != len(words):\n+ raise ValueError(\n+ f\"In line {i} in text file {text_file} number of words {len(words)} is not equal to the \"\n+ f\"number of labels {len(pairs)} in labels file {labels_file}.\"\n+ )\n+ punct_line, capit_line = zip(*pairs)\n+ punct_labels_lines.append(punct_line)\n+ capit_labels_lines.append(capit_line)\n+ punct_unique_labels.update(punct_line)\n+ capit_unique_labels.update(capit_line)\n+\n+ if len(punct_labels_lines) != len(text_lines):\n+ raise ValueError(\n+ f\"Number of text lines {len(text_lines)} in text file {text_file} is not equal to the number of lines \"\n+ f\"{len(punct_labels_lines)} in labels file {labels_file}.\"\n+ )\n+ dataset = list(zip(text_lines, punct_labels_lines, capit_labels_lines))\n+ if len(dataset) == 0:\n+ raise ValueError(f\"Dataset loaded from files {text_file} and {labels_file} is empty.\")\n+ if num_samples > 0:\n+ dataset = dataset[:num_samples]\n+ text_lines, punct_labels_lines, capit_labels_lines = zip(*dataset)\n+ return text_lines, punct_labels_lines, capit_labels_lines, punct_unique_labels, capit_unique_labels\n+\n+ def _mark_up_batches(self, input_ids: List[ArrayLike]) -> Tuple[List[int], List[int], List[int]]:\n+ \"\"\"\n+ Computes indices of first samples in batch, batch sizes, seq lengths for batches. ``input_ids`` has to be\n+ sorted by number of tokens in ascending order.\n \n-def _get_subtokens_and_subtokens_mask(query: str, tokenizer: TokenizerSpec) -> Tuple[List[str], List[int]]:\n- \"\"\"\n- Tokenizes input query into subtokens and creates subtokens mask. Subtokens mask is an array of the same length as\n- subtokens array and contains zeros and ones in which. If element of mask equals 1, then corresponding subtoken in\n- subtokens array is first subtoken in some word\n- Args:\n- query: a string that will be tokenized\n- tokenizer: an instance of tokenizer\n- Returns:\n- subtokens: list of subtokens\n- subtokens_mask: list of ints\n- \"\"\"\n- words = query.strip().split()\n- subtokens = []\n- subtokens_mask = []\n- for j, word in enumerate(words):\n- word_tokens = tokenizer.text_to_tokens(word)\n- subtokens.extend(word_tokens)\n- subtokens_mask.append(1)\n- subtokens_mask.extend([0] * (len(word_tokens) - 1))\n- return subtokens, subtokens_mask\n-\n-\n-def _check_max_seq_length_and_margin_and_step(max_seq_length: int, margin: int, step: int):\n- \"\"\"\n- Checks values of ``max_seq_length``, ``margin``, and ``step``.\n- Args:\n- max_seq_length: a segment length with ``[CLS]`` and ``[SEP]`` tokens\n- margin: a number of input tokens near edges of segments which are not used in punctuation and capitalization\n- prediction.\n- step: offset of consequent segments.\n- Returns:\n- None\n- \"\"\"\n- if max_seq_length < 3:\n- raise ValueError(\n- f\"Parameter `max_seq_length={max_seq_length}` cannot be less than 3 because `max_seq_length` is a length \"\n- f\"of a segment with [CLS] and [SEP] tokens.\"\n- )\n- if margin >= (max_seq_length - 2) // 2 and margin > 0 or margin < 0:\n- raise ValueError(\n- f\"Parameter `margin` has to be not negative and less than `(max_seq_length - 2) // 2`. Don't forget about \"\n- f\"CLS and EOS tokens in the beginning and the end of segment. margin={margin}, \"\n- f\"max_seq_length={max_seq_length}\"\n- )\n- if step <= 0:\n- raise ValueError(f\"Parameter `step` has to be positive whereas step={step}\")\n- if step > max_seq_length - 2 - 2 * margin:\n- logging.warning(\n- f\"Parameter step={step} is too big. It will be reduced to `min(max_seq_length, + 2) \"\n- f\"- 2 - 2 * margin`.\"\n- )\n+ Batches are marked up with respect to following conditions:\n+ - total number of tokens in batch including paddings is less or equal to ``self.tokens_in_batch``\n+ - batch size is evenly divisible by 8 (except for the last batch)\n+ - seq length (elements of the third returned object) is evenly divisible by 8\n \n+ If ``self.batch_mark_up_progress_queue`` is not None, then the progress in mark up is reported via\n+ ``self.batch_mark_up_progress_queue``. Otherwise, ``tqdm`` instance is created in this function.\n \n-def get_features_infer(\n- queries: List[str],\n- tokenizer: TokenizerSpec,\n- max_seq_length: int = 64,\n- step: Optional[int] = 8,\n- margin: Optional[int] = 16,\n-) -> Tuple[\n- List[List[int]], List[List[int]], List[List[int]], List[List[int]], List[int], List[int], List[bool], List[bool],\n-]:\n- \"\"\"\n- Processes the data and returns features.\n+ Args:\n+ input_ids: a list of 1D int32 arrays. Elements of ``input_ids`` have to be sorted by length in ascending\n+ order\n \n- Args:\n- queries: text sequences\n- tokenizer: such as AutoTokenizer\n- max_seq_length: max sequence length minus 2 for [CLS] and [SEP]\n- step: relative shift of consequent segments into which long queries are split. Long queries are split into\n- segments which can overlap. Parameter ``step`` controls such overlapping. Imagine that queries are\n- tokenized into characters, ``max_seq_length=5``, and ``step=2``. In such a case query \"hello\" is\n- tokenized into segments ``[['[CLS]', 'h', 'e', 'l', '[SEP]'], ['[CLS]', 'l', 'l', 'o', '[SEP]']]``.\n- margin: number of subtokens near edges of segments which are not used for punctuation and capitalization\n- prediction. The first segment does not have left margin and the last segment does not have right\n- margin. For example, if input sequence is tokenized into characters, ``max_seq_length=5``,\n- ``step=1``, and ``margin=1``, then query \"hello\" will be tokenized into segments\n- ``[['[CLS]', 'h', 'e', 'l', '[SEP]'], ['[CLS]', 'e', 'l', 'l', '[SEP]'],\n- ['[CLS]', 'l', 'l', 'o', '[SEP]']]``. These segments are passed to the model. Before final predictions\n- computation, margins are removed. In the next list, subtokens which logits are not used for final\n- predictions computation are marked with asterisk: ``[['[CLS]'*, 'h', 'e', 'l'*, '[SEP]'*],\n- ['[CLS]'*, 'e'*, 'l', 'l'*, '[SEP]'*], ['[CLS]'*, 'l'*, 'l', 'o', '[SEP]'*]]``.\n+ Returns:\n+ batch_beginnings: a list of indices in ``input_ids`` of first samples of every batch\n+ batch_sizes: a list of numbers of samples in batches\n+ batch_seq_lengths: a list of sequence lengths after padding for every batch\n+ \"\"\"\n+ batch_beginnings, batch_sizes, batch_seq_lengths = [], [], []\n+ current_max_length = 0\n+ start = 0\n+ if self.batch_mark_up_progress_queue is None:\n+ inp_iterator = tqdm(enumerate(input_ids), total=len(input_ids), desc=\"Batch mark up\", unit=\"query\")\n+ else:\n+ inp_iterator = enumerate(input_ids)\n+ progress_made = 0\n+ for i, inp in inp_iterator:\n+ current_max_length = max(current_max_length, ceil(len(inp) / 8) * 8)\n+ if current_max_length * (i + 1 - start) > self.tokens_in_batch:\n+ batch_size = (i - start) // 8 * 8\n+ if batch_size == 0:\n+ if i > start:\n+ batch_size = i - start\n+ logging.warning(\n+ f\"Could not create batch with multiple of 8 size. Probably there is a too long sequence in \"\n+ f\"the dataset. current_max_length={current_max_length}. Batch size will be reduced to \"\n+ f\"{batch_size}. tokens_in_batch={self.tokens_in_batch}. The batch includes sequences from \"\n+ f\"{start} to {i - 1}.\"\n+ )\n+ else:\n+ logging.warning(\n+ f\"Input sequence number {i - 1} is too long. Could not fit it into batch with \"\n+ f\"{self.tokens_in_batch} tokens. Sequence number {i - 1} will not be added to batches.\"\n+ )\n+ start = i\n+ current_max_length = ceil(len(inp) / 8) * 8\n+ continue\n+ seq_length = ceil(max([len(inp) for inp in input_ids[start : start + batch_size]]) / 8) * 8\n+ batch_beginnings.append(start)\n+ batch_sizes.append(batch_size)\n+ batch_seq_lengths.append(seq_length)\n+ start += batch_size\n+ current_max_length = ceil(max([len(inp) for inp in input_ids[start : i + 1]]) / 8) * 8\n+ if self.batch_mark_up_progress_queue is not None:\n+ progress_made += 1\n+ if progress_made >= BATCH_MARK_UP_PROGRESS_REPORT_PERIOD:\n+ self.batch_mark_up_progress_queue.put(progress_made)\n+ progress_made = 0\n+ if start < len(input_ids):\n+ seq_length = ceil(max([len(inp) for inp in input_ids[start:]]) / 8) * 8\n+ batch_beginnings.append(start)\n+ batch_sizes.append(len(input_ids) - start)\n+ batch_seq_lengths.append(seq_length)\n+ if self.batch_mark_up_progress_queue is not None:\n+ self.batch_mark_up_progress_queue.put(progress_made)\n+ assert sum(batch_sizes) == len(input_ids)\n+ for i in range(len(batch_beginnings) - 1):\n+ assert batch_beginnings[i] + batch_sizes[i] == batch_beginnings[i + 1]\n+ assert batch_seq_lengths[i] >= max(\n+ [len(inp) for inp in input_ids[batch_beginnings[i] : batch_beginnings[i] + batch_sizes[i]]]\n+ )\n+ return batch_beginnings, batch_sizes, batch_seq_lengths\n \n- Returns:\n- all_input_ids: list of input ids of all segments\n- all_segment_ids: token type ids of all segments\n- all_input_mask: attention mask to use for BERT model\n- all_subtokens_mask: masks out all subwords besides the first one\n- all_quantities_of_preceding_words: number of words in query preceding a segment. Used for joining\n- predictions from overlapping segments.\n- all_query_ids: index of a query to which segment belongs\n- all_is_first: is segment first segment in a query\n- all_is_last: is segment last segment in a query\n- \"\"\"\n- st = []\n- stm = []\n- sent_lengths = []\n- for i, query in enumerate(queries):\n- subtokens, subtokens_mask = _get_subtokens_and_subtokens_mask(query, tokenizer)\n- sent_lengths.append(len(subtokens))\n- st.append(subtokens)\n- stm.append(subtokens_mask)\n- _check_max_seq_length_and_margin_and_step(max_seq_length, margin, step)\n- if max_seq_length > max(sent_lengths) + 2:\n- max_seq_length = max(sent_lengths) + 2\n- # If `max_seq_length` is greater than maximum length of input query, parameters ``margin`` and ``step`` are\n- # not used will not be used.\n- step = 1\n- # Maximum number of word subtokens in segment. The first and the last tokens in segment are CLS and EOS\n- length = max_seq_length - 2\n- else:\n- # Maximum number of word subtokens in segment. The first and the last tokens in segment are CLS and EOS\n- length = max_seq_length - 2\n- step = min(length - margin * 2, step)\n- logging.info(f'Max length: {max_seq_length}')\n- get_stats(sent_lengths)\n- all_input_ids, all_segment_ids, all_subtokens_mask, all_input_mask, all_input_mask = [], [], [], [], []\n- all_quantities_of_preceding_words, all_query_ids, all_is_first, all_is_last = [], [], [], []\n- for q_i, query_st in enumerate(st):\n- q_inp_ids, q_segment_ids, q_subtokens_mask, q_inp_mask, q_quantities_of_preceding_words = [], [], [], [], []\n- for i in range(0, max(len(query_st), length) - length + step, step):\n- subtokens = [tokenizer.cls_token] + query_st[i : i + length] + [tokenizer.sep_token]\n- q_inp_ids.append(tokenizer.tokens_to_ids(subtokens))\n- q_segment_ids.append([0] * len(subtokens))\n- q_subtokens_mask.append([0] + stm[q_i][i : i + length] + [0])\n- q_inp_mask.append([1] * len(subtokens))\n- q_quantities_of_preceding_words.append(np.count_nonzero(stm[q_i][:i]))\n- all_input_ids.append(q_inp_ids)\n- all_segment_ids.append(q_segment_ids)\n- all_subtokens_mask.append(q_subtokens_mask)\n- all_input_mask.append(q_inp_mask)\n- all_quantities_of_preceding_words.append(q_quantities_of_preceding_words)\n- all_query_ids.append([q_i] * len(q_inp_ids))\n- all_is_first.append([True] + [False] * (len(q_inp_ids) - 1))\n- all_is_last.append([False] * (len(q_inp_ids) - 1) + [True])\n- return (\n- list(itertools.chain(*all_input_ids)),\n- list(itertools.chain(*all_segment_ids)),\n- list(itertools.chain(*all_input_mask)),\n- list(itertools.chain(*all_subtokens_mask)),\n- list(itertools.chain(*all_quantities_of_preceding_words)),\n- list(itertools.chain(*all_query_ids)),\n- list(itertools.chain(*all_is_first)),\n- list(itertools.chain(*all_is_last)),\n- )\n+ def _pack_into_batches(\n+ self,\n+ input_ids: List[ArrayLike],\n+ subtokens_mask: List[ArrayLike],\n+ punct_labels: List[ArrayLike],\n+ capit_labels: List[ArrayLike],\n+ ) -> List[Dict[str, ArrayLike]]:\n+ \"\"\"\n+ Shuffle input sequences, sort them by number of tokens, pad, and pack into batches which satisfy following\n+ conditions:\n+ - total number of tokens in batch including paddings is less or equal to ``self.tokens_in_batch``\n+ - batch size is evenly divisible by 8 (except for the last batch)\n+ - seq length (elements of the third returned object) is evenly divisible by 8\n+ Created batches are shuffled before returning.\n+\n+ If ``self.add_masks_and_segment_ids_to_batch`` is ``True``, then ``'segment_ids'``, ``'loss_mask'``, and\n+ ``'input_mask'`` are added to the batch.\n+\n+ If ``self.batch_building_progress_queue`` is not ``None``, then padding progress is reported to\n+ ``self.batch_building_progress_queue``. Otherwise, a new ``tqdm`` instance is created in ``pack_into_batches``\n+ method.\n+\n+ Args:\n+ input_ids: a list of 1D int32 arrays which contain token ids of dataset source\n+ subtokens_mask: a list of 1D boolean arrays which elements are ``True`` if corresponding token is the\n+ first token in some word\n+ punct_labels: a list of 1D int32 arrays which contain encoded punctuation labels\n+ capit_labels: a list of 1D int32 arrays which contain encoded capitalization labels\n+\n+ Returns:\n+ a list of batches. Each batch is a dictionary with items:\n+ - ``'input_ids'``: a ``np.int32`` numpy array;\n+ - ``'subtokens_mask'``: a boolean numpy array;\n+ - ``'punct_labels'``: a ``np.int32`` numpy array;\n+ - ``'capit_labels'``: a ``np.int32`` numpy array.\n+ If ``self.add_masks_and_segment_ids_to_batch`` is ``True``, then a batch also contain items\n+ - ``'segment_ids'``: a ``np.int8`` numpy array;\n+ - ``'input_mask'``: a boolean numpy array;\n+ - ``'loss_mask'``: a boolean numpy array.\n+\n+ The values of a batch dictionary are numpy arrays of identical shape.\n+ \"\"\"\n+ zipped = list(zip(input_ids, subtokens_mask, punct_labels, capit_labels))\n+ random.shuffle(zipped)\n+ input_ids, subtokens_mask, punct_labels, capit_labels = zip(*sorted(zipped, key=lambda x: x[0].shape[0]))\n+ batch_beginnings, batch_sizes, batch_seq_lengths = self._mark_up_batches(input_ids)\n+ batches = []\n+ if self.batch_building_progress_queue is None:\n+ inp_iterator = tqdm(\n+ zip(batch_beginnings, batch_sizes, batch_seq_lengths),\n+ total=len(batch_beginnings),\n+ desc=\"Batch building\",\n+ unit=\"batch\",\n+ )\n+ else:\n+ # In this case we report number of queries not number of batches\n+ inp_iterator = zip(batch_beginnings, batch_sizes, batch_seq_lengths)\n+ progress_made = 0\n+ for start, size, length in inp_iterator:\n+ batch_input_ids = pad(input_ids[start : start + size], length, self.tokenizer.pad_id)\n+ batch_subtokens_mask = pad(subtokens_mask[start : start + size], length, False)\n+ batch = {\n+ \"input_ids\": batch_input_ids,\n+ \"subtokens_mask\": batch_subtokens_mask,\n+ \"punct_labels\": pad(\n+ punct_labels[start : start + size], length, self.punct_label_ids[self.pad_label]\n+ ).astype(np.int64),\n+ \"capit_labels\": pad(\n+ capit_labels[start : start + size], length, self.capit_label_ids[self.pad_label]\n+ ).astype(np.int64),\n+ }\n+ if self.add_masks_and_segment_ids_to_batch:\n+ batch_segment_ids, batch_input_mask, batch_loss_mask = create_masks_and_segment_ids(\n+ batch_input_ids,\n+ batch_subtokens_mask,\n+ self.tokenizer.pad_id,\n+ self.tokenizer.cls_id,\n+ self.tokenizer.sep_id,\n+ self.ignore_start_end,\n+ self.ignore_extra_tokens,\n+ )\n+ batch['segment_ids'] = batch_segment_ids\n+ batch['input_mask'] = batch_input_mask\n+ batch['loss_mask'] = batch_loss_mask\n+ batches.append(batch)\n+ if self.batch_building_progress_queue is not None:\n+ progress_made += size\n+ if progress_made >= BATCH_BUILDING_PROGRESS_REPORT_PERIOD:\n+ self.batch_building_progress_queue.put(progress_made)\n+ progress_made = 0\n+ if self.batch_building_progress_queue is not None:\n+ self.batch_building_progress_queue.put(progress_made)\n+ random.shuffle(batches)\n+ return batches\n+\n+ def repack_batches_with_shuffle(self) -> None:\n+ \"\"\"A function for proper shuffling of a dataset. Pytorch data loader shuffing will only permute batches.\"\"\"\n+ logging.info(\"Shuffling training dataset\")\n+ self.batches = self._pack_into_batches(\n+ self.input_ids, self.subtokens_mask, self.punct_labels, self.capit_labels\n+ )\n \n+ def _calculate_and_save_label_frequencies(self, all_labels: List[ArrayLike], name: str) -> Dict[str, float]:\n+ \"\"\"Calculates and saves labels frequencies in :attr:`label_info_save_dir`.\"\"\"\n+ merged_labels = itertools.chain.from_iterable(all_labels)\n+ if self.verbose:\n+ logging.info('Three most popular labels')\n+ self.label_info_save_dir.mkdir(parents=True, exist_ok=True)\n+ _, label_frequencies, _ = get_label_stats(\n+ merged_labels, str(self.label_info_save_dir / f'label_count_{name}.tsv')\n+ )\n+ return label_frequencies\n \n-class BertPunctuationCapitalizationInferDataset(Dataset):\n- \"\"\"\n- Creates dataset to use during inference for punctuation and capitalization tasks with a pretrained model.\n- For dataset to use during training with labels, see BertPunctuationCapitalizationDataset.\n+ def save_labels_and_get_file_paths(\n+ self, punct_labels_file_name: str, capit_labels_file_name: str\n+ ) -> Tuple[Path, Path]:\n+ \"\"\"\n+ Saves label ids into files located in ``self.label_info_save_dir``. Saved label ids are usually used for\n+ ``.nemo`` checkpoint creation.\n \n- Parameters ``max_seq_length``, ``step``, ``margin`` are for controlling the way queries are split into segments\n- which then processed by the model. Parameter ``max_seq_length`` is a length of a segment after tokenization\n- including special tokens [CLS] in the beginning and [SEP] in the end of a segment. Parameter ``step`` is shift\n- between consequent segments. Parameter ``margin`` is used to exclude negative effect of subtokens near\n- borders of segments which have only one side context.\n+ The signatures of this method and the signature of the method\n+ :meth:`~nemo.collections.nlp.data.token_classification.BertPunctuationCapitalizationTarredDataset.save_labels_and_get_file_paths`\n+ must be identical.\n \n- Args:\n- queries: list of sequences.\n- tokenizer: such as AutoTokenizer\n- max_seq_length: max sequence length minus 2 for [CLS] and [SEP]\n- step: relative shift of consequent segments into which long queries are split. Long queries are split into\n- segments which can overlap. Parameter ``step`` controls such overlapping. Imagine that queries are\n- tokenized into characters, ``max_seq_length=5``, and ``step=2``. In such a case query \"hello\" is\n- tokenized into segments ``[['[CLS]', 'h', 'e', 'l', '[SEP]'], ['[CLS]', 'l', 'l', 'o', '[SEP]']]``.\n- margin: number of subtokens in the beginning and the end of segments which are not used for prediction\n- computation. The first segment does not have left margin and the last segment does not have right\n- margin. For example, if input sequence is tokenized into characters, ``max_seq_length=5``,\n- ``step=1``, and ``margin=1``, then query \"hello\" will be tokenized into segments\n- ``[['[CLS]', 'h', 'e', 'l', '[SEP]'], ['[CLS]', 'e', 'l', 'l', '[SEP]'],\n- ['[CLS]', 'l', 'l', 'o', '[SEP]']]``. These segments are passed to the model. Before final predictions\n- computation, margins are removed. In the next list, subtokens which logits are not used for final\n- predictions computation are marked with asterisk: ``[['[CLS]'*, 'h', 'e', 'l'*, '[SEP]'*],\n- ['[CLS]'*, 'e'*, 'l', 'l'*, '[SEP]'*], ['[CLS]'*, 'l'*, 'l', 'o', '[SEP]'*]]``.\n- \"\"\"\n+ Args:\n+ punct_labels_file_name (:obj:`str`): a name of a punctuation labels file\n+ capit_labels_file_name (:obj:`str`): a name of a capitalization labels file\n \n- @property\n- def output_types(self) -> Optional[Dict[str, NeuralType]]:\n- \"\"\"Returns definitions of module output ports.\n-\n- input_ids: ids of word subtokens encoded using tokenizer\n- segment_ids: an array of zeros\n- input_mask: attention mask. Zeros if input is padding.\n- subtoken_mask: a mask used for retrieving predictions for words. An element equals ``1`` if corresponding\n- token is the first token in some word and zero otherwise. For example, if input query\n- \"language processing\" is tokenized into [\"[CLS]\", \"language\", \"process\", \"ing\", \"SEP\"], then\n- ``subtokens_mask`` will be [0, 1, 1, 0, 0].\n- quantities_of_preceding_words: number of words preceding a segment in a query. It is used for uniting\n- predictions from different segments if such segments overlap. For example, if query \"hello john\" is\n- tokenized into segments ``[['hell', 'o'], ['john']]``, then ``quantities_of_preceding_words=[0, 1]``.\n- query_ids: ids of queries to which segments belong. For example, if ``queries=[\"foo\", \"bar\"]`` are\n- segmented into ``[[['[CLS]', 'f', 'o', '[SEP]'], ['[CLS]', 'o', 'o', '[SEP]']],\n- [['[CLS]', 'b', 'a', '[SEP]'], ['[CLS]', 'a', 'r', '[SEP]']]]``, then for batch\n- [['[CLS]', 'o', 'o', '[SEP]'], ['[CLS]', 'b', 'a', '[SEP]'], ['[CLS]', 'a', 'r', '[SEP]']]\n- ``query_ids=[0, 1, 1]``.\n- is_first: is segment the first segment in query. The left margin of the first segment in a query is not\n- removed and this parameter is used to identify first segments.\n- is_last: is segment the last segment in query. The right margin of the last segment in a query is not\n- removed and this parameter is used to identify last segments.\n+ Returns:\n+ :obj:`Tuple[pathlib.Path, pathlib.Path]`: a tuple containing:\n \n+ - :obj:`pathlib.Path`: a path to the saved punctuation labels file\n+ - :obj:`pathlib.Path`: a path to the saved capitalization labels file\n \"\"\"\n- return {\n- 'input_ids': NeuralType(('B', 'T'), ChannelType()),\n- 'segment_ids': NeuralType(('B', 'T'), ChannelType()),\n- 'input_mask': NeuralType(('B', 'T'), MaskType()),\n- 'subtokens_mask': NeuralType(('B', 'T'), MaskType()),\n- 'quantities_of_preceding_words': NeuralType(('B',), Index()),\n- 'query_ids': NeuralType(('B',), Index()),\n- 'is_first': NeuralType(('B',), BoolType()),\n- 'is_last': NeuralType(('B',), BoolType()),\n- }\n-\n- def __init__(\n- self, queries: List[str], tokenizer: TokenizerSpec, max_seq_length: int = 128, step: int = 32, margin: int = 16\n- ):\n- features = get_features_infer(\n- queries=queries, max_seq_length=max_seq_length, tokenizer=tokenizer, step=step, margin=margin\n- )\n- self.all_input_ids: List[List[int]] = features[0]\n- self.all_segment_ids: List[List[int]] = features[1]\n- self.all_input_mask: List[List[int]] = features[2]\n- self.all_subtokens_mask: List[List[int]] = features[3]\n- self.all_quantities_of_preceding_words: List[int] = features[4]\n- self.all_query_ids: List[int] = features[5]\n- self.all_is_first: List[bool] = features[6]\n- self.all_is_last: List[bool] = features[7]\n+ nemo_dir = self.label_info_save_dir / LABEL_ID_DIR_FOR_NEMO_CHECKPOINT\n+ punct_labels_file = nemo_dir / punct_labels_file_name\n+ capit_labels_file = nemo_dir / capit_labels_file_name\n+ save_label_ids(self.punct_label_ids, punct_labels_file)\n+ save_label_ids(self.capit_label_ids, capit_labels_file)\n+ return punct_labels_file, capit_labels_file\n \n def __len__(self) -> int:\n- return len(self.all_input_ids)\n-\n- def collate_fn(\n- self, batch: List[Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, int, int, bool, bool]]\n- ) -> Tuple[\n- torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, Tuple[int], Tuple[int], Tuple[bool], Tuple[bool]\n- ]:\n- inp_ids, segment_ids, inp_mask, st_mask, n_preceding, query_ids, is_first, is_last = zip(*batch)\n- return (\n- pad_sequence([torch.tensor(x) for x in inp_ids], batch_first=True, padding_value=0),\n- pad_sequence([torch.tensor(x) for x in segment_ids], batch_first=True, padding_value=0),\n- pad_sequence([torch.tensor(x) for x in inp_mask], batch_first=True, padding_value=0),\n- pad_sequence([torch.tensor(x) for x in st_mask], batch_first=True, padding_value=0),\n- n_preceding,\n- query_ids,\n- is_first,\n- is_last,\n- )\n+ return len(self.batches)\n \n- def __getitem__(self, idx: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, int, int, bool, bool]:\n- return (\n- np.array(self.all_input_ids[idx]),\n- np.array(self.all_segment_ids[idx]),\n- np.array(self.all_input_mask[idx], dtype=np.float32),\n- np.array(self.all_subtokens_mask[idx]),\n- self.all_quantities_of_preceding_words[idx],\n- self.all_query_ids[idx],\n- self.all_is_first[idx],\n- self.all_is_last[idx],\n- )\n+ def collate_fn(self, batches: List[Dict[str, ArrayLike]]) -> Dict[str, torch.Tensor]:\n+ \"\"\"\n+ Return zeroth batch from ``batches`` list passed for collating and casts ``'segment_ids'``, ``'punct_labels'``,\n+ ``'capit_labels'`` to types supported by\n+ :class:`~nemo.collections.nlp.models.token_classification.punctuation_capitalization_model.PunctuationCapitalizationModel`.\n+ All output tensors have shape ``[Batch, Time]``.\n+\n+ .. warning::\n+ A ``batch_size`` parameter of a PyTorch data loader and sampler has to be ``1``.\n+\n+ Args:\n+ batches (:obj:`List[Dict[str, ArrayLike]]`): a list containing 1 batch passed for collating\n+\n+ Returns:\n+ :obj:`Dict[str, torch.Tensor]`: a batch dictionary with following items (for detailed description of batch\n+ items see method :meth:`__getitem__`):\n+\n+ - ``'input_ids'`` (:obj:`torch.Tensor`): :obj:`torch.int32` tensor,\n+ - ``'subtokens_mask'`` (:obj:`torch.Tensor`): :obj:`torch.bool` tensor,\n+ - ``'punct_labels'`` (:obj:`torch.Tensor`): :obj:`torch.int64` tensor,\n+ - ``'capit_labels'`` (:obj:`torch.Tensor`): :obj:`torch.int64` tensor,\n+ - ``'segment_ids'`` (:obj:`torch.Tensor`): :obj:`torch.int32` tensor,\n+ - ``'input_mask'`` (:obj:`torch.Tensor`): :obj:`torch.bool` tensor,\n+ - ``'loss_mask'`` (:obj:`torch.Tensor`): :obj:`torch.bool` tensor.\n+ \"\"\"\n+ batch = {k: torch.as_tensor(v) for k, v in batches[0].items()}\n+ batch['segment_ids'] = batch['segment_ids'].int()\n+ batch['punct_labels'] = batch['punct_labels'].long()\n+ batch['capit_labels'] = batch['capit_labels'].long()\n+ return batch\n+\n+ def __getitem__(self, idx: int) -> Dict[str, ArrayLike]:\n+ \"\"\"\n+ Return a batch with index ``idx``. The values of a batch dictionary are numpy arrays of identical shapes\n+ ``[Batch, Time]``. Labels are identical for all tokens in a word. For example, if\n+\n+ - word ``'Tokenization'`` is tokenized into tokens ``['token', 'ization']``,\n+ - it is followed by comma,\n+\n+ then punctuation labels are ``[',', ',']`` and capitalization labels are ``['U', 'U']`` (``'U'`` is a label\n+ for words which start with upper case character).\n+\n+ Args:\n+ idx: an index of returned batch\n+\n+ Returns:\n+ :obj:`Dict[str, ArrayLike]`: a dictionary with items:\n+\n+ - ``'input_ids'`` (:obj:`numpy.ndarray`): :obj:`numpy.int32` array containing encoded tokens,\n+ - ``'subtokens_mask'`` (:obj:`numpy.ndarray`): :obj:`bool` array which elements are ``True`` if they\n+ correspond to first token in a word,\n+ - ``'punct_labels'`` (:obj:`numpy.ndarray`): :obj:`numpy.int32` array containing encoded punctuation\n+ labels,\n+ - ``'capit_labels'`` (:obj:`numpy.ndarray`): :obj:`numpy.int32` array containing encoded capitalization\n+ labels.\n+ - ``'segment_ids'`` (:obj:`numpy.ndarray`): :obj:`numpy.int8` array filled with zeros (BERT token types\n+ in HuggingFace terminology) (if ``self.add_masks_and_segment_ids_to_batch`` is ``False``, then this\n+ items is missing),\n+ - ``'input_mask'`` (:obj:`numpy.ndarray`): :obj:`bool` array which elements are ``True`` if corresponding\n+ token is not a padding token (if ``self.add_masks_and_segment_ids_to_batch`` is ``False``, then this\n+ items is missing),\n+ - ``'loss_mask'`` (:obj:`numpy.ndarray`): :obj:`bool` array which elements are ``True`` if loss is\n+ computed for corresponding token. See more in description of constructor parameters\n+ ``ignore_start_end``, ``ignore_extra_tokens`` (if ``self.add_masks_and_segment_ids_to_batch`` is\n+ ``False``, then this items is missing).\n+ \"\"\"\n+ return self.batches[idx]\ndiff --git a/nemo/collections/nlp/data/token_classification/punctuation_capitalization_infer_dataset.py b/nemo/collections/nlp/data/token_classification/punctuation_capitalization_infer_dataset.py\nnew file mode 100644\n--- /dev/null\n+++ b/nemo/collections/nlp/data/token_classification/punctuation_capitalization_infer_dataset.py\n@@ -0,0 +1,334 @@\n+# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+import itertools\n+from typing import Dict, List, Optional, Tuple\n+\n+import numpy as np\n+import torch\n+from torch.nn.utils.rnn import pad_sequence\n+\n+from nemo.collections.common.tokenizers import TokenizerSpec\n+from nemo.collections.nlp.data import get_stats\n+from nemo.core import Dataset\n+from nemo.core.neural_types import ChannelType, Index, MaskType, NeuralType\n+from nemo.core.neural_types.elements import BoolType\n+from nemo.utils import logging\n+\n+\n+def get_features_infer(\n+ queries: List[str],\n+ tokenizer: TokenizerSpec,\n+ max_seq_length: int = 64,\n+ step: Optional[int] = 8,\n+ margin: Optional[int] = 16,\n+) -> Tuple[\n+ List[List[int]], List[List[int]], List[List[int]], List[List[int]], List[int], List[int], List[bool], List[bool],\n+]:\n+ \"\"\"\n+ Processes the data and returns features.\n+\n+ Args:\n+ queries: text sequences\n+ tokenizer: such as AutoTokenizer\n+ max_seq_length: max sequence length minus 2 for [CLS] and [SEP]\n+ step: relative shift of consequent segments into which long queries are split. Long queries are split into\n+ segments which can overlap. Parameter ``step`` controls such overlapping. Imagine that queries are\n+ tokenized into characters, ``max_seq_length=5``, and ``step=2``. In such a case query \"hello\" is\n+ tokenized into segments ``[['[CLS]', 'h', 'e', 'l', '[SEP]'], ['[CLS]', 'l', 'l', 'o', '[SEP]']]``.\n+ margin: number of subtokens near edges of segments which are not used for punctuation and capitalization\n+ prediction. The first segment does not have left margin and the last segment does not have right\n+ margin. For example, if input sequence is tokenized into characters, ``max_seq_length=5``,\n+ ``step=1``, and ``margin=1``, then query \"hello\" will be tokenized into segments\n+ ``[['[CLS]', 'h', 'e', 'l', '[SEP]'], ['[CLS]', 'e', 'l', 'l', '[SEP]'],\n+ ['[CLS]', 'l', 'l', 'o', '[SEP]']]``. These segments are passed to the model. Before final predictions\n+ computation, margins are removed. In the next list, subtokens which logits are not used for final\n+ predictions computation are marked with asterisk: ``[['[CLS]'*, 'h', 'e', 'l'*, '[SEP]'*],\n+ ['[CLS]'*, 'e'*, 'l', 'l'*, '[SEP]'*], ['[CLS]'*, 'l'*, 'l', 'o', '[SEP]'*]]``.\n+\n+ Returns:\n+ all_input_ids: list of input ids of all segments\n+ all_segment_ids: token type ids of all segments\n+ all_input_mask: attention mask to use for BERT model\n+ all_subtokens_mask: masks out all subwords besides the first one\n+ all_quantities_of_preceding_words: number of words in query preceding a segment. Used for joining\n+ predictions from overlapping segments.\n+ all_query_ids: index of a query to which segment belongs\n+ all_is_first: is segment first segment in a query\n+ all_is_last: is segment last segment in a query\n+ \"\"\"\n+ st = []\n+ stm = []\n+ sent_lengths = []\n+ for i, query in enumerate(queries):\n+ subtokens, subtokens_mask = _get_subtokens_and_subtokens_mask(query, tokenizer)\n+ sent_lengths.append(len(subtokens))\n+ st.append(subtokens)\n+ stm.append(subtokens_mask)\n+ _check_max_seq_length_and_margin_and_step(max_seq_length, margin, step)\n+ if max_seq_length > max(sent_lengths) + 2:\n+ max_seq_length = max(sent_lengths) + 2\n+ # If `max_seq_length` is greater than maximum length of input query, parameters ``margin`` and ``step`` are\n+ # not used will not be used.\n+ step = 1\n+ # Maximum number of word subtokens in segment. The first and the last tokens in segment are CLS and EOS\n+ length = max_seq_length - 2\n+ else:\n+ # Maximum number of word subtokens in segment. The first and the last tokens in segment are CLS and EOS\n+ length = max_seq_length - 2\n+ step = min(length - margin * 2, step)\n+ logging.info(f'Max length: {max_seq_length}')\n+ get_stats(sent_lengths)\n+ all_input_ids, all_segment_ids, all_subtokens_mask, all_input_mask, all_input_mask = [], [], [], [], []\n+ all_quantities_of_preceding_words, all_query_ids, all_is_first, all_is_last = [], [], [], []\n+ for q_i, query_st in enumerate(st):\n+ q_inp_ids, q_segment_ids, q_subtokens_mask, q_inp_mask, q_quantities_of_preceding_words = [], [], [], [], []\n+ for i in range(0, max(len(query_st), length) - length + step, step):\n+ subtokens = [tokenizer.cls_token] + query_st[i : i + length] + [tokenizer.sep_token]\n+ q_inp_ids.append(tokenizer.tokens_to_ids(subtokens))\n+ q_segment_ids.append([0] * len(subtokens))\n+ q_subtokens_mask.append([False] + stm[q_i][i : i + length] + [False])\n+ q_inp_mask.append([True] * len(subtokens))\n+ q_quantities_of_preceding_words.append(np.count_nonzero(stm[q_i][:i]))\n+ all_input_ids.append(q_inp_ids)\n+ all_segment_ids.append(q_segment_ids)\n+ all_subtokens_mask.append(q_subtokens_mask)\n+ all_input_mask.append(q_inp_mask)\n+ all_quantities_of_preceding_words.append(q_quantities_of_preceding_words)\n+ all_query_ids.append([q_i] * len(q_inp_ids))\n+ all_is_first.append([True] + [False] * (len(q_inp_ids) - 1))\n+ all_is_last.append([False] * (len(q_inp_ids) - 1) + [True])\n+ return (\n+ list(itertools.chain(*all_input_ids)),\n+ list(itertools.chain(*all_segment_ids)),\n+ list(itertools.chain(*all_input_mask)),\n+ list(itertools.chain(*all_subtokens_mask)),\n+ list(itertools.chain(*all_quantities_of_preceding_words)),\n+ list(itertools.chain(*all_query_ids)),\n+ list(itertools.chain(*all_is_first)),\n+ list(itertools.chain(*all_is_last)),\n+ )\n+\n+\n+def _check_max_seq_length_and_margin_and_step(max_seq_length: int, margin: int, step: int):\n+ \"\"\"\n+ Checks values of ``max_seq_length``, ``margin``, and ``step``.\n+ Args:\n+ max_seq_length: a segment length with ``[CLS]`` and ``[SEP]`` tokens\n+ margin: a number of input tokens near edges of segments which are not used in punctuation and capitalization\n+ prediction.\n+ step: offset of consequent segments.\n+ Returns:\n+ None\n+ \"\"\"\n+ if max_seq_length < 3:\n+ raise ValueError(\n+ f\"Parameter `max_seq_length={max_seq_length}` cannot be less than 3 because `max_seq_length` is a length \"\n+ f\"of a segment with [CLS] and [SEP] tokens.\"\n+ )\n+ if margin >= (max_seq_length - 2) // 2 and margin > 0 or margin < 0:\n+ raise ValueError(\n+ f\"Parameter `margin` has to be not negative and less than `(max_seq_length - 2) // 2`. Don't forget about \"\n+ f\"CLS and EOS tokens in the beginning and the end of segment. margin={margin}, \"\n+ f\"max_seq_length={max_seq_length}\"\n+ )\n+ if step <= 0:\n+ raise ValueError(f\"Parameter `step` has to be positive whereas step={step}\")\n+ if step > max_seq_length - 2 - 2 * margin:\n+ logging.warning(\n+ f\"Parameter step={step} is too big. It will be reduced to `min(max_seq_length, + 2) \"\n+ f\"- 2 - 2 * margin`.\"\n+ )\n+\n+\n+def _get_subtokens_and_subtokens_mask(query: str, tokenizer: TokenizerSpec) -> Tuple[List[str], List[bool]]:\n+ \"\"\"\n+ Tokenizes input query into subtokens and creates subtokens mask. Subtokens mask is an array of the same length as\n+ subtokens array and contains zeros and ones in which. If element of mask equals 1, then corresponding subtoken in\n+ subtokens array is first subtoken in some word\n+ Args:\n+ query: a string that will be tokenized\n+ tokenizer: an instance of tokenizer\n+ Returns:\n+ subtokens: list of subtokens\n+ subtokens_mask: list of ints\n+ \"\"\"\n+ words = query.strip().split()\n+ subtokens = []\n+ subtokens_mask = []\n+ for j, word in enumerate(words):\n+ word_tokens = tokenizer.text_to_tokens(word)\n+ subtokens.extend(word_tokens)\n+ subtokens_mask.append(True)\n+ subtokens_mask.extend([False] * (len(word_tokens) - 1))\n+ return subtokens, subtokens_mask\n+\n+\n+class BertPunctuationCapitalizationInferDataset(Dataset):\n+ \"\"\"\n+ Creates dataset to use during inference for punctuation and capitalization tasks with a pretrained model.\n+ For dataset to use during training with labels, see\n+ :class:`~nemo.collections.nlp.data.token_classification.punctuation_capitalization_dataset.BertPunctuationCapitalizationDataset`\n+ and\n+ :class:`~nemo.collections.nlp.data.token_classification.punctuation_capitalization_tarred_dataset.BertPunctuationCapitalizationTarredDataset`.\n+\n+ Parameters ``max_seq_length``, ``step``, ``margin`` are for controlling the way queries are split into segments\n+ which then processed by the model. Parameter ``max_seq_length`` is a length of a segment after tokenization\n+ including special tokens [CLS] in the beginning and [SEP] in the end of a segment. Parameter ``step`` is shift\n+ between consequent segments. Parameter ``margin`` is used to exclude negative effect of subtokens near\n+ borders of segments which have only one side context.\n+\n+ Args:\n+ queries (:obj:`List[str]`): list of sequences.\n+ tokenizer (:obj:`TokenizerSpec`): a tokenizer which was used for model training. It should have properties\n+ ``cls_id``, ``sep_id``, ``unk_id``, ``pad_id``.\n+ max_seq_length (:obj:`int`, `optional`, defaults to :obj:`128`): max sequence length which includes [CLS] and\n+ [SEP] tokens\n+ step (:obj:`int`, `optional`, defaults to :obj:`8`): relative shift of consequent segments into which long\n+ queries are split. Long queries are split into segments which can overlap. Parameter ``step`` controls such\n+ overlapping. Imagine that queries are tokenized into characters, ``max_seq_length=5``, and ``step=2``. In\n+ such a case query \"hello\" is tokenized into segments\n+ ``[['[CLS]', 'h', 'e', 'l', '[SEP]'], ['[CLS]', 'l', 'l', 'o', '[SEP]']]``.\n+ margin (:obj:`int`, `optional`, defaults to :obj:`16`): number of subtokens in the beginning and the end of\n+ segments which are not used for prediction computation. The first segment does not have left margin and the\n+ last segment does not have right margin. For example, if input sequence is tokenized into characters,\n+ ``max_seq_length=5``, ``step=1``, and ``margin=1``, then query \"hello\" will be tokenized into segments\n+ ``[['[CLS]', 'h', 'e', 'l', '[SEP]'], ['[CLS]', 'e', 'l', 'l', '[SEP]'],\n+ ['[CLS]', 'l', 'l', 'o', '[SEP]']]``. These segments are passed to the model. Before final predictions\n+ computation, margins are removed. In the next list, subtokens which logits are not used for final\n+ predictions computation are marked with asterisk: ``[['[CLS]'*, 'h', 'e', 'l'*, '[SEP]'*],\n+ ['[CLS]'*, 'e'*, 'l', 'l'*, '[SEP]'*], ['[CLS]'*, 'l'*, 'l', 'o', '[SEP]'*]]``.\n+ \"\"\"\n+\n+ @property\n+ def output_types(self) -> Optional[Dict[str, NeuralType]]:\n+ \"\"\"Returns neural types of :meth:`collate_fn` output.\"\"\"\n+ return {\n+ 'input_ids': NeuralType(('B', 'T'), ChannelType()),\n+ 'segment_ids': NeuralType(('B', 'T'), ChannelType()),\n+ 'input_mask': NeuralType(('B', 'T'), MaskType()),\n+ 'subtokens_mask': NeuralType(('B', 'T'), MaskType()),\n+ 'quantities_of_preceding_words': NeuralType(('B',), Index()),\n+ 'query_ids': NeuralType(('B',), Index()),\n+ 'is_first': NeuralType(('B',), BoolType()),\n+ 'is_last': NeuralType(('B',), BoolType()),\n+ }\n+\n+ def __init__(\n+ self, queries: List[str], tokenizer: TokenizerSpec, max_seq_length: int = 64, step: int = 8, margin: int = 16\n+ ):\n+ features = get_features_infer(\n+ queries=queries, max_seq_length=max_seq_length, tokenizer=tokenizer, step=step, margin=margin\n+ )\n+ self.all_input_ids: List[List[int]] = features[0]\n+ self.all_segment_ids: List[List[int]] = features[1]\n+ self.all_input_mask: List[List[int]] = features[2]\n+ self.all_subtokens_mask: List[List[int]] = features[3]\n+ self.all_quantities_of_preceding_words: List[int] = features[4]\n+ self.all_query_ids: List[int] = features[5]\n+ self.all_is_first: List[bool] = features[6]\n+ self.all_is_last: List[bool] = features[7]\n+\n+ def __len__(self) -> int:\n+ return len(self.all_input_ids)\n+\n+ def collate_fn(\n+ self, batch: List[Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, int, int, bool, bool]]\n+ ) -> Tuple[\n+ torch.Tensor,\n+ torch.Tensor,\n+ torch.Tensor,\n+ torch.Tensor,\n+ Tuple[int, ...],\n+ Tuple[int, ...],\n+ Tuple[bool, ...],\n+ Tuple[bool, ...],\n+ ]:\n+ \"\"\"\n+ Collates samples into batches.\n+\n+ Args:\n+ batch (:obj:`List[tuple]`): a list of samples returned by :meth:`__getitem__` method.\n+\n+ Returns:\n+ :obj:`Tuple[torch.Tensor (x4), Tuple[int, ...] (x2), Tuple[bool, ...] (x2)]`: a tuple containing 8\n+ elements:\n+\n+ - ``input_ids`` (:obj:`torch.Tensor`): an integer tensor of shape ``[Batch, Time]`` containing encoded\n+ input text.\n+ - ``segment_ids`` (:obj:`torch.Tensor`): an integer tensor of shape ``[Batch, Time]`` filled with zeros.\n+ - ``input_mask`` (:obj:`torch.Tensor`): a boolean tensor of shape ``[Batch, Time]`` which elements are\n+ ``True`` if corresponding token is not a padding token.\n+ - ``subtokens_mask`` (:obj:`torch.Tensor`): a boolean tensor of shape ``[Batch, Time]`` which elements\n+ are ``True`` if corresponding tken is the first token in a word.\n+ - ``quantities_of_preceding_words`` (:obj:`Tuple[int, ...]`): a tuple containing number of words in\n+ a query preceding current segment.\n+ - ``query_ids`` (:obj:`Tuple[int, ...]`): a tuple containing indices of queries to which segments belong.\n+ - ``is_first`` (:obj:`Tuple[bool, ...]`): a tuple booleans which elements are ``True`` if corresponding\n+ segment is the first segment in a query.\n+ - ``is_last`` (:obj:`Tuple[bool, ...]`): a tuple of booleans which elements are ``True`` if corresponding\n+ segment is the last segment in a query.\n+ \"\"\"\n+ inp_ids, segment_ids, inp_mask, st_mask, n_preceding, query_ids, is_first, is_last = zip(*batch)\n+ return (\n+ pad_sequence([torch.tensor(x) for x in inp_ids], batch_first=True, padding_value=0),\n+ pad_sequence([torch.tensor(x) for x in segment_ids], batch_first=True, padding_value=0),\n+ pad_sequence([torch.tensor(x) for x in inp_mask], batch_first=True, padding_value=0),\n+ pad_sequence([torch.tensor(x) for x in st_mask], batch_first=True, padding_value=0),\n+ n_preceding,\n+ query_ids,\n+ is_first,\n+ is_last,\n+ )\n+\n+ def __getitem__(self, idx: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, int, int, bool, bool]:\n+ \"\"\"\n+ Returns batch used for punctuation and capitalization inference.\n+\n+ Args:\n+ idx (:obj:`int`): a batch index\n+\n+ Returns:\n+ :obj:`Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, int, int, bool, bool]`: a tuple containing:\n+\n+ - ``input_ids`` (:obj:`np.ndarray`): an integer numpy array of shape ``[Time]``. Ids of word\n+ subtokens encoded using tokenizer passed in constructor ``tokenizer`` parameter.\n+ - ``segment_ids`` (:obj:`np.ndarray`): an integer zeros numpy array of shape ``[Time]``. Indices\n+ of segments for BERT model (token types in HuggingFace terminology).\n+ - ``input_mask`` (:obj:`np.ndarray`): a boolean numpy array of shape ``[Time]``. An element of\n+ this array is ``True`` if corresponding token is not padding token.\n+ - ``subtokens_mask`` (:obj:`np.ndarray`): a boolean numpy array of shape ``[Time]``. An element\n+ equals ``True`` if corresponding token is the first token in a word and ``False`` otherwise. For\n+ example, if input query ``\"language processing\"`` is tokenized into\n+ ``[\"[CLS]\", \"language\", \"process\", \"ing\", \"SEP\"]``, then ``subtokens_mask`` will be\n+ ``[False, True, True, False, False]``.\n+ - ``quantities_of_preceding_words`` (:obj:`int`): a number of words preceding current segment in the\n+ query to which the segment belongs. This parameter is used for uniting predictions from adjacent\n+ segments.\n+ - ``query_ids`` (:obj:`int`): an index of query to which the segment belongs\n+ - ``is_first`` (:obj:`bool`): whether a segment is the first segment in a query. The left margin of\n+ the first segment in a query is not removed.\n+ - ``is_last`` (:obj:`bool`): whether a query is the last query in a query. The right margin of the last\n+ segment in a query is not removed.\n+ \"\"\"\n+ return (\n+ np.array(self.all_input_ids[idx]),\n+ np.array(self.all_segment_ids[idx]),\n+ np.array(self.all_input_mask[idx], dtype=np.float32),\n+ np.array(self.all_subtokens_mask[idx]),\n+ self.all_quantities_of_preceding_words[idx],\n+ self.all_query_ids[idx],\n+ self.all_is_first[idx],\n+ self.all_is_last[idx],\n+ )\ndiff --git a/nemo/collections/nlp/data/token_classification/punctuation_capitalization_tarred_dataset.py b/nemo/collections/nlp/data/token_classification/punctuation_capitalization_tarred_dataset.py\nnew file mode 100644\n--- /dev/null\n+++ b/nemo/collections/nlp/data/token_classification/punctuation_capitalization_tarred_dataset.py\n@@ -0,0 +1,1137 @@\n+# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+import json\n+import multiprocessing as mp\n+import os\n+import pickle\n+import re\n+import shutil\n+from collections import deque\n+from pathlib import Path\n+from typing import Any, Callable, Dict, Iterator, List, Optional, Set, Tuple, Type, Union\n+\n+import torch\n+import webdataset as wds\n+from joblib import Parallel, delayed\n+from numpy.typing import ArrayLike\n+from omegaconf import DictConfig\n+from torch.utils.data import IterableDataset\n+\n+from nemo.collections.common.tokenizers import TokenizerSpec\n+from nemo.collections.nlp.data.token_classification.punctuation_capitalization_dataset import (\n+ LABEL_ID_DIR_FOR_NEMO_CHECKPOINT,\n+ BertPunctuationCapitalizationDataset,\n+ Progress,\n+ create_label_ids,\n+ create_masks_and_segment_ids,\n+ load_label_ids,\n+ raise_not_equal_labels_error,\n+)\n+from nemo.collections.nlp.modules.common.tokenizer_utils import get_tokenizer\n+from nemo.core.neural_types import ChannelType, LabelsType, MaskType, NeuralType\n+from nemo.utils import logging\n+\n+NUMBER_RE = \"(0|[1-9][0-9]*)\"\n+TAR_FRAGMENT_TMPL_IN_PROGRESS = \"fragment{fragment_idx}.{file_idx}.tar\"\n+TAR_FRAGMENT_TMPL_FINISHED = \"fragment{fragment_idx}.num_batches{num_batches}.{file_idx}.tar\"\n+TAR_FRAGMENT_TMPL_TO_REPACK = \"fragment{fragment_idx}.num_batches{num_batches}.{file_idx}.tar.to_repack\"\n+TAR_FRAGMENT_PATTERN_IN_PROGRESS = re.compile(f\"fragment{NUMBER_RE}.{NUMBER_RE}.tar$\")\n+TAR_FRAGMENT_PATTERN_FINISHED = re.compile(f\"fragment{NUMBER_RE}.num_batches{NUMBER_RE}.{NUMBER_RE}.tar$\")\n+TAR_FRAGMENT_PATTERN_TO_REPACK = re.compile(f\"fragment{NUMBER_RE}.num_batches{NUMBER_RE}.{NUMBER_RE}.tar.to_repack$\")\n+\n+DATASET_PARAMETERS_TMPL = \"{prefix}.tokens{tokens_in_batch}.max_seq_length{max_seq_length}.{tokenizer}\"\n+TAR_FINAL_TMPL = \".batches{num_batches}.{ctr}.tar\"\n+\n+PROGRESS_REPORT_PERIOD = 10 ** 4\n+\n+METADATA_PUNCT_LABEL_VOCAB_KEY = 'punct_label_vocab_file'\n+METADATA_CAPIT_LABEL_VOCAB_KEY = 'capit_label_vocab_file'\n+DEFAULT_PUNCT_LABEL_VOCAB_FILE_NAME = 'punct_label_vocab.csv'\n+DEFAULT_CAPIT_LABEL_VOCAB_FILE_NAME = 'capit_label_vocab.csv'\n+\n+\n+def count_lines_and_get_fragment_starting_positions(\n+ file_name: Path, lines_per_dataset_fragment: int\n+) -> Tuple[int, List[int]]:\n+ \"\"\"\n+ Returns number of lines in a file and indices of fragment starting bytes.\n+\n+ Args:\n+ file_name: a path to a text or label file\n+ lines_per_dataset_fragment: number of lines in a dataset fragment. The last fragment can contain less lines\n+\n+ Returns:\n+ num_lines: number of lines in a file\n+ start_bytes: indices of fragment starting bytes\n+ \"\"\"\n+ pos = [0]\n+ with file_name.open() as f:\n+ i = 0\n+ line = f.readline()\n+ while line:\n+ i += 1\n+ if i % lines_per_dataset_fragment == 0:\n+ pos.append(f.tell())\n+ line = f.readline()\n+ return i, pos[:-1] if i % lines_per_dataset_fragment == 0 else pos\n+\n+\n+def get_fragment_start_bytes(\n+ text_file: Path, labels_file: Path, lines_per_dataset_fragment: int\n+) -> Tuple[int, List[int], List[int]]:\n+ \"\"\"\n+ A function for calculating borders of dataset fragments. The function is used to split ``text_file`` and\n+ ``labels_file`` for processing them in parallel.\n+\n+ Args:\n+ text_file: a path to a dataset source file\n+ labels_file: a path to a dataset label file\n+ lines_per_dataset_fragment: a number of lines in one fragment\n+\n+ Returns:\n+ num_lines: total number of elements in the dataset (number of lines in ``text_file``` and ``labels_file``)\n+ text_start_bytes: indices of the first bytes of fragments in ``text_file``\n+ label_start_bytes: indices of the first bytes of fragments in ``labels_file``\n+ \"\"\"\n+ logging.info(\n+ f\"Counting lines in files {text_file} and {labels_file} and creating segment borders. This may take \"\n+ f\"considerable time. 86GB, 1.27b lines file was processed in 7 minutes.\"\n+ )\n+ result = Parallel(n_jobs=2)(\n+ delayed(count_lines_and_get_fragment_starting_positions)(file_name, lines_per_dataset_fragment)\n+ for file_name in [text_file, labels_file]\n+ )\n+ if result[0][0] != result[1][0]:\n+ raise ValueError(\n+ f\"Text file {text_file} and label file {labels_file} contain different number of lines. Number of lines \"\n+ f\"in text file: {result[0][0]}, number of lines in label file: {result[1][0]}.\"\n+ )\n+ num_lines = result[0][0]\n+ text_start_bytes, label_start_bytes = result[0][1], result[1][1]\n+ assert len(text_start_bytes) == len(label_start_bytes)\n+ return num_lines, text_start_bytes, label_start_bytes\n+\n+\n+def process_fragment(\n+ text_file: Path,\n+ labels_file: Path,\n+ output_dir: Path,\n+ text_start_pos: int,\n+ label_start_pos: int,\n+ lines_per_dataset_fragment: int,\n+ max_seq_length: int,\n+ tokens_in_batch: int,\n+ num_batches_per_tarfile: int,\n+ tokenizer_name: str,\n+ tokenizer_model: Optional[Path],\n+ vocab_file: Optional[Path],\n+ merges_file: Optional[Path],\n+ special_tokens: Dict[str, str],\n+ use_fast_tokenizer: Optional[bool],\n+ pad_label: str,\n+ punct_label_ids: Dict[str, int],\n+ capit_label_ids: Dict[str, int],\n+ fragment_idx: int,\n+ tokenization_progress_queue: mp.Queue,\n+ batch_mark_up_progress_queue: mp.Queue,\n+ batch_building_progress_queue: mp.Queue,\n+ writing_to_tar_progress_queue: mp.Queue,\n+) -> None:\n+ tokenizer = get_tokenizer(\n+ tokenizer_name,\n+ tokenizer_model=None if tokenizer_model is None else str(tokenizer_model),\n+ vocab_file=None if vocab_file is None else str(vocab_file),\n+ merges_file=None if merges_file is None else str(merges_file),\n+ special_tokens=special_tokens,\n+ use_fast=use_fast_tokenizer,\n+ )\n+ tmp_text = output_dir / f'tmp_text_{fragment_idx}.txt'\n+ tmp_labels = output_dir / f'tmp_labels_{fragment_idx}.txt'\n+ with text_file.open() as tf, labels_file.open() as lf, tmp_text.open('w') as otf, tmp_labels.open('w') as olf:\n+ tf.seek(text_start_pos)\n+ lf.seek(label_start_pos)\n+ for _ in range(lines_per_dataset_fragment):\n+ text_line = tf.readline()\n+ if not text_line:\n+ break\n+ otf.write(text_line)\n+ olf.write(lf.readline())\n+ dataset = BertPunctuationCapitalizationDataset(\n+ tmp_text,\n+ tmp_labels,\n+ max_seq_length,\n+ tokenizer,\n+ tokens_in_batch=tokens_in_batch,\n+ pad_label=pad_label,\n+ punct_label_ids=punct_label_ids,\n+ capit_label_ids=capit_label_ids,\n+ n_jobs=0,\n+ use_cache=False,\n+ add_masks_and_segment_ids_to_batch=False,\n+ verbose=False,\n+ tokenization_progress_queue=tokenization_progress_queue,\n+ batch_mark_up_progress_queue=batch_mark_up_progress_queue,\n+ batch_building_progress_queue=batch_building_progress_queue,\n+ )\n+ tmp_text.unlink()\n+ tmp_labels.unlink()\n+ tar_ctr = 0\n+ current_file_name = output_dir / TAR_FRAGMENT_TMPL_IN_PROGRESS.format(fragment_idx=fragment_idx, file_idx=tar_ctr)\n+ current_num_batches = 0\n+ sink = wds.TarWriter(str(current_file_name))\n+ progress_made = 0\n+ for batch_i, batch in enumerate(dataset):\n+ sink.write({\"__key__\": f\"fragment-{fragment_idx}-batch-{batch_i}\", \"batch.pyd\": batch})\n+ current_num_batches += 1\n+ progress_made += len(batch['input_ids'])\n+ if current_num_batches % num_batches_per_tarfile == 0:\n+ sink.close()\n+ current_file_name.rename(\n+ output_dir\n+ / TAR_FRAGMENT_TMPL_FINISHED.format(\n+ fragment_idx=fragment_idx, num_batches=current_num_batches, file_idx=tar_ctr\n+ )\n+ )\n+ writing_to_tar_progress_queue.put(progress_made)\n+ progress_made = 0\n+ tar_ctr += 1\n+ current_file_name = output_dir / TAR_FRAGMENT_TMPL_IN_PROGRESS.format(\n+ fragment_idx=fragment_idx, file_idx=tar_ctr\n+ )\n+ current_num_batches = 0\n+ sink = wds.TarWriter(str(current_file_name))\n+ sink.close()\n+ writing_to_tar_progress_queue.put(progress_made)\n+ if progress_made > 0:\n+ new_file_name = output_dir / TAR_FRAGMENT_TMPL_TO_REPACK.format(\n+ fragment_idx=fragment_idx, num_batches=current_num_batches, file_idx=tar_ctr\n+ )\n+ current_file_name.rename(new_file_name)\n+ else:\n+ current_file_name.unlink()\n+ if fragment_idx == 0:\n+ punct_label_ids_file, capit_label_ids_file = dataset.save_labels_and_get_file_paths(\n+ DEFAULT_PUNCT_LABEL_VOCAB_FILE_NAME, DEFAULT_CAPIT_LABEL_VOCAB_FILE_NAME\n+ )\n+ punct_label_ids_file.rename(output_dir / DEFAULT_PUNCT_LABEL_VOCAB_FILE_NAME)\n+ capit_label_ids_file.rename(output_dir / DEFAULT_CAPIT_LABEL_VOCAB_FILE_NAME)\n+ shutil.rmtree(punct_label_ids_file.parent)\n+\n+\n+def remove_unexpected_files_and_dirs(output_dir: Path, output_file_tmpl: str, metadata_file_name: Path) -> None:\n+ \"\"\"\n+ This function removes all files with names which may be used in the dataset creation.\n+\n+ Args:\n+ output_dir: a path to directory where removal is performed\n+ output_file_tmpl: a format string for a name of final tar file. Must include fields ``ctr`` for number of the\n+ file and ``num_batches`` for number of batches in the file.\n+ metadata_file_name: a metadata file name\n+ \"\"\"\n+ if not output_dir.is_dir():\n+ return\n+ tar_final_pattern = re.compile(output_file_tmpl.format(ctr=NUMBER_RE, num_batches=NUMBER_RE))\n+ unexpected_tar_files = [\n+ path\n+ for path in output_dir.iterdir()\n+ if any(\n+ [\n+ p.match(path.name) is not None\n+ for p in [\n+ TAR_FRAGMENT_PATTERN_IN_PROGRESS,\n+ TAR_FRAGMENT_PATTERN_FINISHED,\n+ TAR_FRAGMENT_PATTERN_TO_REPACK,\n+ tar_final_pattern,\n+ ]\n+ ]\n+ )\n+ ]\n+ if unexpected_tar_files:\n+ logging.warning(\n+ f\"Found {len(unexpected_tar_files)} unexpected tar files in the output directory {output_dir}. \"\n+ f\"All of them are going to be removed. The files match one of 3 patterns: \"\n+ f\"'{TAR_FRAGMENT_PATTERN_IN_PROGRESS.pattern}', '{TAR_FRAGMENT_PATTERN_FINISHED.pattern}', \"\n+ f\"'{tar_final_pattern.pattern}'. The first unexpected files: \"\n+ f\"{', '.join([str(f) for f in unexpected_tar_files[:3]])}.\"\n+ )\n+ for fn in unexpected_tar_files:\n+ fn.unlink()\n+ if metadata_file_name.exists():\n+ logging.warning(f\"Found metadata file {metadata_file_name}. It is going to be removed.\")\n+ metadata_file_name.unlink()\n+ punct_label_ids = output_dir / DEFAULT_PUNCT_LABEL_VOCAB_FILE_NAME\n+ capit_label_ids = output_dir / DEFAULT_CAPIT_LABEL_VOCAB_FILE_NAME\n+ if punct_label_ids.exists():\n+ logging.warning(f\"Found unexpected punctuation label file {punct_label_ids}. It is going to be removed.\")\n+ punct_label_ids.unlink()\n+ if capit_label_ids.exists():\n+ logging.warning(f\"Found unexpected capitalization label file {capit_label_ids}. It is going to be removed.\")\n+ capit_label_ids.unlink()\n+\n+\n+def collect_unique_labels_from_fragment(\n+ labels_file: Path, start_pos: int, lines_per_dataset_fragment: int, progress_queue: mp.Queue, fragment_idx: int\n+) -> Tuple[Set[str], Set[str]]:\n+ \"\"\"\n+ Returns a set of unique punctuation labels and a set of unique capitalization labels.\n+\n+ Args:\n+ labels_file: a path to a file with labels\n+ start_pos: an index of the first byte of a fragment in ``labels_file``\n+ lines_per_dataset_fragment: number of lines in dataset fragment. In the last fragment there can be less lines.\n+ progress_queue: a queue for reporting number of processed lines\n+ fragment_idx: a processed fragment index\n+\n+ Returns:\n+ unique_punct: a set of unique punctuation labels\n+ unique_capit: a set of unique capitalization labels\n+ \"\"\"\n+ unique_punct, unique_capit = set(), set()\n+ with labels_file.open() as f:\n+ f.seek(start_pos)\n+ progress_report = 0\n+ for i in range(lines_per_dataset_fragment):\n+ line = f.readline()\n+ if not line:\n+ break\n+ pairs = line.split()\n+ if not all([len(p) == 2 for p in pairs]):\n+ broken_pairs = [i for i, p in enumerate(pairs) if len(p) != 2]\n+ raise ValueError(\n+ f\"Found broken labels line in number {fragment_idx * lines_per_dataset_fragment + i} in file \"\n+ f\"{labels_file}. Indices of broken pairs of labels: {broken_pairs}\"\n+ )\n+ punct, capit = zip(*pairs)\n+ unique_punct.update(punct)\n+ unique_capit.update(capit)\n+ progress_report += 1\n+ if progress_report >= PROGRESS_REPORT_PERIOD:\n+ progress_queue.put(progress_report)\n+ progress_report = 0\n+ progress_queue.put(progress_report)\n+ return unique_punct, unique_capit\n+\n+\n+def create_label_dictionaries(\n+ labels_file: Path,\n+ text_start_bytes: List[int],\n+ num_lines: int,\n+ lines_per_dataset_fragment: int,\n+ pad_label: str,\n+ n_jobs: int,\n+) -> Tuple[Dict[str, int], Dict[str, int]]:\n+ \"\"\"\n+ Creates punctuation and capitalization label ids dictionaries based on labels present in ``labels_file``.\n+\n+ Args:\n+ labels_file: a path to file with labels\n+ text_start_bytes: indices of first bytes of fragments in ``labels_file``\n+ num_lines: total number of lines in ``labels_file``\n+ lines_per_dataset_fragment: number of lines in dataset fragments. The last fragment can have less lines\n+ pad_label: a label used for padding and for absence of punctuation and capitalization\n+ n_jobs: a number of fragments processed in parallel\n+\n+ Returns:\n+ punct_label_ids: a dictionary with punctuation label ids\n+ capit_label_ids: a dictionary with capitalization label ids\n+ \"\"\"\n+ with Progress(num_lines, \"Creating label dictionary\", \"line\") as progress_queues:\n+ result = Parallel(n_jobs=min(n_jobs, len(text_start_bytes)))(\n+ delayed(collect_unique_labels_from_fragment)(\n+ labels_file, start_pos, lines_per_dataset_fragment, *progress_queues, fragment_idx\n+ )\n+ for fragment_idx, start_pos in enumerate(text_start_bytes)\n+ )\n+ unique_punct, unique_capit = zip(*result)\n+ unique_punct = set().union(*unique_punct)\n+ unique_capit = set().union(*unique_capit)\n+ return create_label_ids(unique_punct, pad_label), create_label_ids(unique_capit, pad_label)\n+\n+\n+def check_label_ids(pad_label: str, punct_label_ids: Dict[str, int], capit_label_ids: Dict[str, int]) -> None:\n+ \"\"\"\n+ A function for checking that pad label has zeroth id in ``punct_label_dis`` and ``capit_label_ids`` dictionaries.\n+ Args:\n+ pad_label: a pad label\n+ punct_label_ids: a dictionary with punctuation label ids\n+ capit_label_ids: a dictionary with capitalization label ids\n+ \"\"\"\n+ msg = \"Parameter `pad_label` has to have id 0 in dictionary `{param_name}` whereas it has id {id_}.\" + (\n+ '' if len(pad_label) > 10 else f\" pad_label='{pad_label}'\"\n+ )\n+ if punct_label_ids is not None:\n+ if punct_label_ids[pad_label] != 0:\n+ raise ValueError(msg.format(param_name='punct_label_ids', id_=punct_label_ids[pad_label]))\n+ if capit_label_ids is not None:\n+ if capit_label_ids[pad_label] != 0:\n+ raise ValueError(msg.format(param_name='capit_label_ids', id_=capit_label_ids[pad_label]))\n+\n+\n+def process_error(msg: str, error_class_or_function: Union[Type[Exception], Callable[[str], Any]]) -> None:\n+ if issubclass(error_class_or_function, Exception):\n+ raise error_class_or_function(msg)\n+ if callable(error_class_or_function):\n+ error_class_or_function(msg)\n+ raise ValueError(\n+ f\"Parameter `error_class_or_function` has to be a subclass of `Exception` or a function.\"\n+ f\"Given {type(error_class_or_function)}\"\n+ )\n+\n+\n+def check_labels_for_being_unique_before_building_label_ids(\n+ pad_label: str,\n+ other_labels: List[str],\n+ pad_label_name: str,\n+ other_labels_name: str,\n+ error_class_or_function: Union[Type[Exception], Callable[[str], Any]],\n+) -> None:\n+ \"\"\"\n+ A function for checking that that all labels are unique.\n+\n+ Args:\n+ pad_label: a pad label\n+ other_labels: a list of labels except for the pad label\n+ pad_label_name: a name of the pad label used in error message\n+ other_labels_name: a name of other labels used in error message\n+ error_class_or_function: a class of an exception which is raised if there is a problem with labels.\n+ Alternatively it can be a function for handling exceptions, for example ``argparse.ArgumentParser.error``.\n+ Such a function has to take one argument -- error message.\n+ \"\"\"\n+ for i, lbl in enumerate(other_labels):\n+ if lbl == pad_label:\n+ msg = f\"Label number {i} in parameter `{other_labels_name}` is equal to `{pad_label_name}`.\"\n+ process_error(msg, error_class_or_function)\n+ for i in range(len(other_labels) - 1):\n+ for lbl in other_labels[i + 1 :]:\n+ if lbl == other_labels[i]:\n+ msg = f\"Label number {i} occurs at least 2 times in parameter `{other_labels_name}`.\"\n+ process_error(msg, error_class_or_function)\n+\n+\n+def build_label_ids_from_list_of_labels(pad_label: str, other_labels: List[str]) -> Dict[str, int]:\n+ \"\"\"\n+ Builds label ids dictionary from pad label and list of other labels. Used for parsing command line arguments.\n+ Args:\n+ pad_label: a pad label\n+ other_labels: list of labels except for the pad label\n+\n+ Returns:\n+ a dictionary with label ids\n+ \"\"\"\n+ check_labels_for_being_unique_before_building_label_ids(\n+ pad_label, other_labels, 'pad_label', 'other_labels', ValueError\n+ )\n+ ids = {pad_label: 0}\n+ for lbl in other_labels:\n+ ids[lbl] = len(ids)\n+ return ids\n+\n+\n+def get_label_dictionaries(\n+ labels_file: Path,\n+ start_bytes: List[int],\n+ num_lines: int,\n+ lines_per_dataset_fragment: int,\n+ pad_label: str,\n+ punct_label_ids: Optional[Dict[str, int]],\n+ capit_label_ids: Optional[Dict[str, int]],\n+ punct_label_vocab_file: Optional[Path],\n+ capit_label_vocab_file: Optional[Path],\n+ n_jobs: int,\n+) -> Tuple[Dict[str, int], Dict[str, int]]:\n+ \"\"\"\n+ Return label ids if the label ids are present in parameters ``punct_label_ids``, ``capit_label_ids``,\n+ ``punct_label_vocab_file``, ``capit_label_vocab_file``. Otherwise, label ids are created using ``labels_file``.\n+\n+ Args:\n+ labels_file: a path to file with labels. Labels have to be given in the format described in\n+ https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/main/nlp/punctuation_and_capitalization.html#nemo-data-format\n+ start_bytes: a list of positions in ``labels_file`` at which fragments start. Parameter ``start_bytes`` is used\n+ for creating labels for several fragments in parallel\n+ num_lines: total number of lines in ``labels_file``. Parameter ``num_lines`` is used for showing progress of\n+ label ids collection\n+ lines_per_dataset_fragment: number of lines in a dataset fragment\n+ pad_label: a label used for padding and also neutral label showing there is no punctuation and capitalization.\n+ Label ``pad_label`` has to have id ``0`` in parameters ``punct_label_ids``, ``capit_label_ids``,\n+ ``punct_label_vocab_file``, ``capit_label_vocab_file`` if these parameters are provided.\n+ punct_label_ids: a dictionary with punctuation label ids. Pad label has to have id ``0``. No more than 1 of\n+ parameters ``punct_label_ids`` and ``punct_label_vocab_file`` can be provided.\n+ capit_label_ids: a dictionary with capitalization label ids. Pad label has to have id ``0``. No more than 1 of\n+ parameters ``capit_label_ids`` and ``capit_label_vocab_file`` can be provided.\n+ punct_label_vocab_file: a text file with punctuation labels. Every line in the file contains 1 label. Pad label\n+ has to be in the first line. No more than 1 of parameters ``punct_label_ids`` and\n+ ``punct_label_vocab_file`` can be provided.\n+ capit_label_vocab_file: a text file with capitalization labels. Every line in the file contains 1 label. Pad\n+ label has to be in the first line. No more than 1 of parameters ``capit_label_ids`` and\n+ ``capit_label_vocab_file`` can be provided.\n+ n_jobs: a number of fragments processed in parallel\n+\n+ Returns:\n+ punct_label_ids: a dictionary with punctuation label ids\n+ capit_label_ids: a dictionary with capitalization label ids\n+ \"\"\"\n+ if punct_label_ids is not None and punct_label_vocab_file is not None:\n+ raise ValueError(\"You can provide at most one of parameters `punct_label_ids` and `punct_label_vocab_file`.\")\n+ if capit_label_ids is not None and capit_label_vocab_file is not None:\n+ raise ValueError(\"You can provide at most one of parameters `capit_label_ids` and `capit_label_vocab_file`.\")\n+ if punct_label_ids is None and punct_label_vocab_file is not None:\n+ punct_label_ids = load_label_ids(punct_label_vocab_file)\n+ if capit_label_ids is None and capit_label_vocab_file is not None:\n+ capit_label_ids = load_label_ids(capit_label_vocab_file)\n+ check_label_ids(pad_label, punct_label_ids, capit_label_ids)\n+ if punct_label_ids is None or capit_label_ids is None:\n+ _punct_label_ids, _capit_label_ids = create_label_dictionaries(\n+ labels_file, start_bytes, num_lines, lines_per_dataset_fragment, pad_label, n_jobs\n+ )\n+ if punct_label_ids is None:\n+ punct_label_ids = _punct_label_ids\n+ if capit_label_ids is None:\n+ capit_label_ids = _capit_label_ids\n+ return punct_label_ids, capit_label_ids\n+\n+\n+def decode_pyd(key: str, value: bytes) -> Any:\n+ \"\"\"\n+ Used for decoding batch loaded by ``webdataset`` from tar files.\n+ Args:\n+ key: name of a batch\n+ value: pickled batch\n+\n+ Returns:\n+ decoded batch\n+ \"\"\"\n+ return pickle.loads(value)\n+\n+\n+def repack_tar_files_with_not_enough_batches(output_dir: Path, num_batches_per_tarfile: int) -> None:\n+ f\"\"\"\n+ It is possible that number of batches in a fragment is not evenly divisible by ``num_batches_per_tarfile``.\n+ In such a case excess batches are put in a tar file which matches a pattern\n+ ``fragment(0|[1-9][0-9]*).num_batches(0|[1-9][0-9]*).(0|[1-9][0-9]*).tar.to_repack``. Such files are repacked by\n+ ``repack_tar_files_with_not_enough_batches`` function into tar files with correct ``num_batches_per_tarfile``\n+ batches each. If there is no enough batches in repacked files, then up to ``num_batches_per_tarfile - 1``\n+ remaining batches may be discarded.\n+ \n+ Args:\n+ output_dir: a path to the output directory which contains files to repack and where new files are saved\n+ num_batches_per_tarfile: a number of batches in 1 tar file. If number of batches in files matching a pattern\n+ ``fragment(0|[1-9][0-9]*).num_batches(0|[1-9][0-9]*).(0|[1-9][0-9]*).tar.to_repack`` is not evenly\n+ divisible by ``num_batches_per_tarfile`` excess batches are discarded.\n+ \"\"\"\n+ files_to_repack_with_matches = [\n+ (path, TAR_FRAGMENT_PATTERN_TO_REPACK.match(path.name))\n+ for path in output_dir.iterdir()\n+ if TAR_FRAGMENT_PATTERN_TO_REPACK.match(path.name) is not None\n+ ]\n+ files_to_repack_with_matches = sorted(files_to_repack_with_matches, key=lambda x: int(x[1].group(3)))\n+ logging.info(f\"Found {len(files_to_repack_with_matches)} files for repacking.\")\n+ files_to_repack_with_matches = deque(files_to_repack_with_matches)\n+ total_batches_in_repacked_files = 0\n+ initial_number_of_files_to_repack = len(files_to_repack_with_matches)\n+ pop_file_ds = None\n+ new_file_sink = None\n+ new_file_num_batches = 0\n+ while files_to_repack_with_matches:\n+ assert pop_file_ds is None or new_file_sink is None\n+ if new_file_sink is None:\n+ # `append_file` is a file which content will serve as a start for new tar file. `append_file` content is\n+ # copied into a `new_file` and then content of other files needing repacking is appended to content of\n+ # `new_file`.\n+ append_file, match = files_to_repack_with_matches.popleft()\n+ new_file = append_file.parent / TAR_FRAGMENT_TMPL_FINISHED.format(\n+ fragment_idx=match.group(1), num_batches=num_batches_per_tarfile, file_idx=match.group(3)\n+ )\n+ new_file_sink = wds.TarWriter(str(new_file))\n+ append_ds_to_rewrite = (\n+ wds.WebDataset(urls=[str(append_file)], nodesplitter=None)\n+ .decode(wds.handle_extension('.pyd', decode_pyd))\n+ .to_tuple('__key__', 'batch.pyd')\n+ )\n+ for key, batch in iter(append_ds_to_rewrite):\n+ new_file_sink.write({\"__key__\": key, \"batch.pyd\": batch})\n+ new_file_num_batches += 1\n+ total_batches_in_repacked_files += 1\n+ assert total_batches_in_repacked_files < initial_number_of_files_to_repack * num_batches_per_tarfile\n+ assert new_file_num_batches == int(match.group(2)), (\n+ f\"Number of batches {new_file_num_batches} in {append_file} is different from number of batches \"\n+ f\"{match.group(2)} in repacked tar file with name {append_file}.\"\n+ )\n+ append_file.unlink()\n+ if files_to_repack_with_matches and pop_file_ds is None:\n+ pop_file, _ = files_to_repack_with_matches.pop()\n+ pop_file_ds = (\n+ wds.WebDataset(urls=[str(pop_file)], nodesplitter=None)\n+ .decode(wds.handle_extension('.pyd', decode_pyd))\n+ .to_tuple('__key__', 'batch.pyd')\n+ )\n+ pop_file_ds = iter(pop_file_ds)\n+ if pop_file_ds is not None and new_file_sink is not None:\n+ while new_file_num_batches < num_batches_per_tarfile:\n+ try:\n+ key, batch = next(pop_file_ds)\n+ except StopIteration:\n+ pop_file_ds = None\n+ pop_file.unlink()\n+ break\n+ new_file_sink.write({\"__key__\": key, \"batch.pyd\": batch})\n+ total_batches_in_repacked_files += 1\n+ assert total_batches_in_repacked_files < initial_number_of_files_to_repack * num_batches_per_tarfile\n+ new_file_num_batches += 1\n+ if new_file_num_batches >= num_batches_per_tarfile:\n+ assert new_file_num_batches == num_batches_per_tarfile\n+ new_file_sink.close()\n+ new_file_sink = None\n+ new_file_num_batches = 0\n+ if new_file_sink is not None:\n+ new_file_sink.close()\n+ new_file.unlink()\n+ logging.info(f\"Discarded {new_file_num_batches} batches.\")\n+ if pop_file_ds is not None:\n+ pop_file.unlink()\n+ logging.info(f\"Repacked {total_batches_in_repacked_files} batches from short tar files\")\n+\n+\n+def create_metadata_file(\n+ output_dir: Path, output_file_tmpl: str, metadata_file_name: Path, num_batches_per_tarfile: int\n+) -> None:\n+ \"\"\"\n+ Rename tar files according to template ``output_file_tmpl`` and save metadata file.\n+ Args:\n+ output_dir: a path to directory which contains initial tar files and where renamed tar files are saved\n+ output_file_tmpl: a template of a new tar file name\n+ metadata_file_name: a path to a file into which metadata is going to be saved\n+ num_batches_per_tarfile: a required number of batches in tar files. Used for checking that present tar files\n+ have correct number of batches\n+ \"\"\"\n+ metadata = {\"num_batches\": 0, \"tar_files\": []}\n+ for i, fn in enumerate([fn for fn in output_dir.iterdir() if TAR_FRAGMENT_PATTERN_FINISHED.match(fn.name)]):\n+ nb = int(TAR_FRAGMENT_PATTERN_FINISHED.match(fn.name).group(2))\n+ assert nb == num_batches_per_tarfile\n+ new_name = output_dir / output_file_tmpl.format(ctr=i, num_batches=nb)\n+ fn.rename(new_name)\n+ metadata['tar_files'].append(new_name.name)\n+ metadata[\"num_batches\"] += nb\n+ metadata[METADATA_PUNCT_LABEL_VOCAB_KEY] = DEFAULT_PUNCT_LABEL_VOCAB_FILE_NAME\n+ metadata[METADATA_CAPIT_LABEL_VOCAB_KEY] = DEFAULT_CAPIT_LABEL_VOCAB_FILE_NAME\n+ logging.info(f\"{metadata['num_batches']} batches are in tarred dataset with metadata file {metadata_file_name}\")\n+ with metadata_file_name.open('w') as f:\n+ json.dump(metadata, f, indent=2)\n+\n+\n+def create_tarred_dataset(\n+ text_file: Union[os.PathLike, str],\n+ labels_file: Union[os.PathLike, str],\n+ output_dir: Union[os.PathLike, str],\n+ max_seq_length: int,\n+ tokens_in_batch: int,\n+ lines_per_dataset_fragment: int,\n+ num_batches_per_tarfile: int,\n+ tokenizer_name: str,\n+ tokenizer_model: Optional[Union[os.PathLike, str]] = None,\n+ vocab_file: Optional[Union[os.PathLike, str]] = None,\n+ merges_file: Optional[Union[os.PathLike, str]] = None,\n+ special_tokens: Optional[Dict[str, str]] = None,\n+ use_fast_tokenizer: Optional[bool] = False,\n+ pad_label: str = 'O',\n+ punct_label_ids: Optional[Dict[str, int]] = None,\n+ capit_label_ids: Optional[Dict[str, int]] = None,\n+ punct_label_vocab_file: Optional[Union[os.PathLike, str]] = None,\n+ capit_label_vocab_file: Optional[Union[os.PathLike, str]] = None,\n+ tar_file_prefix: Optional[str] = 'punctuation_capitalization',\n+ n_jobs: Optional[int] = None,\n+) -> None:\n+ \"\"\"\n+ Creates tarred dataset from ``text_file`` and ``labels_file``. A tarred dataset allows to train on large amounts of\n+ data without storing it all into memory simultaneously. You may use these function directly or try script\n+ `examples/nlp/token_classification/data/create_punctuation_capitalization_tarred_dataset.py\n+ `_.\n+\n+ Tarred dataset is a directory which contains metadata file, tar files with batches, \n+ ``punct_label_vocab.csv`` and ``capit_label_vocab.csv`` files.\n+\n+ Metadata file is a JSON file with 4 items: ``'num_batches'``, ``'tar_files'``, ``'punct_label_vocab_file'``, \n+ ``'capit_label_vocab_file'``. The item ``'num_batches'`` (``int``) is a total number of batches in tarred dataset.\n+ ``'tar_files'`` is a list of paths to tar files relative to directory containing the metadata file. The items\n+ ``'punct_label_vocab_file'`` and ``'capit_label_vocab_file'`` are correspondingly paths to punctuation and\n+ capitalization label vocabulary files. These paths are relative to directory containing the metadata file.\n+\n+ Every tar file contains objects written using ``webdataset.TarWriter``. Each object is a dictionary with two items:\n+ ``'__key__'`` and ``'batch.pyd'``. ``'__key__'`` is a name of a batch and ``'batch.pyd'`` is a pickled dictionary\n+ which contains ``'input_ids'``, ``'subtokens_mask'``, ``'punct_labels'``, ``'capit_labels'``. ``'input_ids'`` is an\n+ array containing ids of source tokens, ``'subtokens_mask'`` is a boolean array showing first tokens in words,\n+ ``'punct_labels'`` and ``'capit_labels'`` are arrays with ids of labels.\n+\n+ Metadata file should be passed to constructor of :class:`BertPunctuationCapitalizationTarredDataset` and the\n+ instance of the class will handle iteration and constructing masks and token types for BERT model.\n+\n+ Args:\n+ text_file (:obj:`Union[os.PathLike, str]`): a path to a file with dataset source. Dataset source is lowercased\n+ text without punctuation. Number of lines in ``text_file`` has to be equal to the number of lines in\n+ ``labels_file``.\n+ labels_file (:obj:`Union[os.PathLike, str]`): a path to a file with labels. Labels are given in the format\n+ described in :ref:`NeMo Data Format`.\n+ output_dir (:obj:`Union[os.PathLike, str]`): a path to a directory where metadata file, tar files and\n+ ``'punct_label_ids.csv'`` and ``'capit_label_ids.csv'`` files are saved.\n+ max_seq_length (:obj:`int`): Maximum number of subtokens in an input sequence. A source sequence which contains\n+ too many subtokens is clipped to ``max_seq_length - 2`` subtokens and then [CLS] token is prepended to the\n+ clipped sequence and [SEP] token is appended to the clipped sequence. The clipping is performed via removal\n+ of subtokens in the end of a source sequence.\n+ tokens_in_batch (:obj:`int`): maximum number of tokens in a batch including [CLS], [SEP], [UNK], and [PAD]\n+ tokens. Before packing into batches source sequences are sorted by number of tokens in order to reduce\n+ number of pad tokens. So the number of samples in a batch may vary.\n+ lines_per_dataset_fragment (:obj:`int`): a number of lines processed by one worker during creation of tarred\n+ dataset. A worker tokenizes ``lines_per_dataset_fragment`` lines and keeps in RAM tokenized text labels\n+ before packing them into batches. Reducing ``lines_per_dataset_fragment`` leads to reducing of the amount\n+ of memory used by this function.\n+ num_batches_per_tarfile (:obj:`int`): a number of batches saved in a tar file. If you increase\n+ ``num_batches_per_tarfile``, then there will be less tar files in the dataset. There cannot be less then\n+ ``num_batches_per_tarfile`` batches in a tar file, and all excess batches are removed. Maximum number of\n+ discarded batches is ``num_batches_per_tarfile - 1``.\n+ tokenizer_name (:obj:`str`): a name of the tokenizer used for tokenization of source sequences. Possible\n+ options are ``'sentencepiece'``, ``'word'``, ``'char'``, HuggingFace tokenizers. For more options see\n+ function ``nemo.collections.nlp.modules.common.get_tokenizer``. The tokenizer must have properties\n+ ``cls_id``, ``pad_id``, ``sep_id``, ``unk_id``.\n+ tokenizer_model (:obj:`Union[os.PathLike, str]`, `optional`): a path to a tokenizer model required for\n+ ``'sentencepiece'`` tokenizer.\n+ vocab_file (:obj:`Union[os.PathLike, str]`, `optional`): a path to a vocabulary file which can be used in\n+ ``'word'``, ``'char'``, and HuggingFace tokenizers.\n+ merges_file (:obj:`Union[os.PathLike, str]`, `optional`): a path to merges file which can be used in\n+ HuggingFace tokenizers.\n+ special_tokens (:obj:`Dict[str, str]`, `optional`): a dictionary with special tokens passed to constructors of\n+ ``'char'``, ``'word'``, ``'sentencepiece'``, and various HuggingFace tokenizers.\n+ use_fast_tokenizer (:obj:`bool`, `optional`, defaults to :obj:`False`): whether to use fast HuggingFace\n+ tokenizer.\n+ pad_label (:obj:`str`, `optional`, defaults to :obj:`'O'`): a pad label both for punctuation and\n+ capitalization. This label is also a neutral label (used for marking words which do not need punctuation\n+ and capitalization).\n+ punct_label_ids (:obj:`Dict[str, int]`, `optional`): a dictionary which keys are punctuation labels and values\n+ are label ids. The pad label ``pad_label`` has to have id ``0``. You can provide at most one of parameters\n+ ``punct_label_ids`` and ``punct_label_vocab_file``. If none of parameters ``punct_label_ids`` and\n+ ``punct_label_vocab_file`` is provided, then punctuation label ids will be inferred from ``labels_file``\n+ file.\n+ capit_label_ids (:obj:`Dict[str, int]`, `optional`): same as ``punct_label_ids`` for capitalization labels.\n+ punct_label_vocab_file (:obj:`Union[os.PathLike, str]`, `optional`): a path to a file with punctuation labels.\n+ These labels include pad label. The pad label has to be the first label in the file. Each label is written\n+ on a separate line. Alternatively you can use ``punct_labels_ids`` parameter. If none of parameters\n+ ``punct_labels_ids`` and ``punct_label_vocab_file`` is provided, then punctuation label ids will be\n+ inferred from ``labels_file`` file.\n+ capit_label_vocab_file (:obj:`Union[os.PathLike, str]`, `optional`): same as ``punct_label_vocab_file`` for\n+ capitalization labels.\n+ tar_file_prefix (:obj:`str`, `optional`, defaults :obj:`'punctuation_capitalization'`): a string from which tar\n+ file names start.\n+ n_jobs (:obj:`int`, `optional`): a number of workers for creating tarred dataset. If ``None``, then ``n_jobs``\n+ is equal to number of CPUs.\n+ \"\"\"\n+ if n_jobs is None:\n+ n_jobs = mp.cpu_count()\n+ text_file, labels_file = Path(text_file).expanduser(), Path(labels_file).expanduser()\n+ output_dir = Path(output_dir).expanduser()\n+ ds_params_str = DATASET_PARAMETERS_TMPL.format(\n+ prefix=tar_file_prefix,\n+ tokens_in_batch=tokens_in_batch,\n+ max_seq_length=max_seq_length,\n+ tokenizer=tokenizer_name,\n+ )\n+ output_file_tmpl = ds_params_str + TAR_FINAL_TMPL\n+ metadata_file_name = output_dir / ('metadata.' + ds_params_str + '.json')\n+ remove_unexpected_files_and_dirs(output_dir, output_file_tmpl, metadata_file_name)\n+ num_lines, text_start_bytes, label_start_bytes = get_fragment_start_bytes(\n+ text_file, labels_file, lines_per_dataset_fragment\n+ )\n+ if text_start_bytes:\n+ output_dir.mkdir(parents=True, exist_ok=True)\n+ else:\n+ raise ValueError(f\"Both {labels_file} and {text_file} are empty. Tarred dataset cannot be created.\")\n+ punct_label_ids, capit_label_ids = get_label_dictionaries(\n+ labels_file,\n+ label_start_bytes,\n+ num_lines,\n+ lines_per_dataset_fragment,\n+ pad_label,\n+ punct_label_ids,\n+ capit_label_ids,\n+ punct_label_vocab_file,\n+ capit_label_vocab_file,\n+ n_jobs,\n+ )\n+\n+ with Progress(\n+ num_lines, [\"Tokenization\", \"Batch mark up\", \"Batch building\", \"Writing tarred dataset\"], \"query\"\n+ ) as progress_queues:\n+ Parallel(n_jobs=min(n_jobs, len(text_start_bytes)))(\n+ delayed(process_fragment)(\n+ text_file,\n+ labels_file,\n+ output_dir,\n+ text_start_pos,\n+ label_start_pos,\n+ lines_per_dataset_fragment,\n+ max_seq_length,\n+ tokens_in_batch,\n+ num_batches_per_tarfile,\n+ tokenizer_name,\n+ None if tokenizer_model is None else Path(tokenizer_model).expanduser(),\n+ None if vocab_file is None else Path(vocab_file).expanduser(),\n+ None if merges_file is None else Path(merges_file).expanduser(),\n+ special_tokens,\n+ use_fast_tokenizer,\n+ pad_label,\n+ punct_label_ids,\n+ capit_label_ids,\n+ fragment_idx,\n+ *progress_queues,\n+ )\n+ for fragment_idx, (text_start_pos, label_start_pos) in enumerate(zip(text_start_bytes, label_start_bytes))\n+ )\n+ repack_tar_files_with_not_enough_batches(output_dir, num_batches_per_tarfile)\n+ create_metadata_file(output_dir, output_file_tmpl, metadata_file_name, num_batches_per_tarfile)\n+\n+\n+class BertPunctuationCapitalizationTarredDataset(IterableDataset):\n+ \"\"\"\n+ Punctuation capitalization dataset which allows not to load all data in memory simultaneously. A tarred dataset\n+ is created from text and label files using script\n+ `examples/nlp/token_classification/data/create_punctuation_capitalization_tarred_dataset.py\n+ `_\n+ or function\n+ :func:`~nemo.collections.nlp.data.token_classification.punctuation_capitalization_tarred_dataset.create_tarred_dataset`.\n+\n+ Args:\n+ metadata_file (:obj:`Union[os.PathLike, str]`): a path to tarred dataset metadata file. Metadata file and files\n+ referenced in metadata file are created by\n+ `examples/nlp/token_classification/data/create_punctuation_capitalization_tarred_dataset.py\n+ `_.\n+ Metadata file is a JSON file which contains ``'num_batches'``, ``'tar_files'``,\n+ ``'punct_label_vocab_file'``, ``'capit_label_vocab_file'`` items. The first item is total number of batches\n+ in a dataset, the second is a list of paths to tar files relative to directory containing\n+ ``metadata_file``. Items ``'punct_label_vocab_file'`` and ``'capit_label_vocab_file'`` are paths to\n+ ``.csv`` files which contain unique punctuation an capitalization label vocabularies. Vocabulary file paths\n+ are relative to directory containing the ``metadata_file``. Each line in ``'punct_label_vocab_file'`` and\n+ ``'capit_label_vocab_file'`` contains 1 label. The first lines in ``'punct_label_vocab_file'`` and\n+ ``'capit_label_vocab_file'`` files are neutral labels which also serve as pad labels. Neutral labels for\n+ punctuation and capitalization must be equal to the ``pad_label`` parameter.\n+ tokenizer (:obj:`TokenizerSpec`): a tokenizer instance used for tokenization of dataset source. A tokenizer\n+ instance is used for getting ids of [CLS], [PAD], and [SEP] tokens which are used for masks creation.\n+ pad_label (:obj:`str`): a label that is used for padding and for absence of punctuation or\n+ capitalization. Used for checking items ``'punct_label_vocab'`` and ``'capit_label_vocab'`` of dictionary\n+ in ``metadata_file``.\n+ label_info_save_dir (:obj:`Union[os.PathLike, str]`, `optional`): a path to a directory where label\n+ vocabularies are copied when method :meth:`save_labels_and_get_file_paths` is called. This parameter is\n+ useful if tarred dataset directory is read-only.\n+ ignore_extra_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`): whether to use only first token in a\n+ word for loss computation and training. If set to ``True``, then loss will be computed only for the first\n+ tokens of words.\n+ ignore_start_end (:obj:`bool`, `optional`, defaults to :obj:`True`): whether to compute loss for [CLS] and\n+ [SEP] tokens. If set to ``True``, then loss will not be computed for [CLS] and [SEP] tokens.\n+ world_size (:obj:`int`, `optional`, defaults to :obj:`1`): a number of processes used for model training. It is\n+ used together with a ``global_rank`` parameter to decide which tar files will be used in the current\n+ process.\n+ global_rank (:obj:`int`, `optional`, defaults to :obj:`0`): a number of current process in the pool of workers\n+ used for model training. It is used together with ``world_size`` parameter to decide which tar files will\n+ be used in the current process.\n+ shuffle_n (:obj:`int`, `optional`, defaults to :obj:`1`): a number of shuffled batches in a buffer.\n+ ``shuffle_n`` batches are loaded into memory, shuffled, and then yielded by a dataset instance.\n+ \"\"\"\n+\n+ @property\n+ def output_types(self) -> Optional[Dict[str, NeuralType]]:\n+ \"\"\"Returns neural types of batches yielded by this dataset.\"\"\"\n+ return {\n+ 'input_ids': NeuralType(('B', 'T'), ChannelType()),\n+ 'segment_ids': NeuralType(('B', 'T'), ChannelType()),\n+ 'input_mask': NeuralType(('B', 'T'), MaskType()),\n+ 'subtokens_mask': NeuralType(('B', 'T'), MaskType()),\n+ 'loss_mask': NeuralType(('B', 'T'), MaskType()),\n+ 'punct_labels': NeuralType(('B', 'T'), LabelsType()),\n+ 'capit_labels': NeuralType(('B', 'T'), LabelsType()),\n+ }\n+\n+ def __init__(\n+ self,\n+ metadata_file: Union[os.PathLike, str],\n+ tokenizer: TokenizerSpec,\n+ pad_label: str,\n+ label_info_save_dir: Optional[Union[os.PathLike, str]] = None,\n+ ignore_extra_tokens: bool = False,\n+ ignore_start_end: bool = True,\n+ world_size: int = 1,\n+ global_rank: int = 0,\n+ shuffle_n: int = 1,\n+ ) -> None:\n+ super().__init__()\n+ self.tokenizer = tokenizer\n+ self.metadata_file = Path(metadata_file).expanduser()\n+ if label_info_save_dir is None:\n+ self.for_nemo_ckpt = self.metadata_file.parent / LABEL_ID_DIR_FOR_NEMO_CHECKPOINT\n+ else:\n+ self.for_nemo_ckpt = Path(label_info_save_dir).expanduser() / LABEL_ID_DIR_FOR_NEMO_CHECKPOINT\n+ with open(self.metadata_file) as f:\n+ self.metadata = json.load(f)\n+ self.ignore_extra_tokens = ignore_extra_tokens\n+ self.ignore_start_end = ignore_start_end\n+ self.tar_files = []\n+ for file_path in self.metadata['tar_files']:\n+ file_path = Path(file_path).expanduser()\n+ if file_path.is_absolute():\n+ self.tar_files.append(str(file_path))\n+ else:\n+ self.tar_files.append(str(self.metadata_file.parent / file_path))\n+ self.punct_label_vocab_file = self.metadata_file.parent / self.metadata[METADATA_PUNCT_LABEL_VOCAB_KEY]\n+ self.capit_label_vocab_file = self.metadata_file.parent / self.metadata[METADATA_CAPIT_LABEL_VOCAB_KEY]\n+ self.punct_label_ids = load_label_ids(self.punct_label_vocab_file)\n+ self.capit_label_ids = load_label_ids(self.capit_label_vocab_file)\n+ self.pad_label = pad_label\n+ self._check_pad_label()\n+ begin_idx = (len(self.tar_files) // world_size) * global_rank\n+ end_idx = begin_idx + (len(self.tar_files) // world_size)\n+ logging.info(\n+ \"Partitioning tarred dataset: process (%d) taking shards [%d, %d)\", global_rank, begin_idx, end_idx\n+ )\n+ self.tar_files = self.tar_files[begin_idx:end_idx]\n+ self.length = self.metadata['num_batches'] // world_size\n+ self._dataset = wds.WebDataset(urls=self.tar_files, nodesplitter=None).decode(\n+ wds.handle_extension('.pyd', decode_pyd)\n+ )\n+ if shuffle_n > 0:\n+ self._dataset.shuffle(shuffle_n)\n+ else:\n+ logging.info(\"WebDataset will not shuffle files within the tar files.\")\n+ self._dataset = self._dataset.to_tuple('__key__', 'batch.pyd').map(f=self._build_sample)\n+\n+ def _check_pad_label(self) -> None:\n+ \"\"\"\n+ Checks the condition that ``pad_label`` passed to this class constructor has ``0`` id in\n+ ``self.punct_label_ids`` and ``self.capit_label_ids`` loaded from tarred dataset.\n+ \"\"\"\n+ for label_ids, labels_file, task in [\n+ (self.punct_label_ids, self.metadata[METADATA_PUNCT_LABEL_VOCAB_KEY], \"punctuation\"),\n+ (self.capit_label_ids, self.metadata[METADATA_CAPIT_LABEL_VOCAB_KEY], \"capitalization\"),\n+ ]:\n+ if label_ids[self.pad_label] != 0:\n+ raise ValueError(\n+ f\"Pad label '{self.pad_label}' has non zero id {label_ids[self.pad_label]} in {task} \"\n+ f\"ids dictionary loaded from {labels_file}.\"\n+ )\n+\n+ def check_for_label_consistency_with_model_config(\n+ self,\n+ punct_label_ids: Optional[Dict[str, int]],\n+ capit_label_ids: Optional[Dict[str, int]],\n+ class_labels: DictConfig,\n+ common_dataset_parameters_config: DictConfig,\n+ ) -> None:\n+ \"\"\"\n+ Checks that label ids loaded from tarred dataset are identical to those provided in\n+ ``model.common_dataset_parameters`` :ref:`config` item. In addition,\n+ this method checks that label ids set in attributes ``punct_label_ids`` and ``capit_label_ids`` of an instance\n+ of\n+ :class:`~nemo.collections.nlp.models.token_classification.punctuation_capitalization_model.PunctuationCapitalizationModel`\n+ are identical to label ids loaded from tarred dataset.\n+\n+ Args:\n+ punct_label_ids: a content of ``punct_label_ids`` attribute of an instance of\n+ :class:`~nemo.collections.nlp.models.token_classification.punctuation_capitalization_model.PunctuationCapitalizationModel`\n+ in which this tarred dataset is used.\n+ capit_label_ids: a content of ``capit_label_ids`` attribute of an instance of\n+ :class:`~nemo.collections.nlp.models.token_classification.punctuation_capitalization_model.PunctuationCapitalizationModel`\n+ in which this tarred dataset is used.\n+ class_labels: a config item ``model.class_labels``. See more in description of\n+ :ref:`class labels config`.\n+ common_dataset_parameters_config: a config item ``model.common_dataset_parameters``. See more in\n+ of :ref:`common dataset parameters config`.\n+ \"\"\"\n+ tarred_dataset_label_desc_tmpl = (\n+ f'{{label_type}} labels loaded from tarred dataset with metadata file {self.metadata_file}'\n+ )\n+ if punct_label_ids is not None:\n+ if punct_label_ids != self.punct_label_ids:\n+ raise_not_equal_labels_error(\n+ first_labels=self.punct_label_ids,\n+ second_labels=punct_label_ids,\n+ first_labels_desc=tarred_dataset_label_desc_tmpl.format(label_type='Punctuation'),\n+ second_labels_desc=\"Punctuation labels stored in an attribute \"\n+ \"`PunctuationCapitalizationModel.punct_label_ids`\",\n+ )\n+ if capit_label_ids is not None:\n+ if capit_label_ids != self.capit_label_ids:\n+ raise_not_equal_labels_error(\n+ first_labels=self.capit_label_ids,\n+ second_labels=capit_label_ids,\n+ first_labels_desc=tarred_dataset_label_desc_tmpl.format(label_type='Capitalization'),\n+ second_labels_desc=\"Capitalization labels stored in an attribute\"\n+ \"`PunctuationCapitalizationModel.capit_label_ids`\",\n+ )\n+ if common_dataset_parameters_config.punct_label_ids is not None:\n+ cfg_punct_label_ids = dict(common_dataset_parameters_config.punct_label_ids)\n+ if cfg_punct_label_ids != self.punct_label_ids:\n+ raise_not_equal_labels_error(\n+ first_labels=self.punct_label_ids,\n+ second_labels=cfg_punct_label_ids,\n+ first_labels_desc=tarred_dataset_label_desc_tmpl.format(label_type='Punctuation'),\n+ second_labels_desc='Punctuation labels stored a config field '\n+ '`model.common_dataset_parameters.punct_label_ids`',\n+ )\n+ if common_dataset_parameters_config.capit_label_ids is not None:\n+ cfg_capit_label_ids = dict(common_dataset_parameters_config.capit_label_ids)\n+ if cfg_capit_label_ids != self.capit_label_ids:\n+ raise_not_equal_labels_error(\n+ first_labels=self.capit_label_ids,\n+ second_labels=cfg_capit_label_ids,\n+ first_labels_desc=tarred_dataset_label_desc_tmpl.format(label_type='Capitalization'),\n+ second_labels_desc='Capitalization labels stored a config field '\n+ '`model.common_dataset_parameters.capit_label_ids`',\n+ )\n+ if common_dataset_parameters_config.label_vocab_dir is not None:\n+ label_vocab_dir = Path(common_dataset_parameters_config.label_vocab_dir).expanduser()\n+ punct_label_vocab_file = label_vocab_dir / class_labels.punct_labels_file\n+ file_punct_vocab = load_label_ids(punct_label_vocab_file)\n+ if file_punct_vocab != self.punct_label_ids:\n+ raise_not_equal_labels_error(\n+ first_labels=self.punct_label_ids,\n+ second_labels=file_punct_vocab,\n+ first_labels_desc=tarred_dataset_label_desc_tmpl.format(label_type='Punctuation'),\n+ second_labels_desc=f'labels stored in file {punct_label_vocab_file} passed in '\n+ f'`model.common_dataset_parameters.punct_label_vocab_file`',\n+ )\n+ capit_label_vocab_file = label_vocab_dir / class_labels.capit_labels_file\n+ file_capit_vocab = load_label_ids(capit_label_vocab_file)\n+ if file_capit_vocab != self.capit_label_ids:\n+ raise_not_equal_labels_error(\n+ first_labels=self.capit_label_ids,\n+ second_labels=file_capit_vocab,\n+ first_labels_desc=tarred_dataset_label_desc_tmpl.format(label_type='Capitalization'),\n+ second_labels_desc=f'labels stored in file {capit_label_vocab_file} passed in '\n+ f'`model.common_dataset_parameters.capit_label_vocab_file`',\n+ )\n+\n+ def save_labels_and_get_file_paths(\n+ self, punct_labels_file_name: str, capit_labels_file_name: str\n+ ) -> Tuple[Path, Path]:\n+ \"\"\"\n+ Copies label vocabulary files for punctuation and capitalization into directory passed in the constructor\n+ parameter ``label_info_save_dir``. The names of new\n+ files are ``punct_labels_file_name`` and ``capit_labels_file_name``.\n+\n+ The signatures of this method and the signature of the method\n+ :meth:`~nemo.collections.nlp.data.token_classification.BertPunctuationCapitalizationDataset.save_labels_and_get_file_paths`\n+ must be identical.\n+\n+ Args:\n+ punct_labels_file_name (:obj:`str`): a name of punctuation labels file\n+ capit_labels_file_name (:obj:`str`): a name of capitalization labels file\n+\n+ Returns:\n+ :obj:`Tuple[Path, Path]`: a tuple of 2 elements\n+\n+ - :obj:`pathlib.Path`: a path to the new punctuation label ids file\n+ - :obj:`pathlib.Path`: a path to the new capitalization label ids file\n+ \"\"\"\n+ self.for_nemo_ckpt.mkdir(parents=True, exist_ok=True)\n+ punct_label_ids_file = self.for_nemo_ckpt / punct_labels_file_name\n+ capit_label_ids_file = self.for_nemo_ckpt / capit_labels_file_name\n+ shutil.copy(str(self.punct_label_vocab_file), str(punct_label_ids_file))\n+ shutil.copy(str(self.capit_label_vocab_file), str(capit_label_ids_file))\n+ return punct_label_ids_file, capit_label_ids_file\n+\n+ def _build_sample(self, batch: Tuple[str, Dict[str, ArrayLike]]) -> Dict[str, ArrayLike]:\n+ \"\"\"\n+ Takes batch loaded from tarred dataset and transforms it for passing to the model. Adds ``'segment_ids'``,\n+ ``'input_mask'``, ``'loss_mask'`` items to the batch.\n+\n+ Args:\n+ batch: a tuple of 2 elements: batch name and a dictionary with ``'input_ids'``, ``'subtokens_mask'``,\n+ ``'punct_labels'``, ``'capit_labels'``. Batch name is not needed for training and inference and\n+ discarded.\n+\n+ Returns:\n+ a batch in the form of a dictionary with items:\n+ - ``'input_ids'``: a ``np.int32`` numpy array of shape ``[Batch, Time]``;\n+ - ``'subtokens_mask'``: a boolean numpy array of shape ``[Batch, Time]``;\n+ - ``'punct_labels'``: a ``np.int32`` numpy array of shape ``[Batch, Time]``;\n+ - ``'capit_labels'``: a ``np.int32`` numpy array of shape ``[Batch, Time]``;\n+ - ``'segment_ids'``: a ``np.int8`` numpy array of shape ``[Batch, Time]``;\n+ - ``'input_mask'``: a boolean numpy array of shape ``[Batch, Time]``;\n+ - ``'loss_mask'``: a boolean numpy array of shape ``[Batch, Time]``.\n+ \"\"\"\n+ _, batch = batch\n+ batch_segment_ids, batch_input_mask, batch_loss_mask = create_masks_and_segment_ids(\n+ batch['input_ids'],\n+ batch['subtokens_mask'],\n+ self.tokenizer.pad_id,\n+ self.tokenizer.cls_id,\n+ self.tokenizer.sep_id,\n+ self.ignore_start_end,\n+ self.ignore_extra_tokens,\n+ )\n+ batch['segment_ids'] = batch_segment_ids\n+ batch['input_mask'] = batch_input_mask\n+ batch['loss_mask'] = batch_loss_mask\n+ return batch\n+\n+ def __iter__(self) -> Iterator[Dict[str, ArrayLike]]:\n+ \"\"\"\n+ Constructs an iterator of batches. The values of one batch dictionary are numpy arrays of identical shapes\n+ ``[Batch, Time]``.\n+\n+ Returns:\n+ :obj:`Iterator[Dict[str, ArrayLike]]`: an iterator of batches with items:\n+\n+ - ``'input_ids'``: ``np.int32`` array containing encoded tokens,\n+ - ``'subtokens_mask'``: ``bool`` array which elements are ``True`` if they correspond to first token in\n+ a word,\n+ - ``'punct_labels'``: ``np.int32`` array with encoded punctuation labels,\n+ - ``'capit_labels'``: ``np.int32`` array with encoded capitalization labels,\n+ - ``'segment_ids'``: ``np.int8`` array filled with zeros (BERT token types in HuggingFace terminology),\n+ - ``'input_mask'``: ``bool`` array which elements are ``True`` if corresponding token is not a padding\n+ token,\n+ - ``'loss_mask'``: ``bool`` array which elements are ``True`` if loss is computed for corresponding\n+ token. See more in description of constructor parameters ``ignore_start_end``, ``ignore_extra_tokens``.\n+ \"\"\"\n+ return self._dataset.__iter__()\n+\n+ def __len__(self) -> int:\n+ return self.length\n+\n+ @staticmethod\n+ def collate_fn(batches: List[Dict[str, ArrayLike]]) -> Dict[str, torch.Tensor]:\n+ \"\"\"\n+ Return zeroth batch of ``batches`` list passed for collating and casts ``'segment_ids'``, ``'punct_labels'``,\n+ ``'capit_labels'`` to types supported by\n+ :class:`~nemo.collections.nlp.models.token_classification.punctuation_capitalization_model.PunctuationCapitalizationModel`.\n+ All output tensors have shape ``[Batch, Time]``.\n+\n+ .. warning::\n+ ``batch size`` parameter of a PyTorch data loader and sampler has to be ``1``.\n+\n+ Args:\n+ batches (:obj:`List[Dict[str, ArrayLike]]`): a list of batches passed for collating\n+\n+ Returns:\n+ :obj:`Dict[str, torch.Tensor]`: a batch dictionary with following items (for detailed description of batch\n+ items see method :meth:`__getitem__`):\n+\n+ - ``'input_ids'`` (:obj:`torch.Tensor`): :obj:`torch.int32` tensor,\n+ - ``'subtokens_mask'`` (:obj:`torch.Tensor`): :obj:`torch.bool` tensor,\n+ - ``'punct_labels'`` (:obj:`torch.Tensor`): :obj:`torch.int64` tensor,\n+ - ``'capit_labels'`` (:obj:`torch.Tensor`): :obj:`torch.int64` tensor,\n+ - ``'segment_ids'`` (:obj:`torch.Tensor`): :obj:`torch.int32` tensor,\n+ - ``'input_mask'`` (:obj:`torch.Tensor`): :obj:`torch.bool` tensor,\n+ - ``'loss_mask'`` (:obj:`torch.Tensor`): :obj:`torch.bool` tensor.\n+ \"\"\"\n+ batch = {k: torch.as_tensor(v) for k, v in batches[0].items()}\n+ batch['segment_ids'] = batch['segment_ids'].int()\n+ batch['punct_labels'] = batch['punct_labels'].long()\n+ batch['capit_labels'] = batch['capit_labels'].long()\n+ return batch\ndiff --git a/nemo/collections/nlp/models/nlp_model.py b/nemo/collections/nlp/models/nlp_model.py\n--- a/nemo/collections/nlp/models/nlp_model.py\n+++ b/nemo/collections/nlp/models/nlp_model.py\n@@ -65,7 +65,8 @@ def __init__(self, cfg: DictConfig, trainer: Trainer = None):\n def register_artifact(\n self, config_path: str, src: str, verify_src_exists: bool = False,\n ):\n- \"\"\" Overrides ModelPT register_artifact default behavior. NLP models usually need artifacts that are optional.\"\"\"\n+ \"\"\" Overrides ModelPT register_artifact default behavior.\n+ NLP models usually need artifacts that are optional.\"\"\"\n return super().register_artifact(config_path, src, verify_src_exists=verify_src_exists)\n \n @rank_zero_only\ndiff --git a/nemo/collections/nlp/models/token_classification/__init__.py b/nemo/collections/nlp/models/token_classification/__init__.py\n--- a/nemo/collections/nlp/models/token_classification/__init__.py\n+++ b/nemo/collections/nlp/models/token_classification/__init__.py\n@@ -12,7 +12,9 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n-\n+from nemo.collections.nlp.models.token_classification.punctuation_capitalization_config import (\n+ PunctuationCapitalizationModelConfig,\n+)\n from nemo.collections.nlp.models.token_classification.punctuation_capitalization_model import (\n PunctuationCapitalizationModel,\n )\ndiff --git a/nemo/collections/nlp/models/token_classification/punctuation_capitalization_config.py b/nemo/collections/nlp/models/token_classification/punctuation_capitalization_config.py\nnew file mode 100644\n--- /dev/null\n+++ b/nemo/collections/nlp/models/token_classification/punctuation_capitalization_config.py\n@@ -0,0 +1,325 @@\n+# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+from dataclasses import dataclass\n+from typing import Any, Dict, Optional\n+\n+from omegaconf.omegaconf import MISSING, DictConfig, OmegaConf\n+\n+from nemo.collections.nlp.data.token_classification.punctuation_capitalization_dataset import (\n+ PunctuationCapitalizationEvalDataConfig,\n+ PunctuationCapitalizationTrainDataConfig,\n+ legacy_data_config_to_new_data_config,\n+)\n+from nemo.core.config import TrainerConfig\n+from nemo.core.config.modelPT import NemoConfig\n+from nemo.utils.exp_manager import ExpManagerConfig\n+\n+\n+@dataclass\n+class TokenizerConfig:\n+ \"\"\"A structure and default values of source text tokenizer.\"\"\"\n+\n+ vocab_file: Optional[str] = None\n+ \"\"\"A path to vocabulary file which is used in ``'word'``, ``'char'``, and HuggingFace tokenizers\"\"\"\n+\n+ tokenizer_name: str = MISSING\n+ \"\"\"A name of the tokenizer used for tokenization of source sequences. Possible options are ``'sentencepiece'``,\n+ ``'word'``, ``'char'``, HuggingFace tokenizers (e.g. ``'bert-base-uncased'``). For more options see function\n+ ``nemo.collections.nlp.modules.common.get_tokenizer``. The tokenizer must have properties ``cls_id``, ``pad_id``,\n+ ``sep_id``, ``unk_id``.\"\"\"\n+\n+ special_tokens: Optional[Dict[str, str]] = None\n+ \"\"\"A dictionary with special tokens passed to constructors of ``'char'``, ``'word'``, ``'sentencepiece'``, and\n+ various HuggingFace tokenizers.\"\"\"\n+\n+ tokenizer_model: Optional[str] = None\n+ \"\"\"A path to a tokenizer model required for ``'sentencepiece'`` tokenizer.\"\"\"\n+\n+\n+@dataclass\n+class LanguageModelConfig:\n+ \"\"\"\n+ A structure and default values of language model configuration of punctuation and capitalization model. BERT like\n+ HuggingFace models are supported. Provide a valid ``pretrained_model_name`` and, optionally, you may\n+ reinitialize model via ``config_file`` or ``config``.\n+\n+ Alternatively you can initialize the language model using ``lm_checkpoint``.\n+\n+ This config is a part of :class:`PunctuationCapitalizationModelConfig` config.\n+ \"\"\"\n+\n+ pretrained_model_name: str = MISSING\n+ \"\"\"A mandatory parameter containing name of HuggingFace pretrained model. For example, ``'bert-base-uncased'``.\"\"\"\n+\n+ config_file: Optional[str] = None\n+ \"\"\"A path to a file with HuggingFace model config which is used to reinitialize language model.\"\"\"\n+\n+ config: Optional[Dict] = None\n+ \"\"\"A HuggingFace config which is used to reinitialize language model.\"\"\"\n+\n+ lm_checkpoint: Optional[str] = None\n+ \"\"\"A path to a ``torch`` checkpoint of a language model.\"\"\"\n+\n+\n+@dataclass\n+class HeadConfig:\n+ \"\"\"\n+ A structure and default values of configuration of capitalization or punctuation model head. This config defines a\n+ multilayer perceptron which is applied to outputs of a language model. Number of units in the hidden layer is equal\n+ to the dimension of the language model.\n+\n+ This config is a part of :class:`PunctuationCapitalizationModelConfig` config.\n+ \"\"\"\n+\n+ num_fc_layers: int = 1\n+ \"\"\"A number of hidden layers in a multilayer perceptron.\"\"\"\n+\n+ fc_dropout: float = 0.1\n+ \"\"\"A dropout used in an MLP.\"\"\"\n+\n+ activation: str = 'relu'\n+ \"\"\"An activation used in hidden layers.\"\"\"\n+\n+ use_transformer_init: bool = True\n+ \"\"\"Whether to initialize the weights of the classifier head with the approach that was used for language model\n+ initialization.\"\"\"\n+\n+\n+@dataclass\n+class ClassLabelsConfig:\n+ \"\"\"\n+ A structure and default values of a mandatory part of config which contains names of files which are saved in .nemo\n+ checkpoint. These files can also be used for passing label vocabulary to the model. For using them as label\n+ vocabularies you will need to provide path these files in parameter\n+ ``model.common_dataset_parameters.label_vocab_dir``. Each line in labels files\n+ contains 1 label. The values are sorted, ``==