├── LICENSE ├── README.md ├── bootstrapped_vocabulary ├── non_padded_namespaces.txt └── tokens.txt ├── pointergen ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-36.pyc │ ├── beam_search_predictor.cpython-36.pyc │ ├── cnndmail_dataset_reader.cpython-36.pyc │ ├── custom_instance.cpython-36.pyc │ ├── fields.cpython-36.pyc │ └── model.cpython-36.pyc ├── beam_search_predictor.py ├── cnndmail_dataset_reader.py ├── custom_instance.py ├── fields.py ├── model.py └── model_withcoverage.py ├── pretrained_model_skeleton.tar.gz ├── pretrained_model_skeleton_withcoverage.tar.gz ├── sample_datafile.jsonl └── sample_experiment.jsonnet /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | PointerGenerator network implementation in AllenNLP 2 | --- 3 | 4 | This repo contains an implementation of the pointer-generator network from [See et al (2017)](https://arxiv.org/abs/1704.04368) 5 | in PyTorch wrapped in the AllenNLP framework. You need to use allennlp version 0.8.5 6 | 7 | 8 | #### Running pretrained model 9 | 10 | We are releasing the pretrained model parameters from See et al converted into 11 | PyTorch's format. You can download the pretrained parameter file from [here](https://drive.google.com/drive/folders/1vU6-npbiPjw4ZUuy1LXzaN6XhETWrg74?usp=sharing) 12 | 13 | To run the pretrained model without coverage, use the command 14 | 15 | `allennlp predict pretrained_model_skeleton.tar.gz --weights-file see_etal_weights_without_coverage.th --include-package pointergen --cuda-device --predictor beamsearch ` 16 | 17 | where `weights-file` is the PyTorch pretrained weights file downloaded from the link above. A sample 18 | `test-file` has been provided to illustrate the input jsonl format. 19 | 20 | 21 | For the model with coverage, use 22 | 23 | `allennlp predict pretrained_model_skeleton_withcoverage.tar.gz --weights-file see_etal_weights_with_coverage.th --include-package pointergen --cuda-device --predictor beamsearch ` 24 | 25 | 26 | 27 | #### Training your own model 28 | 29 | The configuration for training a model is given in the `sample_experiment.jsonnet` file. You have to provide paths 30 | to the training and validation jsonl files in it. You can also customize the model size 31 | and optimizer parameters via this file. To train a model, run the command 32 | 33 | `allennlp train sample_experiment.jsonnet --include-package pointergen -s ` 34 | 35 | The above command will train the model without the coverage loss. To further train the model with coverage loss, follow the next steps. 36 | Suppose the serialization directory of the model trained without coverage is `precoverage`. Then run 37 | 38 | 39 | `allennlp train precoverage/config.json --include-package pointergen -s postcoverage --overrides '{"model":{"type":"pointer_generator_withcoverage"}, "trainer":{"num_epochs":1}, "vocabulary": {"extend": true, "directory_path": "precoverage/vocabulary", "max_vocab_size":1}}'` 40 | 41 | We will discuss why this command looks so ugly later. After running this command, you would be asked if you want to load weigths from a non-coverage model. Enter yes and in the next prompt enter the path to the weights (`precoverage/best.th` in this case) 42 | 43 | To make predictions on a test file, the usual command is used. 44 | 45 | `allennlp predict postcoverage/model.tar.gz --include-package pointergen --cuda-device 0 --predictor beamsearch sample_datafile.jsonl` 46 | 47 | You would see the same prompt, just reply no to it and the program would continue as usual. 48 | 49 | 50 | #### What do the entries in overrides flag do? 51 | 52 | We prefer to override the settings of the precoverage config.json file rather than creating a new one so that it is ensured that the other parameters of the experiment remain the same (eg. hidden size of LSTM layers). The overrides change the model type to `pointer_generator_coverage` and the number of epochs can be set as required for finetuning. Since we will be loading pretrained weights, we must make sure that the vocabulary of the new model is same as the one that the old one had. This might easily not hold true if for example, you finetune on a slightly different training dataset or a subset of it. So to enforce it we give the path of the vocabulary of the old precoverage model. Ideally the `extend` flag should have been turned to false to disallow further additions to the vocabulary. But then allennlp complains that it was passed an extra parameter `max_vocab_size` which was picked up from the `precoverage/config.json` file. So we set it `extend` to true but pass a very small value of `max_vocab_size` through the override which is certainly even smaller than the loaded vocabulary and hence further additions do not happen to it. Why didn't we set `max_vocab_size` to 0? Because it is interpreted by allennlp as a directive to not place any bounds on the vocabulary size. So we set it to 1 which still has the effect that we want. 53 | 54 | -------------------------------------------------------------------------------- /bootstrapped_vocabulary/non_padded_namespaces.txt: -------------------------------------------------------------------------------- 1 | *tags 2 | *labels 3 | -------------------------------------------------------------------------------- /bootstrapped_vocabulary/tokens.txt: -------------------------------------------------------------------------------- 1 | @@UNKNOWN@@ 2 | @start@ 3 | @end@ 4 | -------------------------------------------------------------------------------- /pointergen/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kukrishna/pointer-generator-pytorch-allennlp/4e4dde6eb100bcd5b8e7534738ddb77fd854e3d7/pointergen/__init__.py -------------------------------------------------------------------------------- /pointergen/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kukrishna/pointer-generator-pytorch-allennlp/4e4dde6eb100bcd5b8e7534738ddb77fd854e3d7/pointergen/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /pointergen/__pycache__/beam_search_predictor.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kukrishna/pointer-generator-pytorch-allennlp/4e4dde6eb100bcd5b8e7534738ddb77fd854e3d7/pointergen/__pycache__/beam_search_predictor.cpython-36.pyc -------------------------------------------------------------------------------- /pointergen/__pycache__/cnndmail_dataset_reader.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kukrishna/pointer-generator-pytorch-allennlp/4e4dde6eb100bcd5b8e7534738ddb77fd854e3d7/pointergen/__pycache__/cnndmail_dataset_reader.cpython-36.pyc -------------------------------------------------------------------------------- /pointergen/__pycache__/custom_instance.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kukrishna/pointer-generator-pytorch-allennlp/4e4dde6eb100bcd5b8e7534738ddb77fd854e3d7/pointergen/__pycache__/custom_instance.cpython-36.pyc -------------------------------------------------------------------------------- /pointergen/__pycache__/fields.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kukrishna/pointer-generator-pytorch-allennlp/4e4dde6eb100bcd5b8e7534738ddb77fd854e3d7/pointergen/__pycache__/fields.cpython-36.pyc -------------------------------------------------------------------------------- /pointergen/__pycache__/model.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kukrishna/pointer-generator-pytorch-allennlp/4e4dde6eb100bcd5b8e7534738ddb77fd854e3d7/pointergen/__pycache__/model.cpython-36.pyc -------------------------------------------------------------------------------- /pointergen/beam_search_predictor.py: -------------------------------------------------------------------------------- 1 | from allennlp.predictors.predictor import Predictor 2 | from allennlp.models.model import Model 3 | from allennlp.data.dataset_readers import DatasetReader 4 | from allennlp.data import Instance 5 | from overrides import overrides 6 | from allennlp.common.util import JsonDict 7 | 8 | from sumeval.metrics.rouge import RougeCalculator 9 | 10 | 11 | 12 | @Predictor.register("beamsearch") 13 | class BeamSearchPredictor(Predictor): 14 | def __init__(self, model: Model, dataset_reader: DatasetReader) -> None: 15 | super().__init__(model, dataset_reader) 16 | self.rouge = RougeCalculator(stopwords=True, lang="en") 17 | 18 | @overrides 19 | def _json_to_instance(self, json_dict: JsonDict) -> Instance: 20 | """ 21 | Expects JSON that looks like ``{"article_lines": ["...", "...", ...], "summary_lines": ["...", "...", ...]}``. 22 | """ 23 | return self._dataset_reader.dict_to_instance(json_dict) 24 | 25 | @overrides 26 | def predict_json(self, inputs: JsonDict) -> JsonDict: 27 | instance = self._json_to_instance(inputs) 28 | predicted = self.predict_instance(instance) 29 | ground_truth = " ".join(instance.fields["meta"]["target_tokens"]) 30 | 31 | return {"ground_truth": ground_truth, 32 | "prediction": predicted} 33 | 34 | 35 | -------------------------------------------------------------------------------- /pointergen/cnndmail_dataset_reader.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from typing import List, Dict 3 | 4 | import numpy as np 5 | 6 | import jsonlines 7 | 8 | from allennlp.common.checks import ConfigurationError 9 | from allennlp.common.util import START_SYMBOL, END_SYMBOL 10 | from allennlp.data.dataset_readers.dataset_reader import DatasetReader 11 | from allennlp.data.fields import TextField, ArrayField, MetadataField, NamespaceSwappingField 12 | from allennlp.data.instance import Instance 13 | from allennlp.data.tokenizers import Token, Tokenizer, WordTokenizer 14 | from allennlp.data.token_indexers import TokenIndexer, SingleIdTokenIndexer 15 | from allennlp.data.tokenizers.word_splitter import JustSpacesWordSplitter 16 | 17 | from overrides import overrides 18 | 19 | from pointergen.custom_instance import SyncedFieldsInstance 20 | from pointergen.fields import SourceTextField, TargetTextField 21 | 22 | logger = logging.getLogger(__name__) # pylint: disable=invalid-name 23 | 24 | 25 | @DatasetReader.register("cnndmail_dataset_reader") 26 | class CNNDmailDatasetReader(DatasetReader): 27 | def __init__(self, 28 | max_source_length : int = 400, 29 | max_target_length : int =100, 30 | tokenizer: Tokenizer = None, 31 | token_indexers: Dict[str, TokenIndexer] = None, 32 | lowercase_tokens : bool = False, 33 | lazy: bool = False, 34 | max_to_read = np.inf) -> None: 35 | super().__init__(lazy) 36 | self.lowercase_tokens = lowercase_tokens 37 | self.max_source_length = max_source_length 38 | self.max_target_length = max_target_length 39 | self.max_to_read = max_to_read 40 | self._tokenizer = tokenizer or WordTokenizer(word_splitter=JustSpacesWordSplitter()) 41 | self._token_indexers = token_indexers or {"tokens": SingleIdTokenIndexer()} 42 | if "tokens" not in self._token_indexers or \ 43 | not isinstance(self._token_indexers["tokens"], SingleIdTokenIndexer): 44 | raise ConfigurationError("CNNDmailDatasetReader expects 'token_indexers' to contain " 45 | "a 'single_id' token indexer called 'tokens'.") 46 | 47 | 48 | @overrides 49 | def _read(self, file_path): 50 | logger.info("Reading instances from lines in file at: %s", file_path) 51 | with jsonlines.open(file_path, "r") as reader: 52 | num_passed = 0 53 | for dp in reader: 54 | if num_passed == self.max_to_read: 55 | raise StopIteration 56 | if len(" ".join(dp["article_lines"]))==0: # if the input article has length 0 then there is a crash due to some NaN popping up. there are 114 such datapoins in cnndmail trainset 57 | continue 58 | num_passed += 1 59 | yield self.dict_to_instance(dp) 60 | 61 | def dict_to_instance(self, dp): 62 | source_sequence = " ".join(dp["article_lines"]) 63 | target_sequence = " ".join(dp["summary_lines"]) 64 | source_words_truncated = source_sequence.split(" ")[:self.max_source_length] 65 | target_words_truncated = target_sequence.split(" ")[:self.max_target_length] 66 | source_sequence = " ".join(source_words_truncated) 67 | target_sequence = " ".join(target_words_truncated) 68 | return self.text_to_instance(source_sequence, target_sequence) 69 | 70 | @staticmethod 71 | def _tokens_to_ids(tokens: List[Token]) -> List[int]: 72 | ids: Dict[str, int] = {} 73 | out: List[int] = [] 74 | for token in tokens: 75 | out.append(ids.setdefault(token.text.lower(), len(ids))) 76 | return out 77 | 78 | @overrides 79 | def text_to_instance(self, source_string: str, target_string: str = None) -> Instance: # type: ignore 80 | """ 81 | Turn raw source string and target string into an ``Instance``. 82 | 83 | Parameters 84 | ---------- 85 | source_string : ``str``, required 86 | target_string : ``str``, optional (default = None) 87 | 88 | Returns 89 | ------- 90 | Instance 91 | See the above for a description of the fields that the instance will contain. 92 | """ 93 | # pylint: disable=arguments-differ 94 | if self.lowercase_tokens: 95 | source_string = source_string.lower() 96 | target_string = target_string.lower() 97 | tokenized_source = self._tokenizer.tokenize(source_string) 98 | source_field = SourceTextField(tokenized_source, self._token_indexers) 99 | 100 | meta_fields = {"source_tokens": [x.text for x in tokenized_source]} 101 | fields_dict = { 102 | "source_tokens": source_field, 103 | } 104 | 105 | if target_string is not None: 106 | tokenized_target = self._tokenizer.tokenize(target_string) 107 | meta_fields["target_tokens"] = [x.text for x in tokenized_target] 108 | tokenized_target.insert(0, Token(START_SYMBOL)) 109 | tokenized_target.append(Token(END_SYMBOL)) 110 | target_field = TargetTextField(tokenized_target, self._token_indexers) 111 | fields_dict["target_tokens"] = target_field 112 | 113 | fields_dict["meta"] = MetadataField(meta_fields) 114 | 115 | return SyncedFieldsInstance(fields_dict) 116 | 117 | 118 | -------------------------------------------------------------------------------- /pointergen/custom_instance.py: -------------------------------------------------------------------------------- 1 | from allennlp.data import Instance 2 | from overrides import overrides 3 | from allennlp.data import Vocabulary 4 | from pointergen.fields import SourceTextField, TargetTextField 5 | 6 | class SyncedFieldsInstance(Instance): 7 | def __init__(self, *args, **kwargs): 8 | super().__init__(*args, **kwargs) 9 | 10 | @overrides 11 | def index_fields(self, vocab: Vocabulary) -> None: 12 | """ 13 | Indexes all fields in this ``Instance`` using the provided ``Vocabulary``. 14 | This `mutates` the current object, it does not return a new ``Instance``. 15 | A ``DataIterator`` will call this on each pass through a dataset; we use the ``indexed`` 16 | flag to make sure that indexing only happens once. 17 | 18 | This means that if for some reason you modify your vocabulary after you've 19 | indexed your instances, you might get unexpected behavior. 20 | """ 21 | if not self.indexed: 22 | self.indexed = True 23 | all_fields = self.fields.values() 24 | source_fields = list(filter(lambda x:type(x)==SourceTextField, all_fields)) 25 | target_fields = list(filter(lambda x:type(x)==TargetTextField, all_fields)) 26 | 27 | assert (len(source_fields)==1), "There should be exactly one source fields because otherwise OOV indices would clash" 28 | for field in self.fields.values(): 29 | if type(field) not in [SourceTextField, TargetTextField]: 30 | field.index(vocab) 31 | 32 | source_field = source_fields[0] 33 | oov_list = source_field.index(vocab) 34 | self.oov_list = oov_list 35 | 36 | for target_field in target_fields: 37 | target_field.index(vocab, oov_list) 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /pointergen/fields.py: -------------------------------------------------------------------------------- 1 | from allennlp.data.fields import TextField 2 | from allennlp.data import Token, TokenIndexer 3 | from overrides import overrides 4 | from allennlp.data import Vocabulary 5 | from allennlp.data.token_indexers.token_indexer import TokenIndexer, TokenType 6 | from allennlp.data.token_indexers import SingleIdTokenIndexer 7 | from copy import copy 8 | 9 | from typing import List, Dict 10 | TokenList = List[TokenType] 11 | 12 | 13 | class SourceTextField(TextField): 14 | def __init__(self, tokens: List[Token], token_indexers: Dict[str, TokenIndexer]) -> None: 15 | assert(len(token_indexers)==1), "Only one indexer is allowed in a SourceTextField" 16 | super().__init__(tokens, token_indexers) 17 | 18 | @overrides 19 | def index(self, vocab: Vocabulary): 20 | pass 21 | 22 | def index(self, vocab: Vocabulary) -> List[str]: 23 | token_arrays: Dict[str, TokenList] = {} 24 | indexer_name_to_indexed_token: Dict[str, List[str]] = {} 25 | token_index_to_indexer_name: Dict[str, str] = {} 26 | 27 | for indexer_name, indexer in self._token_indexers.items(): 28 | assert type(indexer)==SingleIdTokenIndexer, "The indexer must be a singleidtokenindexer" 29 | token_indices = indexer.tokens_to_indices(self.tokens, vocab, indexer_name) 30 | 31 | oovs_list : List[str] = [] 32 | for key, val in token_indices.items(): 33 | #key is string, val is array of ints 34 | oov_id = vocab._token_to_index[indexer.namespace][vocab._oov_token] 35 | 36 | ids_with_unks : List[int] = val 37 | ids_with_oovs : List[int] = [] 38 | 39 | for _id, word in zip(ids_with_unks, self.tokens): 40 | if _id == oov_id: 41 | if word.text not in oovs_list: 42 | oovs_list.append(word.text) 43 | ids_with_oovs.append(vocab.get_vocab_size(indexer.namespace) + oovs_list.index(word.text)) 44 | else: 45 | ids_with_oovs.append(_id) 46 | 47 | token_arrays.update({ 48 | "ids_with_unks": ids_with_unks, 49 | "ids_with_oovs": ids_with_oovs, 50 | "num_oovs": [len(oovs_list)] 51 | }) 52 | indexer_name_to_indexed_token[indexer_name] = ["ids_with_unks", "ids_with_oovs", "num_oovs"] 53 | token_index_to_indexer_name["ids_with_unks"] = indexer_name 54 | token_index_to_indexer_name["ids_with_oovs"] = indexer_name 55 | token_index_to_indexer_name["num_oovs"] = indexer_name 56 | 57 | 58 | self._indexed_tokens = token_arrays 59 | self._indexer_name_to_indexed_token = indexer_name_to_indexed_token 60 | self._token_index_to_indexer_name = token_index_to_indexer_name 61 | self._oovs = oovs_list 62 | 63 | return self._oovs 64 | 65 | class TargetTextField(TextField): 66 | def __init__(self, tokens: List[Token], token_indexers: Dict[str, TokenIndexer]) -> None: 67 | super().__init__(tokens, token_indexers) 68 | 69 | @overrides 70 | def index(self, vocab: Vocabulary, oovs_list: TokenList): 71 | token_arrays: Dict[str, TokenList] = {} 72 | indexer_name_to_indexed_token: Dict[str, List[str]] = {} 73 | token_index_to_indexer_name: Dict[str, str] = {} 74 | for indexer_name, indexer in self._token_indexers.items(): 75 | assert type(indexer)==SingleIdTokenIndexer, "The indexer must be a singleidtokenindexer" 76 | token_indices = indexer.tokens_to_indices(self.tokens, vocab, indexer_name) 77 | 78 | for key, val in token_indices.items(): 79 | oov_id = vocab._token_to_index[indexer.namespace][vocab._oov_token] 80 | 81 | ids_with_unks : List[int] = val 82 | ids_with_oovs : List[int] = [] 83 | 84 | for _id, word in zip(ids_with_unks, self.tokens): 85 | if _id == oov_id: 86 | if word.text not in oovs_list: 87 | ids_with_oovs.append(_id) # let it be the vocab id for OOV 88 | else: 89 | ids_with_oovs.append(vocab.get_vocab_size(indexer.namespace) + oovs_list.index(word.text)) 90 | else: 91 | ids_with_oovs.append(_id) 92 | 93 | token_arrays.update({ 94 | "ids_with_unks": ids_with_unks, 95 | "ids_with_oovs": ids_with_oovs 96 | }) 97 | 98 | indexer_name_to_indexed_token[indexer_name] = ["ids_with_unks", "ids_with_oovs"] 99 | token_index_to_indexer_name["ids_with_unks"] = indexer_name 100 | token_index_to_indexer_name["ids_with_oovs"] = indexer_name 101 | 102 | self._indexed_tokens = token_arrays 103 | self._indexer_name_to_indexed_token = indexer_name_to_indexed_token 104 | self._token_index_to_indexer_name = token_index_to_indexer_name 105 | self._oovs = oovs_list 106 | -------------------------------------------------------------------------------- /pointergen/model.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import numpy as np 4 | import sys 5 | 6 | from torch.autograd import Variable 7 | 8 | import math 9 | 10 | import torch.nn.functional as F 11 | 12 | from tensorboardX import SummaryWriter 13 | 14 | from nltk.translate.bleu_score import corpus_bleu, sentence_bleu 15 | from tqdm import tqdm_notebook 16 | 17 | from allennlp.models import Model 18 | 19 | from torch.nn.utils import clip_grad_norm_ 20 | from allennlp.models.model import Model 21 | from pointergen.custom_instance import SyncedFieldsInstance 22 | from typing import Dict 23 | from overrides import overrides 24 | from allennlp.data.dataset import Batch 25 | from allennlp.nn import util 26 | from allennlp.common.util import START_SYMBOL, END_SYMBOL 27 | from allennlp.training.metrics import CategoricalAccuracy 28 | 29 | EPS=1e-8 30 | 31 | 32 | 33 | def add_with_expansion(A, B): 34 | '''A and B must be of single dimension''' 35 | assert A.ndim==1 and B.ndim==1 36 | shape_diff = np.array(B.shape) - np.array(A.shape) 37 | shape_diff = np.clip(shape_diff, a_min=0, a_max=np.inf).astype(np.int32) 38 | padded_A=np.lib.pad(A, ((0,shape_diff[0]),), 'constant', constant_values=(0)) 39 | 40 | shape_diff = np.array(A.shape) - np.array(B.shape) 41 | shape_diff = np.clip(shape_diff, a_min=0, a_max=np.inf).astype(np.int32) 42 | padded_B=np.lib.pad(B, ((0,shape_diff[0]),), 'constant', constant_values=(0)) 43 | 44 | return padded_A+padded_B 45 | 46 | 47 | def uniform_tensor(shape, a, b): 48 | output = torch.FloatTensor(*shape).uniform_(a, b) 49 | return output 50 | 51 | class Attention(nn.Module): 52 | def __init__(self, total_encoder_hidden_size, total_decoder_hidden_size, attn_vec_size): 53 | super(Attention, self).__init__() 54 | self.total_encoder_hidden_size=total_encoder_hidden_size 55 | self.total_decoder_hidden_size=total_decoder_hidden_size 56 | self.attn_vec_size=attn_vec_size 57 | 58 | self.Wh_layer=nn.Linear(total_encoder_hidden_size, attn_vec_size, bias=False) 59 | self.Ws_layer=nn.Linear(total_decoder_hidden_size, attn_vec_size, bias=True) 60 | self.selector_vector_layer=nn.Linear(attn_vec_size, 1, bias=False) # called 'v' in see et al 61 | 62 | 63 | def forward(self, encoded_seq, decoder_state, input_pad_mask): 64 | ''' 65 | encoded seq is batchsizexenc_seqlenxtotal_encoder_hidden_size 66 | decoder_state is batchsizexdec_seqlenxtotal_decoder_hidden_size 67 | ''' 68 | 69 | projected_decstates = self.Ws_layer(decoder_state) 70 | projected_encstates = self.Wh_layer(encoded_seq) 71 | 72 | added_projections=projected_decstates.unsqueeze(2)+projected_encstates.unsqueeze(1) #batchsizeXdeclenXenclenXattnvecsize 73 | added_projections=torch.tanh(added_projections) 74 | 75 | attn_logits=self.selector_vector_layer(added_projections) 76 | attn_logits=attn_logits.squeeze(3) 77 | 78 | attn_weights = torch.softmax(attn_logits, dim=-1) # shape=batchXdec_lenXenc_len 79 | attn_weights2 = attn_weights*input_pad_mask.unsqueeze(1) 80 | attn_weights_renormalized = attn_weights2/torch.sum(attn_weights2, dim=-1, keepdim=True) # shape=batchx1x1 # TODO - why is there a division without EPS ? 81 | 82 | context_vector = torch.sum(encoded_seq.unsqueeze(1)*attn_weights_renormalized.unsqueeze(-1) , dim=-2) 83 | # shape batchXdec_seqlenXhiddensize 84 | 85 | return context_vector, attn_weights_renormalized 86 | 87 | 88 | 89 | 90 | class CopyMechanism(nn.Module): 91 | def __init__( 92 | self, encoder_hidden_size, decoder_hidden_size, decoder_input_size): 93 | super(CopyMechanism, self).__init__() 94 | self.pgen=nn.Sequential( 95 | nn.Linear(encoder_hidden_size+2*decoder_hidden_size+decoder_input_size, 1), 96 | nn.Sigmoid() 97 | ) 98 | self.output_probs=nn.Softmax(dim=-1) 99 | 100 | def forward( 101 | self, output_logits, attn_weights, decoder_hidden_state, decoder_input, 102 | context_vector, encoder_input, max_oovs): 103 | '''output_logits = batchXseqlenXoutvocab 104 | attn_weights = batchXseqlenXenc_len 105 | decoder_hidden_state = batchXseqlenXdecoder_hidden_size 106 | context_vector = batchXseqlenXencoder_hidden_dim 107 | encoder_input = batchxenc_len''' 108 | output_probabilities=self.output_probs(output_logits) 109 | 110 | batch_size = output_probabilities.size(0) 111 | output_len = output_probabilities.size(1) 112 | append_for_copy = torch.zeros((batch_size, output_len, max_oovs)).cuda() 113 | output_probabilities=torch.cat([output_probabilities, append_for_copy], dim=-1) 114 | 115 | pre_pgen_tensor=torch.cat([context_vector, decoder_hidden_state, decoder_input], dim=-1) 116 | pgen=self.pgen(pre_pgen_tensor) # batchsizeXseqlenX1 117 | pcopy=1.0-pgen 118 | 119 | encoder_input=encoder_input.unsqueeze(1).expand(-1, output_len , -1) # batchXseqlenXenc_len 120 | 121 | # Note that padding words donot get any attention because the attention is a masked attention 122 | 123 | copy_probabilities=torch.zeros_like(output_probabilities) # batchXseqlenXoutvocab 124 | copy_probabilities.scatter_add_(2, encoder_input, attn_weights) 125 | 126 | total_probabilities=pgen*output_probabilities+pcopy*copy_probabilities 127 | return total_probabilities, pgen # batchXseqlenXoutvocab , batchsizeXseqlenX1 128 | 129 | @Model.register("pointer_generator") 130 | class Seq2Seq(Model): 131 | def __init__(self, vocab, hidden_size=256, emb_size=128, num_encoder_layers=1, num_decoder_layers=1, use_copy_mech=True): 132 | super().__init__(vocab) 133 | 134 | ## vocab related setup begins 135 | assert "tokens" in vocab._token_to_index and len(vocab._token_to_index.keys())==1, "Vocabulary must have tokens as the only namespace" 136 | self.vocab_size=vocab.get_vocab_size() 137 | self.PAD_ID = vocab.get_token_index(vocab._padding_token) 138 | self.OOV_ID = vocab.get_token_index(vocab._oov_token) 139 | self.START_ID = vocab.get_token_index(START_SYMBOL) 140 | self.END_ID = vocab.get_token_index(END_SYMBOL) 141 | ## vocab related setup ends 142 | 143 | self.emb_size=emb_size 144 | self.hidden_size=hidden_size 145 | self.num_encoder_layers=num_encoder_layers 146 | self.num_decoder_layers=num_decoder_layers 147 | self.crossentropy=nn.CrossEntropyLoss() 148 | 149 | self.metrics = { 150 | "accuracy" : CategoricalAccuracy(), 151 | } 152 | 153 | self.register_buffer("true_rep", torch.tensor(1.0)) 154 | self.register_buffer("false_rep", torch.tensor(0.0)) 155 | 156 | self.pre_output_dim=hidden_size 157 | 158 | self.use_copy_mech=use_copy_mech 159 | 160 | self.output_embedder = nn.Sequential( 161 | nn.Embedding(num_embeddings=self.vocab_size, embedding_dim=self.emb_size) 162 | ) 163 | 164 | self.input_encoder = nn.Sequential( 165 | self.output_embedder, 166 | torch.nn.LSTM(input_size=self.emb_size, hidden_size=self.hidden_size, num_layers=self.num_encoder_layers, batch_first=True, bidirectional=True), 167 | ) 168 | 169 | self.fuse_h_layer= nn.Sequential( 170 | nn.Linear(2*hidden_size, hidden_size), 171 | nn.ReLU() 172 | ) 173 | 174 | self.fuse_c_layer= nn.Sequential( 175 | nn.Linear(2*hidden_size, hidden_size), 176 | nn.ReLU() 177 | ) 178 | 179 | self.attention_layer=Attention(2*hidden_size, 2*hidden_size, 2*hidden_size) 180 | 181 | if self.use_copy_mech: 182 | self.copymech=CopyMechanism(2*self.hidden_size, self.hidden_size, self.emb_size) 183 | 184 | self.decoder_rnn=torch.nn.LSTM(input_size=self.emb_size, hidden_size=self.hidden_size, num_layers=self.num_decoder_layers, batch_first=False, bidirectional=False) 185 | 186 | self.statenctx_to_prefinal = nn.Linear(3*hidden_size, hidden_size, bias=True) 187 | self.project_to_decoder_input = nn.Linear(emb_size+2*hidden_size, emb_size, bias=True) 188 | 189 | self.output_projector = torch.nn.Conv1d(self.pre_output_dim, self.vocab_size, kernel_size=1, bias=True) 190 | self.softmax = nn.Softmax(dim=-1) 191 | 192 | 193 | def forward(self, source_tokens, target_tokens, meta=None, only_predict_probs=False, return_pgen=False): 194 | inp_with_unks = source_tokens["ids_with_unks"] 195 | inp_with_oovs = source_tokens["ids_with_oovs"] 196 | max_oovs = int(torch.max(source_tokens["num_oovs"])) 197 | 198 | feed_tensor = target_tokens["ids_with_unks"][:, :-1] 199 | if self.use_copy_mech: 200 | target_tensor = target_tokens["ids_with_oovs"][:,1:] 201 | else: 202 | target_tensor = target_tokens["ids_with_unks"][:, 1:] 203 | 204 | 205 | batch_size = inp_with_unks.size(0) 206 | # preparing intial state for feeding into decoder. layers of decoder after first one get zeros as initial state 207 | inp_enc_seq, (last_h_value, last_c_value) = self.encode(inp_with_unks) 208 | 209 | 210 | # inp_enc_seq is batchsizeXseqlenX2*hiddensize 211 | h_value = self.pad_zeros_to_init_state(last_h_value) 212 | c_value = self.pad_zeros_to_init_state(last_c_value) 213 | state_from_inp = (h_value, c_value) 214 | 215 | input_pad_mask=torch.where(inp_with_unks!=0, self.true_rep, self.false_rep) 216 | 217 | output_embedded = self.output_embedder(feed_tensor) 218 | seqlen_first = output_embedded.permute(1,0,2) 219 | output_seq_len = seqlen_first.size(0) 220 | 221 | #initial values 222 | decoder_hidden_state=state_from_inp 223 | 224 | decoder_hstates_batchfirst = state_from_inp[0].permute(1, 0, 2) 225 | decoder_cstates_batchfirst = state_from_inp[1].permute(1, 0, 2) 226 | concatenated_decoder_states = torch.cat([decoder_cstates_batchfirst, decoder_hstates_batchfirst], dim=-1) 227 | context_vector, _ = self.attention_layer(inp_enc_seq, concatenated_decoder_states, input_pad_mask) 228 | # 229 | 230 | output_probs=[] 231 | pgens=[] 232 | 233 | for _i in range(output_seq_len): 234 | seqlen_first_onetimestep = seqlen_first[_i:_i+1] # shape is 1xbatchsizexembsize 235 | context_vector_seqlenfirst = context_vector.permute(1,0,2) # seqlen is 1 always 236 | pre_input_to_decoder=torch.cat([seqlen_first_onetimestep, context_vector_seqlenfirst], dim=-1) 237 | input_to_decoder=self.project_to_decoder_input(pre_input_to_decoder) # shape is 1xbatchsizexembsize 238 | 239 | decoder_h_values, decoder_hidden_state = self.decoder_rnn(input_to_decoder, decoder_hidden_state) 240 | # decoder_h_values is shape 1XbatchsizeXhiddensize 241 | 242 | decoder_h_values_batchfirst = decoder_h_values.permute(1,0,2) 243 | 244 | decoder_hstates_batchfirst = decoder_hidden_state[0].permute(1, 0, 2) 245 | decoder_cstates_batchfirst = decoder_hidden_state[1].permute(1, 0, 2) 246 | concatenated_decoder_states = torch.cat([decoder_cstates_batchfirst, decoder_hstates_batchfirst], dim=-1) 247 | 248 | context_vector, attn_weights = self.attention_layer(inp_enc_seq, concatenated_decoder_states, input_pad_mask) 249 | 250 | decstate_and_context=torch.cat([decoder_h_values_batchfirst, context_vector], dim=-1) #batchsizeXdec_seqlenX3*hidden_size 251 | prefinal_tensor = self.statenctx_to_prefinal(decstate_and_context) 252 | seqlen_last = prefinal_tensor.permute(0,2,1) #batchsizeXpre_output_dimXdec_seqlen 253 | logits = self.output_projector(seqlen_last) 254 | logits = logits.permute(0,2,1) # batchXdec_seqlenXvocab 255 | 256 | # now executing copymechanism 257 | if self.use_copy_mech: 258 | probs_after_copying, pgen = self.copymech(logits, attn_weights, concatenated_decoder_states, input_to_decoder.permute(1,0,2), context_vector, inp_with_oovs, max_oovs) 259 | pgens.append(pgen) 260 | output_probs.append(probs_after_copying) 261 | else: 262 | output_probs.append(self.softmax(logits)) 263 | 264 | 265 | # now calculating loss and numpreds 266 | '''outprobs is list of batchX1xvocabsize 267 | target_tensor is batchXseqlen''' 268 | targets_tensor_seqfirst = target_tensor.permute(1,0) 269 | pad_mask=torch.where(targets_tensor_seqfirst!=self.PAD_ID, self.true_rep, self.false_rep) 270 | # TODO: SHOULD WE SET REQUIRES_GRAD=FALSE FOR PAD_MASK? 271 | 272 | loss=0.0 273 | numpreds=0 274 | total_pgen=0 275 | 276 | total_pgen_placewise=torch.zeros((output_seq_len)).cuda() 277 | numpreds_placewise=torch.zeros((output_seq_len)).cuda() 278 | 279 | if return_pgen and not self.use_copy_mech: 280 | print("Cannot return pgen when copy mechanism is switched off") 281 | assert False 282 | 283 | for _i in range(len(output_probs)): 284 | predicted_probs = output_probs[_i].squeeze(1) 285 | true_labels = targets_tensor_seqfirst[_i] 286 | mask_labels = pad_mask[_i] 287 | selected_probs=torch.gather(input=predicted_probs, dim=1, index=true_labels.unsqueeze(1)) 288 | selected_probs=selected_probs.squeeze(1) 289 | selected_neg_logprobs=-1*torch.log(selected_probs) 290 | loss+=torch.sum(selected_neg_logprobs*mask_labels) 291 | 292 | this_numpreds=torch.sum(mask_labels).detach() 293 | numpreds+=this_numpreds 294 | 295 | for metric in self.metrics.values(): 296 | metric(predicted_probs, true_labels, mask_labels) 297 | 298 | if return_pgen: 299 | pgen=pgens[_i].squeeze(1).squeeze(1) 300 | total_pgen+=torch.sum(pgen*mask_labels) 301 | 302 | total_pgen_placewise[_i]+=torch.sum(pgen*mask_labels).detach() 303 | numpreds_placewise[_i]+=this_numpreds 304 | 305 | 306 | if return_pgen: 307 | return { 308 | "loss": loss/numpreds, 309 | "total_pgen": total_pgen, 310 | "numpreds_placewise": numpreds_placewise, 311 | "total_pgen_placewise": total_pgen_placewise 312 | } 313 | else: 314 | return { 315 | "loss": loss/numpreds 316 | } 317 | 318 | 319 | def pad_zeros_to_init_state(self, h_value): 320 | '''can also be c_value''' 321 | assert(h_value.size(0)==1) # h_value should only be of last layer of lstm 322 | return torch.cat([h_value]+[torch.zeros_like(h_value) for _i in range(self.num_encoder_layers-1)], dim=0) 323 | 324 | 325 | def encode(self, inp): 326 | '''Get the encoding of input''' 327 | batch_size = inp.size(0) 328 | inp_seq_len = inp.size(1) 329 | inp_encoded = self.input_encoder(inp) 330 | output_seq=inp_encoded[0] 331 | h_value, c_value = inp_encoded[1] 332 | 333 | h_value_layerwise=h_value.reshape(self.num_encoder_layers, 2, batch_size, self.hidden_size) # numlayersXbidirecXbatchXhid 334 | c_value_layerwise=c_value.reshape(self.num_encoder_layers, 2, batch_size, self.hidden_size) # numlayersXbidirecXbatchXhid 335 | 336 | last_layer_h=h_value_layerwise[-1:,:,:,:] 337 | last_layer_c=c_value_layerwise[-1:,:,:,:] 338 | 339 | last_layer_h=last_layer_h.permute(0,2,1,3).contiguous().view(1, batch_size, 2*self.hidden_size) 340 | last_layer_c=last_layer_c.permute(0,2,1,3).contiguous().view(1, batch_size, 2*self.hidden_size) 341 | 342 | last_layer_h_fused=self.fuse_h_layer(last_layer_h) 343 | last_layer_c_fused=self.fuse_c_layer(last_layer_c) 344 | 345 | return output_seq, (last_layer_h_fused, last_layer_c_fused) 346 | 347 | 348 | def decode_onestep(self, past_outp_input, past_state_tuple, past_context_vector, inp_enc_seq, inp_with_oovs, input_pad_mask, max_oovs): 349 | '''run one step of decoder. outp_input is batchsizex1 350 | past_context_vector is batchsizeX1Xtwice_of_hiddensize''' 351 | outp_embedded = self.output_embedder(past_outp_input) 352 | tok_seqlen_first = outp_embedded.permute(1,0,2) 353 | assert(tok_seqlen_first.size(0)==1) # only one timestep allowed 354 | 355 | context_vector_seqlenfirst = past_context_vector.permute(1,0,2) # seqlen is 1 always 356 | pre_input_to_decoder=torch.cat([tok_seqlen_first, context_vector_seqlenfirst], dim=-1) 357 | input_to_decoder=self.project_to_decoder_input(pre_input_to_decoder) # shape is 1xbatchsizexembsize 358 | 359 | 360 | decoder_h_values, decoder_hidden_state = self.decoder_rnn(input_to_decoder, past_state_tuple) 361 | # decoder_h_values is shape 1XbatchsizeXhiddensize 362 | decoder_h_values_batchfirst = decoder_h_values.permute(1,0,2) 363 | 364 | decoder_hstates_batchfirst = decoder_hidden_state[0].permute(1, 0, 2) 365 | decoder_cstates_batchfirst = decoder_hidden_state[1].permute(1, 0, 2) 366 | concatenated_decoder_states = torch.cat([decoder_cstates_batchfirst, decoder_hstates_batchfirst], dim=-1) 367 | 368 | context_vector, attn_weights = self.attention_layer(inp_enc_seq, concatenated_decoder_states, input_pad_mask) 369 | 370 | decstate_and_context=torch.cat([decoder_h_values_batchfirst, context_vector], dim=-1) #batchsizeXdec_seqlenX3*hidden_size 371 | prefinal_tensor = self.statenctx_to_prefinal(decstate_and_context) 372 | seqlen_last = prefinal_tensor.permute(0,2,1) #batchsizeXpre_output_dimXdec_seqlen 373 | logits = self.output_projector(seqlen_last) 374 | logits = logits.permute(0,2,1) # batchXdec_seqlenXvocab 375 | 376 | # now executing copymechanism 377 | if self.use_copy_mech: 378 | probs_after_copying, _ = self.copymech(logits, attn_weights, concatenated_decoder_states, input_to_decoder.permute(1,0,2), context_vector, inp_with_oovs, max_oovs) 379 | prob_to_return = probs_after_copying[0].squeeze(1) 380 | else: 381 | prob_to_return = self.softmax(logits).squeeze(1) 382 | 383 | 384 | return prob_to_return, decoder_hidden_state, context_vector 385 | 386 | 387 | 388 | def get_initial_state(self, start_ids, initial_decode_state): 389 | '''start_ids is tensor of size batchsizeXseqlen''' 390 | outp_embedded = self.output_embedder(start_ids) 391 | seqlen_first = outp_embedded.permute(1,0,2) 392 | feed=seqlen_first 393 | seqlen=feed.size(0) 394 | h_value, c_value = initial_decode_state 395 | for idx in range(seqlen): 396 | _ , (h_value, c_value) = self.decoder_rnn(feed[idx:idx+1], (h_value, c_value)) 397 | 398 | return (h_value, c_value) 399 | 400 | 401 | @overrides 402 | def forward_on_instance(self, instance: SyncedFieldsInstance) -> Dict[str, str]: 403 | """ 404 | Takes an :class:`~allennlp.data.instance.Instance`, which typically has raw text in it, 405 | converts that text into arrays using this model's :class:`Vocabulary`, passes those arrays 406 | through :func:`self.forward()` and :func:`self.decode()` (which by default does nothing) 407 | and returns the result. Before returning the result, we convert any 408 | ``torch.Tensors`` into numpy arrays and remove the batch dimension. 409 | """ 410 | cuda_device = self._get_prediction_device() 411 | dataset = Batch([instance]) 412 | dataset.index_instances(self.vocab) 413 | 414 | gt_has_oov = False 415 | dataset_tensor_dict = dataset.as_tensor_dict() 416 | if self.OOV_ID in dataset_tensor_dict["target_tokens"]["ids_with_unks"]: 417 | gt_has_oov = True 418 | 419 | model_input = util.move_to_device(dataset.as_tensor_dict(), cuda_device) 420 | output_ids = self.beam_search_decode(**model_input) 421 | 422 | output_words = [] 423 | for _id in output_ids: 424 | if _id Dict[str, float]: 438 | metrics_to_return = { 439 | metric_name: metric.get_metric(reset) for metric_name, metric in self.metrics.items() 440 | } 441 | return metrics_to_return 442 | 443 | 444 | def beam_search_decode(self, source_tokens, target_tokens=None, meta=None, beam_width=4, min_length=35, max_length=120): 445 | inp_with_unks = source_tokens["ids_with_unks"] 446 | inp_with_oovs = source_tokens["ids_with_oovs"] 447 | max_oovs = int(torch.max(source_tokens["num_oovs"])) 448 | input_pad_mask=torch.where(inp_with_unks!=self.PAD_ID, self.true_rep, self.false_rep) 449 | inp_enc_seq, (intial_h_value, intial_c_value) = self.encode(inp_with_unks) 450 | h_value = self.pad_zeros_to_init_state(intial_h_value) 451 | c_value = self.pad_zeros_to_init_state(intial_c_value) 452 | source_encoding=(h_value, c_value) 453 | 454 | # the first context vector is calculated by using the first lstm decoder state 455 | first_decoder_hstates_batchfirst = source_encoding[0].permute(1, 0, 2) 456 | first_decoder_cstates_batchfirst = source_encoding[1].permute(1, 0, 2) 457 | first_concatenated_decoder_states = torch.cat([first_decoder_cstates_batchfirst, first_decoder_hstates_batchfirst], dim=-1) 458 | first_context_vector, _ = self.attention_layer(inp_enc_seq, first_concatenated_decoder_states, input_pad_mask) 459 | 460 | hypotheses = [ {"dec_state" : source_encoding, 461 | "past_context_vector" : first_context_vector, 462 | "logprobs" : [0.0], 463 | "out_words" : [self.START_ID] 464 | } ] 465 | 466 | finished_hypotheses = [] 467 | 468 | def sort_hyps(list_of_hyps): 469 | return sorted(list_of_hyps, key=lambda x:sum(x["logprobs"])/len(x["logprobs"]), reverse=True) 470 | 471 | counter=0 472 | while counter=self.vocab_size: # this guy is an OOV 479 | in_tok=self.OOV_ID 480 | old_dec_state=hyp["dec_state"] 481 | past_context_vector=hyp["past_context_vector"] 482 | old_logprobs=hyp["logprobs"] 483 | new_probs, new_dec_state, new_context_vector = self.decode_onestep( torch.tensor([[in_tok]]).cuda(), old_dec_state, past_context_vector, inp_enc_seq, inp_with_oovs, input_pad_mask, max_oovs) 484 | 485 | probs, indices = torch.topk(new_probs[0], dim=0, k=2*beam_width) 486 | for p, idx in zip(probs, indices): 487 | new_dict = {"dec_state" : new_dec_state, 488 | "past_context_vector" : new_context_vector, 489 | "logprobs" : old_logprobs+[float(torch.log(p).detach().cpu().numpy())], 490 | "out_words" : old_out_words+[idx.item()] 491 | } 492 | new_hypotheses.append(new_dict) 493 | 494 | # time to pick the best of new hypotheses 495 | sorted_new_hypotheses = sort_hyps(new_hypotheses) 496 | hypotheses=[] 497 | for hyp in sorted_new_hypotheses: 498 | if hyp["out_words"][-1]==self.END_ID: 499 | if len(hyp["out_words"])>min_length+1: 500 | finished_hypotheses.append(hyp) 501 | else: 502 | hypotheses.append(hyp) 503 | if len(hypotheses) == beam_width or len(finished_hypotheses) == beam_width: 504 | break 505 | 506 | 507 | if len(finished_hypotheses)>0: 508 | final_candidates = finished_hypotheses 509 | else: 510 | final_candidates = hypotheses 511 | 512 | sorted_final_candidates = sort_hyps(final_candidates) 513 | best_candidate = sorted_final_candidates[0] 514 | 515 | return best_candidate["out_words"] #, best_candidate["log_likelihood"] 516 | 517 | 518 | -------------------------------------------------------------------------------- /pointergen/model_withcoverage.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import numpy as np 4 | import sys 5 | 6 | from torch.autograd import Variable 7 | 8 | import math 9 | 10 | import torch.nn.functional as F 11 | 12 | from tensorboardX import SummaryWriter 13 | 14 | from nltk.translate.bleu_score import corpus_bleu, sentence_bleu 15 | from tqdm import tqdm_notebook 16 | 17 | from allennlp.models import Model 18 | 19 | import torch 20 | 21 | from torch.nn.utils import clip_grad_norm_ 22 | from allennlp.models.model import Model 23 | from pointergen.custom_instance import SyncedFieldsInstance 24 | from typing import Dict 25 | from overrides import overrides 26 | from allennlp.data.dataset import Batch 27 | from allennlp.nn import util 28 | from allennlp.common.util import START_SYMBOL, END_SYMBOL 29 | from allennlp.training.metrics import CategoricalAccuracy, Average 30 | 31 | from distutils.util import strtobool 32 | 33 | import pdb 34 | 35 | # torch.autograd.set_detect_anomaly(True) 36 | 37 | 38 | EPS=1e-8 39 | 40 | 41 | 42 | 43 | def get_yes_no(message): 44 | while True: 45 | try: 46 | x=input(message) 47 | return strtobool(x) 48 | except ValueError: 49 | continue 50 | 51 | 52 | def add_with_expansion(A, B): 53 | '''A and B must be of single dimension''' 54 | assert A.ndim==1 and B.ndim==1 55 | shape_diff = np.array(B.shape) - np.array(A.shape) 56 | shape_diff = np.clip(shape_diff, a_min=0, a_max=np.inf).astype(np.int32) 57 | padded_A=np.lib.pad(A, ((0,shape_diff[0]),), 'constant', constant_values=(0)) 58 | 59 | shape_diff = np.array(A.shape) - np.array(B.shape) 60 | shape_diff = np.clip(shape_diff, a_min=0, a_max=np.inf).astype(np.int32) 61 | padded_B=np.lib.pad(B, ((0,shape_diff[0]),), 'constant', constant_values=(0)) 62 | 63 | return padded_A+padded_B 64 | 65 | 66 | def uniform_tensor(shape, a, b): 67 | output = torch.FloatTensor(*shape).uniform_(a, b) 68 | return output 69 | 70 | class Attention(nn.Module): 71 | def __init__(self, total_encoder_hidden_size, total_decoder_hidden_size, attn_vec_size): 72 | super(Attention, self).__init__() 73 | self.total_encoder_hidden_size=total_encoder_hidden_size 74 | self.total_decoder_hidden_size=total_decoder_hidden_size 75 | self.attn_vec_size=attn_vec_size 76 | 77 | # Wh_var=Variable(torch.zeros(total_encoder_hidden_size,attn_vec_size), requires_grad=True, name="wh_attn_matrix") 78 | # torch.nn.init.xavier_uniform_(Wh_var) 79 | # self.Wh=torch.nn.Parameter(Wh_var, requires_grad=True) 80 | 81 | self.Wh_layer=nn.Linear(total_encoder_hidden_size, attn_vec_size, bias=False) 82 | self.Ws_layer=nn.Linear(total_decoder_hidden_size, attn_vec_size, bias=True) 83 | self.selector_vector_layer=nn.Linear(attn_vec_size, 1, bias=False) # called 'v' in see et al 84 | 85 | self.Wc_layer=nn.Linear(1, attn_vec_size, bias=False) 86 | torch.nn.init.zeros_(self.Wc_layer.weight) 87 | 88 | # stdv = 1.0 / math.sqrt(self.hidden_size) 89 | # intial_attention=uniform_tensor((self.hidden_size, self.attn_vec_size), -stdv, stdv).cuda() 90 | 91 | def forward(self, encoded_seq, decoder_state, input_pad_mask, coverage=None): 92 | ''' 93 | encoded seq is batchsizexenc_seqlenxtotal_encoder_hidden_size 94 | decoder_state is batchsizexdec_seqlenxtotal_decoder_hidden_size 95 | coverage = batchsizexdec_seqlenxenc_seqlen 96 | ''' 97 | 98 | projected_decstates = self.Ws_layer(decoder_state) 99 | projected_encstates = self.Wh_layer(encoded_seq) 100 | added_projections=projected_decstates.unsqueeze(2)+projected_encstates.unsqueeze(1) #batchsizeXdeclenXenclenXattnvecsize 101 | 102 | if coverage is not None: 103 | projected_coverage = self.Wc_layer(coverage.unsqueeze(-1)) # shape = batchsize X dec_seqlen x enc_seqlen X attn_vec_size 104 | added_projections += projected_coverage 105 | 106 | added_projections=torch.tanh(added_projections) 107 | 108 | attn_logits=self.selector_vector_layer(added_projections) 109 | attn_logits=attn_logits.squeeze(3) 110 | 111 | attn_weights = torch.softmax(attn_logits, dim=-1) # shape=batchXdec_lenXenc_len 112 | attn_weights2 = attn_weights*input_pad_mask.unsqueeze(1) 113 | attn_weights_renormalized = attn_weights2/torch.sum(attn_weights2, dim=-1, keepdim=True) # shape=batchx1x1 # TODO - why is there a division without EPS ? 114 | 115 | context_vector = torch.sum(encoded_seq.unsqueeze(1)*attn_weights_renormalized.unsqueeze(-1) , dim=-2) 116 | # shape batchXdec_seqlenXhiddensize 117 | # print(context_vector) 118 | 119 | return context_vector, attn_weights_renormalized 120 | 121 | 122 | 123 | 124 | 125 | class CopyMechanism(nn.Module): 126 | def __init__( 127 | self, encoder_hidden_size, decoder_hidden_size, decoder_input_size): 128 | super(CopyMechanism, self).__init__() 129 | self.pgen=nn.Sequential( 130 | nn.Linear(encoder_hidden_size+2*decoder_hidden_size+decoder_input_size, 1), 131 | nn.Sigmoid() 132 | ) 133 | self.output_probs=nn.Softmax(dim=-1) 134 | 135 | def forward( 136 | self, output_logits, attn_weights, decoder_hidden_state, decoder_input, 137 | context_vector, encoder_input, max_oovs): 138 | '''output_logits = batchXseqlenXoutvocab 139 | attn_weights = batchXseqlenXenc_len 140 | decoder_hidden_state = batchXseqlenXdecoder_hidden_size 141 | context_vector = batchXseqlenXencoder_hidden_dim 142 | encoder_input = batchxenc_len''' 143 | output_probabilities=self.output_probs(output_logits) 144 | 145 | # print(output_probabilities) 146 | 147 | batch_size = output_probabilities.size(0) 148 | output_len = output_probabilities.size(1) 149 | append_for_copy = torch.zeros((batch_size, output_len, max_oovs)).cuda() 150 | output_probabilities=torch.cat([output_probabilities, append_for_copy], dim=-1) 151 | 152 | pre_pgen_tensor=torch.cat([context_vector, decoder_hidden_state, decoder_input], dim=-1) 153 | pgen=self.pgen(pre_pgen_tensor) # batchsizeXseqlenX1 154 | pcopy=1.0-pgen 155 | 156 | encoder_input=encoder_input.unsqueeze(1).expand(-1, output_len , -1) # batchXseqlenXenc_len 157 | 158 | # Note that padding words donot get any attention because the attention is a masked attention 159 | 160 | copy_probabilities=torch.zeros_like(output_probabilities) # batchXseqlenXoutvocab 161 | copy_probabilities.scatter_add_(2, encoder_input, attn_weights) 162 | 163 | 164 | total_probabilities=pgen*output_probabilities+pcopy*copy_probabilities 165 | return total_probabilities, pgen # batchXseqlenXoutvocab , batchsizeXseqlenX1 166 | 167 | @Model.register("pointer_generator_withcoverage") 168 | class Seq2Seq(Model): 169 | def __init__(self, vocab, hidden_size=256, emb_size=128, num_encoder_layers=1, num_decoder_layers=1, min_decode_length=0, max_decode_length=9999, use_copy_mech=True, coverage_coef=1.0): 170 | super().__init__(vocab) 171 | # self.vocab=vocab 172 | 173 | ## vocab related setup begins 174 | assert "tokens" in vocab._token_to_index and len(vocab._token_to_index.keys())==1, "Vocabulary must have tokens as the only namespace" 175 | self.vocab_size=vocab.get_vocab_size() 176 | self.PAD_ID = vocab.get_token_index(vocab._padding_token) 177 | self.OOV_ID = vocab.get_token_index(vocab._oov_token) 178 | self.START_ID = vocab.get_token_index(START_SYMBOL) 179 | self.END_ID = vocab.get_token_index(END_SYMBOL) 180 | ## vocab related setup ends 181 | 182 | self.emb_size=emb_size 183 | self.hidden_size=hidden_size 184 | self.num_encoder_layers=num_encoder_layers 185 | self.num_decoder_layers=num_decoder_layers 186 | self.crossentropy=nn.CrossEntropyLoss() 187 | 188 | self.min_decode_length = min_decode_length 189 | self.max_decode_length = max_decode_length 190 | 191 | self.coverage_coef = coverage_coef 192 | 193 | self.metrics = { 194 | "accuracy" : CategoricalAccuracy(), 195 | "coverage_loss": Average(), 196 | "nll_loss": Average(), 197 | "total_loss": Average(), 198 | } 199 | 200 | # buffers because these dont need grads. These are placed here because they will be replicated across gpus 201 | self.register_buffer("true_rep", torch.tensor(1.0)) 202 | self.register_buffer("false_rep", torch.tensor(0.0)) 203 | 204 | self.pre_output_dim=hidden_size 205 | 206 | self.use_copy_mech=use_copy_mech 207 | 208 | self.output_embedder = nn.Sequential( 209 | nn.Embedding(num_embeddings=self.vocab_size, embedding_dim=self.emb_size) 210 | ) 211 | 212 | self.input_encoder = nn.Sequential( 213 | self.output_embedder, 214 | torch.nn.LSTM(input_size=self.emb_size, hidden_size=self.hidden_size, num_layers=self.num_encoder_layers, batch_first=True, bidirectional=True), 215 | ) 216 | 217 | self.fuse_h_layer= nn.Sequential( 218 | nn.Linear(2*hidden_size, hidden_size), 219 | nn.ReLU() 220 | ) 221 | 222 | self.fuse_c_layer= nn.Sequential( 223 | nn.Linear(2*hidden_size, hidden_size), 224 | nn.ReLU() 225 | ) 226 | 227 | self.attention_layer=Attention(2*hidden_size, 2*hidden_size, 2*hidden_size) 228 | 229 | if self.use_copy_mech: 230 | self.copymech=CopyMechanism(2*self.hidden_size, self.hidden_size, self.emb_size) 231 | 232 | self.decoder_rnn=torch.nn.LSTM(input_size=self.emb_size, hidden_size=self.hidden_size, num_layers=self.num_decoder_layers, batch_first=False, bidirectional=False) 233 | 234 | self.statenctx_to_prefinal = nn.Linear(3*hidden_size, hidden_size, bias=True) 235 | self.project_to_decoder_input = nn.Linear(emb_size+2*hidden_size, emb_size, bias=True) 236 | 237 | self.output_projector = torch.nn.Conv1d(self.pre_output_dim, self.vocab_size, kernel_size=1, bias=True) 238 | self.softmax = nn.Softmax(dim=-1) 239 | 240 | print("If you intend to train a new coverage-augmented model starting from weights of a non-coverage model, you need to specify the path to the weights file.") 241 | print("Otherwise, say no to the question if you intend to do inference or are continuing to train an already coverage-augmented model further using the --recover flag.") 242 | if get_yes_no("Do you want to load pretrained weights from a model trained without coverage? [y/n] :"): 243 | initial_precoverage_paramfile = input("Enter path to pre-coverage weight-file : ") 244 | print(f"Loading precoverage weights from {initial_precoverage_paramfile}") 245 | # this will contain path to a .th weights file that contains pre-coverage weights 246 | pretrained_dict = torch.load(initial_precoverage_paramfile, map_location="cuda:0") 247 | model_dict = self.state_dict() 248 | model_dict.update(pretrained_dict) 249 | self.load_state_dict(model_dict) 250 | 251 | 252 | 253 | def forward(self, source_tokens, target_tokens, meta=None, only_predict_probs=False, return_pgen=False): 254 | inp_with_unks = source_tokens["ids_with_unks"] 255 | inp_with_oovs = source_tokens["ids_with_oovs"] 256 | max_oovs = int(torch.max(source_tokens["num_oovs"])) 257 | 258 | feed_tensor = target_tokens["ids_with_unks"][:, :-1] 259 | if self.use_copy_mech: 260 | target_tensor = target_tokens["ids_with_oovs"][:,1:] 261 | else: 262 | target_tensor = target_tokens["ids_with_unks"][:, 1:] 263 | 264 | 265 | batch_size = inp_with_unks.size(0) 266 | # preparing intial state for feeding into decoder. layers of decoder after first one get zeros as initial state 267 | inp_enc_seq, (last_h_value, last_c_value) = self.encode(inp_with_unks) 268 | 269 | 270 | # inp_enc_seq is batchsizeXseqlenX2*hiddensize 271 | h_value = self.pad_zeros_to_init_state(last_h_value) 272 | c_value = self.pad_zeros_to_init_state(last_c_value) 273 | state_from_inp = (h_value, c_value) 274 | 275 | input_pad_mask=torch.where(inp_with_unks!=self.PAD_ID, self.true_rep, self.false_rep) 276 | 277 | output_embedded = self.output_embedder(feed_tensor) 278 | seqlen_first = output_embedded.permute(1,0,2) 279 | output_seq_len = seqlen_first.size(0) 280 | 281 | #initial values 282 | decoder_hidden_state=state_from_inp 283 | context_vector=torch.zeros(batch_size,1,2*self.hidden_size).cuda() 284 | 285 | # CONTROVERSIAL DIFFERENCE FROM SEE ET AL 286 | decoder_hstates_batchfirst = state_from_inp[0].permute(1, 0, 2) 287 | decoder_cstates_batchfirst = state_from_inp[1].permute(1, 0, 2) 288 | concatenated_decoder_states = torch.cat([decoder_cstates_batchfirst, decoder_hstates_batchfirst], dim=-1) 289 | context_vector, _ = self.attention_layer(inp_enc_seq, concatenated_decoder_states, input_pad_mask) 290 | # 291 | 292 | output_probs=[] 293 | pgens=[] 294 | coverages = [torch.zeros_like(inp_with_unks).type(torch.float).cuda()] 295 | all_attn_weights = [] 296 | 297 | for _i in range(output_seq_len): 298 | seqlen_first_onetimestep = seqlen_first[_i:_i+1] # shape is 1xbatchsizexembsize 299 | context_vector_seqlenfirst = context_vector.permute(1,0,2) # seqlen is 1 always 300 | pre_input_to_decoder=torch.cat([seqlen_first_onetimestep, context_vector_seqlenfirst], dim=-1) 301 | input_to_decoder=self.project_to_decoder_input(pre_input_to_decoder) # shape is 1xbatchsizexembsize 302 | 303 | decoder_h_values, decoder_hidden_state = self.decoder_rnn(input_to_decoder, decoder_hidden_state) 304 | # decoder_h_values is shape 1XbatchsizeXhiddensize 305 | 306 | decoder_h_values_batchfirst = decoder_h_values.permute(1,0,2) 307 | 308 | decoder_hstates_batchfirst = decoder_hidden_state[0].permute(1, 0, 2) 309 | decoder_cstates_batchfirst = decoder_hidden_state[1].permute(1, 0, 2) 310 | concatenated_decoder_states = torch.cat([decoder_cstates_batchfirst, decoder_hstates_batchfirst], dim=-1) 311 | 312 | prev_coverage = coverages[-1] 313 | 314 | context_vector, attn_weights = self.attention_layer(inp_enc_seq, concatenated_decoder_states, input_pad_mask, prev_coverage.unsqueeze(1)) 315 | 316 | all_attn_weights.append(attn_weights.squeeze(1)) 317 | 318 | coverages.append(prev_coverage + attn_weights.squeeze(1)) 319 | 320 | decstate_and_context=torch.cat([decoder_h_values_batchfirst, context_vector], dim=-1) #batchsizeXdec_seqlenX3*hidden_size 321 | prefinal_tensor = self.statenctx_to_prefinal(decstate_and_context) 322 | seqlen_last = prefinal_tensor.permute(0,2,1) #batchsizeXpre_output_dimXdec_seqlen 323 | logits = self.output_projector(seqlen_last) 324 | logits = logits.permute(0,2,1) # batchXdec_seqlenXvocab 325 | 326 | # return self.copymech.output_probs(logits) 327 | 328 | # now doing copymechanism 329 | if self.use_copy_mech: 330 | probs_after_copying, pgen = self.copymech(logits, attn_weights, concatenated_decoder_states, input_to_decoder.permute(1,0,2), context_vector, inp_with_oovs, max_oovs) 331 | pgens.append(pgen) 332 | output_probs.append(probs_after_copying) 333 | else: 334 | output_probs.append(self.softmax(logits)) 335 | 336 | # if only_predict_probs: 337 | # return output_probs 338 | 339 | # now calculating loss and numpreds 340 | '''outprobs is list of batchX1xvocabsize 341 | target_tensor is batchXseqlen''' 342 | targets_tensor_seqfirst = target_tensor.permute(1,0) 343 | target_pad_mask = torch.where(targets_tensor_seqfirst!=self.PAD_ID, self.true_rep, self.false_rep) 344 | # TODO: SHOULD WE SET REQUIRES_GRAD=FALSE FOR PAD_MASK? 345 | 346 | loss=0.0 347 | numpreds=0 348 | total_pgen=0 349 | 350 | total_pgen_placewise=torch.zeros((output_seq_len)).cuda() 351 | numpreds_placewise=torch.zeros((output_seq_len)).cuda() 352 | 353 | if return_pgen and not self.use_copy_mech: 354 | print("Cannot return pgen when copy mechanism is switched off") 355 | assert False 356 | 357 | for _i in range(len(output_probs)): 358 | predicted_probs = output_probs[_i].squeeze(1) 359 | true_labels = targets_tensor_seqfirst[_i] 360 | mask_labels = target_pad_mask[_i] 361 | selected_probs=torch.gather(input=predicted_probs, dim=1, index=true_labels.unsqueeze(1)) 362 | selected_probs=selected_probs.squeeze(1) 363 | selected_neg_logprobs=-1*torch.log(selected_probs) 364 | loss+=torch.sum(selected_neg_logprobs*mask_labels) 365 | 366 | this_numpreds=torch.sum(mask_labels).detach() 367 | numpreds+=this_numpreds 368 | 369 | self.metrics["accuracy"](predicted_probs, true_labels, mask_labels) 370 | 371 | if return_pgen: 372 | pgen=pgens[_i].squeeze(1).squeeze(1) 373 | total_pgen+=torch.sum(pgen*mask_labels) 374 | 375 | total_pgen_placewise[_i]+=torch.sum(pgen*mask_labels).detach() 376 | numpreds_placewise[_i]+=this_numpreds 377 | 378 | # print(pgen.shape, mask_labels.shape , (pgen*mask_labels).shape, selected_neg_logprobs.shape) 379 | # print(torch.sum(pgen), torch.sum(pgen*mask_labels), torch.sum(mask_labels).detach()) 380 | 381 | coverage_loss = self.coverage_loss(all_attn_weights, target_pad_mask.permute(1,0)) # have to permute to get batcsize to first dim 382 | nll_loss = loss/numpreds 383 | total_loss = nll_loss + self.coverage_coef*coverage_loss 384 | 385 | self.metrics["coverage_loss"](coverage_loss.item()) 386 | self.metrics["nll_loss"](nll_loss.item()) 387 | self.metrics["total_loss"](total_loss.item()) 388 | 389 | return { 390 | "loss": total_loss 391 | } 392 | 393 | 394 | def coverage_loss(self, all_attn_weights, output_padding_mask): 395 | '''all_attn_weights is list of elems where each elem is batchsizeXinp_enclen 396 | mask is batchsizeXdeclen''' 397 | coverages = [torch.zeros_like(all_attn_weights[0])] 398 | covlosses = [] 399 | for a in all_attn_weights: 400 | old_coverage = coverages[-1] 401 | minimums = torch.min(a, old_coverage) 402 | covloss = torch.sum(minimums, dim=1, keepdim=True) 403 | covlosses.append(covloss) 404 | new_coverage = old_coverage + a 405 | coverages.append(new_coverage) 406 | concatenated_covlosses = torch.cat(covlosses, dim=1) 407 | coverage_loss = torch.sum(concatenated_covlosses*output_padding_mask)/torch.sum(output_padding_mask) 408 | return coverage_loss 409 | 410 | 411 | 412 | def pad_zeros_to_init_state(self, h_value): 413 | '''can also be c_value''' 414 | assert(h_value.size(0)==1) # h_value should only be of last layer of lstm 415 | return torch.cat([h_value]+[torch.zeros_like(h_value) for _i in range(self.num_encoder_layers-1)], dim=0) 416 | 417 | 418 | def encode(self, inp): 419 | '''Get the encoding of input''' 420 | batch_size = inp.size(0) 421 | inp_seq_len = inp.size(1) 422 | inp_encoded = self.input_encoder(inp) 423 | output_seq=inp_encoded[0] 424 | h_value, c_value = inp_encoded[1] 425 | 426 | h_value_layerwise=h_value.reshape(self.num_encoder_layers, 2, batch_size, self.hidden_size) # numlayersXbidirecXbatchXhid 427 | c_value_layerwise=c_value.reshape(self.num_encoder_layers, 2, batch_size, self.hidden_size) # numlayersXbidirecXbatchXhid 428 | 429 | last_layer_h=h_value_layerwise[-1:,:,:,:] 430 | last_layer_c=c_value_layerwise[-1:,:,:,:] 431 | 432 | last_layer_h=last_layer_h.permute(0,2,1,3).contiguous().view(1, batch_size, 2*self.hidden_size) 433 | last_layer_c=last_layer_c.permute(0,2,1,3).contiguous().view(1, batch_size, 2*self.hidden_size) 434 | 435 | last_layer_h_fused=self.fuse_h_layer(last_layer_h) 436 | last_layer_c_fused=self.fuse_c_layer(last_layer_c) 437 | 438 | return output_seq, (last_layer_h_fused, last_layer_c_fused) 439 | 440 | 441 | def decode_onestep(self, past_outp_input, past_state_tuple, past_context_vector, inp_enc_seq, inp_with_oovs, input_pad_mask, max_oovs, past_coverage_vector): 442 | '''run one step of decoder. outp_input is batchsizex1 443 | past_context_vector is batchsizeX1Xtwice_of_hiddensize 444 | past_coverage_vector is batchsizeXenc_len''' 445 | outp_embedded = self.output_embedder(past_outp_input) 446 | tok_seqlen_first = outp_embedded.permute(1,0,2) 447 | assert(tok_seqlen_first.size(0)==1) # only one timestep allowed 448 | 449 | context_vector_seqlenfirst = past_context_vector.permute(1,0,2) # seqlen is 1 always 450 | pre_input_to_decoder=torch.cat([tok_seqlen_first, context_vector_seqlenfirst], dim=-1) 451 | input_to_decoder=self.project_to_decoder_input(pre_input_to_decoder) # shape is 1xbatchsizexembsize 452 | 453 | 454 | decoder_h_values, decoder_hidden_state = self.decoder_rnn(input_to_decoder, past_state_tuple) 455 | # decoder_h_values is shape 1XbatchsizeXhiddensize 456 | decoder_h_values_batchfirst = decoder_h_values.permute(1,0,2) 457 | 458 | decoder_hstates_batchfirst = decoder_hidden_state[0].permute(1, 0, 2) 459 | decoder_cstates_batchfirst = decoder_hidden_state[1].permute(1, 0, 2) 460 | concatenated_decoder_states = torch.cat([decoder_cstates_batchfirst, decoder_hstates_batchfirst], dim=-1) 461 | 462 | context_vector, attn_weights = self.attention_layer(inp_enc_seq, concatenated_decoder_states, input_pad_mask, past_coverage_vector.unsqueeze(1)) 463 | 464 | decstate_and_context=torch.cat([decoder_h_values_batchfirst, context_vector], dim=-1) #batchsizeXdec_seqlenX3*hidden_size 465 | prefinal_tensor = self.statenctx_to_prefinal(decstate_and_context) 466 | seqlen_last = prefinal_tensor.permute(0,2,1) #batchsizeXpre_output_dimXdec_seqlen 467 | logits = self.output_projector(seqlen_last) 468 | logits = logits.permute(0,2,1) # batchXdec_seqlenXvocab 469 | 470 | 471 | # now doing copymechanism 472 | if self.use_copy_mech: 473 | probs_after_copying, _ = self.copymech(logits, attn_weights, concatenated_decoder_states, input_to_decoder.permute(1,0,2), context_vector, inp_with_oovs, max_oovs) 474 | prob_to_return = probs_after_copying[0].squeeze(1) 475 | else: 476 | prob_to_return = self.softmax(logits).squeeze(1) 477 | 478 | # max_attended = inp_with_oovs[0][torch.argmax(attn_weights)].item() 479 | # max_prob = torch.argmax(probs_after_copying[0][0]) 480 | # print("Attended=", self.vocab._id2token[max_attended]) 481 | # print("Maxprob=", self.vocab._id2token[max_prob]) 482 | 483 | return prob_to_return, decoder_hidden_state, context_vector, attn_weights 484 | 485 | 486 | 487 | def get_initial_state(self, start_ids, initial_decode_state): 488 | '''start_ids is tensor of size batchsizeXseqlen''' 489 | outp_embedded = self.output_embedder(start_ids) 490 | seqlen_first = outp_embedded.permute(1,0,2) 491 | feed=seqlen_first 492 | seqlen=feed.size(0) 493 | h_value, c_value = initial_decode_state 494 | for idx in range(seqlen): 495 | _ , (h_value, c_value) = self.decoder_rnn(feed[idx:idx+1], (h_value, c_value)) 496 | 497 | return (h_value, c_value) 498 | 499 | 500 | @overrides 501 | def forward_on_instance(self, instance: SyncedFieldsInstance) -> Dict[str, str]: 502 | """ 503 | Takes an :class:`~allennlp.data.instance.Instance`, which typically has raw text in it, 504 | converts that text into arrays using this model's :class:`Vocabulary`, passes those arrays 505 | through :func:`self.forward()` and :func:`self.decode()` (which by default does nothing) 506 | and returns the result. Before returning the result, we convert any 507 | ``torch.Tensors`` into numpy arrays and remove the batch dimension. 508 | """ 509 | cuda_device = self._get_prediction_device() 510 | dataset = Batch([instance]) 511 | dataset.index_instances(self.vocab) 512 | model_input = util.move_to_device(dataset.as_tensor_dict(), cuda_device) 513 | output_ids = self.beam_search_decode(**model_input, min_length=self.min_decode_length, max_length=self.max_decode_length) 514 | # output_ids = self.greedy_decode(**model_input, min_length=self.min_decode_length, max_length=self.max_decode_length) 515 | 516 | output_words = [] 517 | for _id in output_ids: 518 | if _id Dict[str, float]: 532 | metrics_to_return = { 533 | metric_name: metric.get_metric(reset) for metric_name, metric in self.metrics.items() 534 | } 535 | return metrics_to_return 536 | 537 | 538 | def beam_search_decode(self, source_tokens, target_tokens=None, meta=None, beam_width=4, min_length=35, max_length=120): 539 | inp_with_unks = source_tokens["ids_with_unks"] 540 | inp_with_oovs = source_tokens["ids_with_oovs"] 541 | max_oovs = int(torch.max(source_tokens["num_oovs"])) 542 | input_pad_mask=torch.where(inp_with_unks!=self.PAD_ID, self.true_rep, self.false_rep) 543 | inp_enc_seq, (intial_h_value, intial_c_value) = self.encode(inp_with_unks) 544 | h_value = self.pad_zeros_to_init_state(intial_h_value) 545 | c_value = self.pad_zeros_to_init_state(intial_c_value) 546 | source_encoding=(h_value, c_value) 547 | 548 | # the first context vector is calculated by using the first lstm decoder state 549 | first_decoder_hstates_batchfirst = source_encoding[0].permute(1, 0, 2) 550 | first_decoder_cstates_batchfirst = source_encoding[1].permute(1, 0, 2) 551 | first_concatenated_decoder_states = torch.cat([first_decoder_cstates_batchfirst, first_decoder_hstates_batchfirst], dim=-1) 552 | starting_coverage = torch.zeros_like(inp_with_unks).type(torch.float).cuda() 553 | first_context_vector, first_attention = self.attention_layer(inp_enc_seq, first_concatenated_decoder_states, input_pad_mask, starting_coverage) 554 | 555 | hypotheses = [ {"dec_state" : source_encoding, 556 | "past_context_vector" : first_context_vector, 557 | "logprobs" : [0.0], 558 | "out_words" : [self.START_ID], 559 | "coverage" : first_attention.squeeze(1), 560 | } ] 561 | 562 | finished_hypotheses = [] 563 | 564 | def sort_hyps(list_of_hyps): 565 | return sorted(list_of_hyps, key=lambda x:sum(x["logprobs"])/len(x["logprobs"]), reverse=True) 566 | 567 | counter=0 568 | while counter=self.vocab_size: # this guy is an OOV 577 | in_tok=self.OOV_ID 578 | old_dec_state=hyp["dec_state"] 579 | past_context_vector=hyp["past_context_vector"] 580 | past_coverage_vector=hyp["coverage"] 581 | old_logprobs=hyp["logprobs"] 582 | new_probs, new_dec_state, new_context_vector, attn_weights = self.decode_onestep( torch.tensor([[in_tok]]).cuda(), old_dec_state, past_context_vector, inp_enc_seq, inp_with_oovs, input_pad_mask, max_oovs, past_coverage_vector) 583 | 584 | probs, indices = torch.topk(new_probs[0], dim=0, k=2*beam_width) 585 | for p, idx in zip(probs, indices): 586 | new_dict = {"dec_state" : new_dec_state, 587 | "past_context_vector" : new_context_vector, 588 | "logprobs" : old_logprobs+[float(torch.log(p).detach().cpu().numpy())], 589 | "out_words" : old_out_words+[idx.item()], 590 | "coverage": past_coverage_vector+attn_weights.squeeze(1) 591 | } 592 | new_hypotheses.append(new_dict) 593 | 594 | # time to pick the best of new hypotheses 595 | sorted_new_hypotheses = sort_hyps(new_hypotheses) 596 | hypotheses=[] 597 | for hyp in sorted_new_hypotheses: 598 | if hyp["out_words"][-1]==self.END_ID: 599 | if len(hyp["out_words"])>min_length+1: 600 | finished_hypotheses.append(hyp) 601 | else: 602 | hypotheses.append(hyp) 603 | if len(hypotheses) == beam_width or len(finished_hypotheses) == beam_width: 604 | break 605 | 606 | if len(finished_hypotheses)>0: 607 | final_candidates = finished_hypotheses 608 | else: 609 | final_candidates = hypotheses 610 | 611 | sorted_final_candidates = sort_hyps(final_candidates) 612 | 613 | best_candidate = sorted_final_candidates[0] 614 | return best_candidate["out_words"] 615 | -------------------------------------------------------------------------------- /pretrained_model_skeleton.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kukrishna/pointer-generator-pytorch-allennlp/4e4dde6eb100bcd5b8e7534738ddb77fd854e3d7/pretrained_model_skeleton.tar.gz -------------------------------------------------------------------------------- /pretrained_model_skeleton_withcoverage.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kukrishna/pointer-generator-pytorch-allennlp/4e4dde6eb100bcd5b8e7534738ddb77fd854e3d7/pretrained_model_skeleton_withcoverage.tar.gz -------------------------------------------------------------------------------- /sample_datafile.jsonl: -------------------------------------------------------------------------------- 1 | {"article_lines": ["I am a cat .", "My name is Tom .", "I chase Jerry all day ."], "summary_lines": ["Tom is a cat .", "He chases a mouse ."]} 2 | {"article_lines": ["I am a mouse .", "My name is Jerry.", "I run away from Tom all day .", "He can never catch me ."], "summary_lines": ["Jerry is a mouse that runs away from a cat ."]} -------------------------------------------------------------------------------- /sample_experiment.jsonnet: -------------------------------------------------------------------------------- 1 | { 2 | "dataset_reader": { 3 | "lazy": false, 4 | "type": "cnndmail_dataset_reader", 5 | "lowercase_tokens": true, 6 | }, 7 | "validation_dataset_reader": { 8 | "lazy": false, 9 | "type": "cnndmail_dataset_reader", 10 | "lowercase_tokens": true, 11 | }, 12 | "datasets_for_vocab_creation": ["train"], 13 | "train_data_path": "sample_datafile.jsonl", // path to training jsonl file 14 | "validation_data_path": "sample_datafile.jsonl", // path to validation jsonl file 15 | "vocabulary": { 16 | "extend": true, 17 | "directory_path": "bootstrapped_vocabulary", 18 | "max_vocab_size": 49998 // note that this is the max number of words to add on top of the words already present in bootstrapped vocab after unk ie. (start, end) 19 | }, 20 | "model": { 21 | "type": "pointer_generator", 22 | "hidden_size": 64, 23 | "emb_size": 32, 24 | }, 25 | "iterator": { 26 | "type": "bucket", 27 | "sorting_keys": [["source_tokens", "num_tokens"]], 28 | "batch_size": 16 29 | }, 30 | "trainer": { 31 | "optimizer": { 32 | "type": "adam", 33 | "lr": 0.001 34 | }, 35 | "validation_metric": "-loss", 36 | "num_serialized_models_to_keep": 1, 37 | "num_epochs": 100, 38 | "grad_norm": 10.0, 39 | "patience": 50, 40 | "cuda_device": 0 41 | } 42 | } 43 | --------------------------------------------------------------------------------