├── LICENSE.txt
├── README.md
├── absa
├── run_base.py
├── run_cls_span.py
├── run_extract_span.py
├── run_joint_span.py
└── utils.py
├── bert
├── modeling.py
├── optimization.py
├── sentiment_modeling.py
└── tokenization.py
├── data
└── absa
│ ├── laptop14_test.txt
│ ├── laptop14_train.txt
│ ├── rest_total_test.txt
│ ├── rest_total_train.txt
│ ├── twitter10_test.txt
│ ├── twitter10_train.txt
│ ├── twitter1_test.txt
│ ├── twitter1_train.txt
│ ├── twitter2_test.txt
│ ├── twitter2_train.txt
│ ├── twitter3_test.txt
│ ├── twitter3_train.txt
│ ├── twitter4_test.txt
│ ├── twitter4_train.txt
│ ├── twitter5_test.txt
│ ├── twitter5_train.txt
│ ├── twitter6_test.txt
│ ├── twitter6_train.txt
│ ├── twitter7_test.txt
│ ├── twitter7_train.txt
│ ├── twitter8_test.txt
│ ├── twitter8_train.txt
│ ├── twitter9_test.txt
│ └── twitter9_train.txt
├── image
└── framework.PNG
└── squad
├── __pycache__
├── squad_evaluate.cpython-35.pyc
├── squad_evaluate.cpython-36.pyc
├── squad_utils.cpython-35.pyc
└── squad_utils.cpython-36.pyc
├── squad_evaluate.py
└── squad_utils.py
/LICENSE.txt:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Open-Domain Targeted Sentiment Analysis via Span-Based Extraction and Classification
2 |
3 | This repo contains the code and data of the following paper:
4 |
5 | [Open-Domain Targeted Sentiment Analysis via Span-Based Extraction and Classification](https://arxiv.org/abs/1906.03820). Minghao Hu, Yuxing Peng, Zhen Huang, Dongsheng Li, Yiwei Lv. ACL 2019.
6 |
7 | In this paper, we propose a span-based extract-then-classify framework for the open-domain targeted sentiment analysis task, which is shown as below:
8 |
9 |
10 |
11 |
12 | This framework consists of two components:
13 | - Multi-target extractor
14 | - Polarity classifier
15 |
16 | Both of two components utilize [BERT](https://github.com/huggingface/pytorch-pretrained-BERT) as backbone network. The multi-target extractor aims to propose one or multiple candidate targets based on the probabilities of the start and end positions. The polarity classifier predicts the sentiment polarity using the span representation of the given target.
17 |
18 | ## Requirements
19 | - Python 3.6
20 | - [Pytorch 1.1](https://pytorch.org/)
21 | - [Allennlp](https://allennlp.org/)
22 |
23 | Download the uncased [BERT-Base](https://drive.google.com/file/d/13I0Gj7v8lYhW5Hwmp5kxm3CTlzWZuok2/view?usp=sharing) model and unzip it in the current directory.
24 |
25 | Run the following commands to set up environments:
26 | ```bash
27 | export DATA_DIR=data/absa
28 | export BERT_DIR=bert-base-uncased
29 | ```
30 |
31 | ## Multi-target extractor
32 | Train the multi-target extractor:
33 | ```shell
34 | python -m absa.run_extract_span \
35 | --vocab_file $BERT_DIR/vocab.txt \
36 | --bert_config_file $BERT_DIR/bert_config.json \
37 | --init_checkpoint $BERT_DIR/pytorch_model.bin \
38 | --do_train \
39 | --do_predict \
40 | --data_dir $DATA_DIR \
41 | --train_file rest_total_train.txt \
42 | --predict_file rest_total_test.txt \
43 | --train_batch_size 32 \
44 | --output_dir out/extract/01
45 | ```
46 |
47 | ## Polarity classifier
48 | Train the polarity classifier:
49 | ```shell
50 | python -m absa.run_cls_span \
51 | --vocab_file $BERT_DIR/vocab.txt \
52 | --bert_config_file $BERT_DIR/bert_config.json \
53 | --init_checkpoint $BERT_DIR/pytorch_model.bin \
54 | --do_train \
55 | --do_predict \
56 | --data_dir $DATA_DIR \
57 | --train_file rest_total_train.txt \
58 | --predict_file rest_total_test.txt \
59 | --train_batch_size 32 \
60 | --output_dir out/cls/01
61 | ```
62 |
63 | ## Pipelined method
64 | Once the above two components have been trained, we can construct a pipeline system by running the following command:
65 | ```shell
66 | python -m absa.run_extract_span \
67 | --vocab_file $BERT_DIR/vocab.txt \
68 | --bert_config_file $BERT_DIR/bert_config.json \
69 | --do_pipeline \
70 | --data_dir $DATA_DIR \
71 | --predict_file rest_total_test.txt \
72 | --logit_threshold 9.5 \
73 | --output_dir out/extract/01
74 |
75 | python -m absa.run_cls_span \
76 | --vocab_file $BERT_DIR/vocab.txt \
77 | --bert_config_file $BERT_DIR/bert_config.json \
78 | --do_pipeline \
79 | --data_dir $DATA_DIR \
80 | --predict_file rest_total_test.txt \
81 | --output_dir out/cls/01 \
82 | --extraction_file out/extract/01/extraction_results.pkl
83 | ```
84 | The predicted results will be saved into a file called `predictions.json` in the `output_dir`:
85 | ```bash
86 | cat out/cls/01/predictions.json
87 | ```
88 |
89 | The test performance is shown in a file called `performance.txt` in the `output_dir`:
90 | ```bash
91 | cat out/cls/01/performance.txt
92 | ```
93 | Which should produce an output like this:
94 | ```bash
95 | pipeline, step: 210, P: 0.6991, R: 0.7156, F1: 0.7073 (common: 1638.0, retrieved: 2343.0, relevant: 2289.0)
96 | ```
97 |
98 | If you train with the `BERT-Large` model, you should see a result similar to 74.9 F1 reported in the paper (The `logit_threshold` is set as 12).
99 |
100 | ## Joint method
101 | You can also try to run the joint method, which jointly train both the multi-target extractor and the polarity classifier:
102 | ```shell
103 | python -m absa.run_joint_span \
104 | --vocab_file $BERT_DIR/vocab.txt \
105 | --bert_config_file $BERT_DIR/bert_config.json \
106 | --init_checkpoint $BERT_DIR/pytorch_model.bin \
107 | --do_train \
108 | --do_predict \
109 | --data_dir $DATA_DIR \
110 | --train_file rest_total_train.txt \
111 | --predict_file rest_total_test.txt \
112 | --train_batch_size 32 \
113 | --logit_threshold 8.0 \
114 | --output_dir out/joint/01
115 | ```
116 |
117 | This will produce a result like this:
118 | ```bash
119 | threshold: 8.0, step: 234, P: 0.7192, R: 0.6514, F1: 0.6836 (common: 1491.0, retrieved: 2073.0, relevant: 2289.0)
120 | ```
121 |
122 | ## Acknowledgements
123 | We sincerely thank Xin Li for releasing the [datasets](https://github.com/lixin4ever/E2E-TBSA).
124 |
125 | If you find the paper or this repository helpful in your work, please use the following citation:
126 | ```
127 | @inproceedings{hu2019open,
128 | title={Open-Domain Targeted Sentiment Analysis via Span-Based Extraction and Classification},
129 | author={Hu, Minghao and Peng, Yuxing and Huang, Zhen and Li, Dongsheng and Lv, Yiwei},
130 | booktitle={Proceedings of ACL},
131 | year={2019}
132 | }
133 | ```
134 |
--------------------------------------------------------------------------------
/absa/run_base.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from __future__ import division
3 | from __future__ import print_function
4 |
5 | import sys
6 | import torch
7 | from bert.optimization import BERTAdam
8 |
9 | try:
10 | import xml.etree.ElementTree as ET, getopt, logging, sys, random, re, copy
11 | from xml.sax.saxutils import escape
12 | except:
13 | sys.exit('Some package is missing... Perhaps ?')
14 |
15 | logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
16 | datefmt = '%m/%d/%Y %H:%M:%S',
17 | level = logging.INFO)
18 | logger = logging.getLogger(__name__)
19 |
20 | def copy_optimizer_params_to_model(named_params_model, named_params_optimizer):
21 | """ Utility function for optimize_on_cpu and 16-bits training.
22 | Copy the parameters optimized on CPU/RAM back to the model on GPU
23 | """
24 | for (name_opti, param_opti), (name_model, param_model) in zip(named_params_optimizer, named_params_model):
25 | if name_opti != name_model:
26 | logger.error("name_opti != name_model: {} {}".format(name_opti, name_model))
27 | raise ValueError
28 | param_model.data.copy_(param_opti.data)
29 |
30 | def set_optimizer_params_grad(named_params_optimizer, named_params_model, test_nan=False):
31 | """ Utility function for optimize_on_cpu and 16-bits training.
32 | Copy the gradient of the GPU parameters to the CPU/RAMM copy of the model
33 | """
34 | is_nan = False
35 | for (name_opti, param_opti), (name_model, param_model) in zip(named_params_optimizer, named_params_model):
36 | if name_opti != name_model:
37 | logger.error("name_opti != name_model: {} {}".format(name_opti, name_model))
38 | raise ValueError
39 | if test_nan and torch.isnan(param_model.grad).sum() > 0:
40 | is_nan = True
41 | if param_opti.grad is None:
42 | param_opti.grad = torch.nn.Parameter(param_opti.data.new().resize_(*param_opti.data.size()))
43 | param_opti.grad.data.copy_(param_model.grad.data)
44 | return is_nan
45 |
46 | def prepare_optimizer(args, model, num_train_steps):
47 | if args.fp16:
48 | param_optimizer = [(n, param.clone().detach().to('cpu').float().requires_grad_()) \
49 | for n, param in model.named_parameters()]
50 | elif args.optimize_on_cpu:
51 | param_optimizer = [(n, param.clone().detach().to('cpu').requires_grad_()) \
52 | for n, param in model.named_parameters()]
53 | else:
54 | param_optimizer = list(model.named_parameters())
55 | no_decay = ['bias', 'LayerNorm']
56 | optimizer_grouped_parameters = [
57 | {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
58 | {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}]
59 | optimizer = BERTAdam(optimizer_grouped_parameters,
60 | lr=args.learning_rate,
61 | warmup=args.warmup_proportion,
62 | t_total=num_train_steps)
63 | return optimizer, param_optimizer
64 |
65 | def post_process_loss(args, n_gpu, loss):
66 | if n_gpu > 1:
67 | loss = loss.mean() # mean() to average on multi-gpu.
68 | if args.fp16 and args.loss_scale != 1.0:
69 | # rescale loss for fp16 training
70 | # see https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/index.html
71 | loss = loss * args.loss_scale
72 | if args.gradient_accumulation_steps > 1:
73 | loss = loss / args.gradient_accumulation_steps
74 | return loss
75 |
76 | def bert_load_state_dict(model, state_dict):
77 | missing_keys = []
78 | unexpected_keys = []
79 | error_msgs = []
80 |
81 | # copy state_dict so _load_from_state_dict can modify it
82 | metadata = getattr(state_dict, '_metadata', None)
83 | state_dict = state_dict.copy()
84 | if metadata is not None:
85 | state_dict._metadata = metadata
86 |
87 | def load(module, prefix=''):
88 | local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {})
89 | module._load_from_state_dict(
90 | state_dict, prefix, local_metadata, True, missing_keys, unexpected_keys, error_msgs)
91 | for name, child in module._modules.items():
92 | if child is not None:
93 | load(child, prefix + name + '.')
94 |
95 | load(model, prefix='' if hasattr(model, 'bert') else 'bert.')
96 |
97 | if len(missing_keys) > 0:
98 | logger.info("Weights of {} not initialized from pretrained model: {}".format(
99 | model.__class__.__name__, missing_keys))
100 | if len(unexpected_keys) > 0:
101 | logger.info("Weights from pretrained model not used in {}: {}".format(
102 | model.__class__.__name__, unexpected_keys))
103 | return model
--------------------------------------------------------------------------------
/absa/run_cls_span.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
3 | #
4 | # Licensed under the Apache License, Version 2.0 (the "License");
5 | # you may not use this file except in compliance with the License.
6 | # You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 | """Run BERT on SemEval."""
16 |
17 | from __future__ import absolute_import
18 | from __future__ import division
19 | from __future__ import print_function
20 |
21 | import sys
22 | import os
23 | import pickle
24 | import json
25 | import argparse
26 | import collections
27 |
28 | import numpy as np
29 | import torch
30 | from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
31 | from torch.utils.data.distributed import DistributedSampler
32 |
33 | import bert.tokenization as tokenization
34 | from bert.modeling import BertConfig
35 | from bert.sentiment_modeling import BertForSpanAspectClassification
36 |
37 | from squad.squad_evaluate import exact_match_score
38 | from absa.utils import read_absa_data, convert_absa_data, convert_examples_to_features, \
39 | RawFinalResult, wrapped_get_final_text, id_to_label
40 | from absa.run_base import copy_optimizer_params_to_model, set_optimizer_params_grad, prepare_optimizer, post_process_loss, bert_load_state_dict
41 |
42 | try:
43 | import xml.etree.ElementTree as ET, getopt, logging, sys, random, re, copy
44 | from xml.sax.saxutils import escape
45 | except:
46 | sys.exit('Some package is missing... Perhaps ?')
47 |
48 | logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
49 | datefmt = '%m/%d/%Y %H:%M:%S',
50 | level = logging.INFO)
51 | logger = logging.getLogger(__name__)
52 |
53 | def read_train_data(args, tokenizer, logger):
54 | if args.debug:
55 | args.train_batch_size = 8
56 |
57 | train_path = os.path.join(args.data_dir, args.train_file)
58 | train_set = read_absa_data(train_path)
59 | train_examples = convert_absa_data(dataset=train_set, verbose_logging=args.verbose_logging)
60 | train_features = convert_examples_to_features(train_examples, tokenizer, args.max_seq_length,
61 | args.verbose_logging, logger)
62 |
63 | num_train_steps = int(
64 | len(train_features) / args.train_batch_size / args.gradient_accumulation_steps * args.num_train_epochs)
65 | logger.info("Num orig examples = %d", len(train_examples))
66 | logger.info("Num split features = %d", len(train_features))
67 | logger.info("Batch size = %d", args.train_batch_size)
68 | logger.info("Num steps = %d", num_train_steps)
69 | all_input_ids = torch.tensor([f.input_ids for f in train_features], dtype=torch.long)
70 | all_input_mask = torch.tensor([f.input_mask for f in train_features], dtype=torch.long)
71 | all_segment_ids = torch.tensor([f.segment_ids for f in train_features], dtype=torch.long)
72 | all_span_starts = torch.tensor([f.start_indexes for f in train_features], dtype=torch.long)
73 | all_span_ends = torch.tensor([f.end_indexes for f in train_features], dtype=torch.long)
74 | all_labels = torch.tensor([f.polarity_labels for f in train_features], dtype=torch.long)
75 | all_label_masks = torch.tensor([f.label_masks for f in train_features], dtype=torch.long)
76 |
77 | train_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_span_starts, all_span_ends,
78 | all_labels, all_label_masks)
79 | if args.local_rank == -1:
80 | train_sampler = RandomSampler(train_data)
81 | else:
82 | train_sampler = DistributedSampler(train_data)
83 | train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=args.train_batch_size)
84 | return train_dataloader, num_train_steps
85 |
86 | def read_eval_data(args, tokenizer, logger):
87 | if args.debug:
88 | args.predict_batch_size = 8
89 |
90 | eval_path = os.path.join(args.data_dir, args.predict_file)
91 | eval_set = read_absa_data(eval_path)
92 | eval_examples = convert_absa_data(dataset=eval_set, verbose_logging=args.verbose_logging)
93 | eval_features = convert_examples_to_features(eval_examples, tokenizer, args.max_seq_length,
94 | args.verbose_logging, logger)
95 |
96 | logger.info("Num orig examples = %d", len(eval_examples))
97 | logger.info("Num split features = %d", len(eval_features))
98 | logger.info("Batch size = %d", args.predict_batch_size)
99 | all_input_ids = torch.tensor([f.input_ids for f in eval_features], dtype=torch.long)
100 | all_input_mask = torch.tensor([f.input_mask for f in eval_features], dtype=torch.long)
101 | all_segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long)
102 | all_span_starts = torch.tensor([f.start_indexes for f in eval_features], dtype=torch.long)
103 | all_span_ends = torch.tensor([f.end_indexes for f in eval_features], dtype=torch.long)
104 | all_label_masks = torch.tensor([f.label_masks for f in eval_features], dtype=torch.long)
105 | all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long)
106 | eval_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_span_starts, all_span_ends,
107 | all_label_masks, all_example_index)
108 | if args.local_rank == -1:
109 | eval_sampler = SequentialSampler(eval_data)
110 | else:
111 | eval_sampler = DistributedSampler(eval_data)
112 | eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.predict_batch_size)
113 | return eval_examples, eval_features, eval_dataloader
114 |
115 | def pipeline_eval_data(args, tokenizer, logger):
116 | if args.debug:
117 | args.predict_batch_size = 8
118 |
119 | eval_path = os.path.join(args.data_dir, args.predict_file)
120 | eval_set = read_absa_data(eval_path)
121 | eval_examples = convert_absa_data(dataset=eval_set, verbose_logging=args.verbose_logging)
122 |
123 | eval_features = convert_examples_to_features(eval_examples, tokenizer, args.max_seq_length,
124 | args.verbose_logging, logger)
125 |
126 | assert args.extraction_file is not None
127 | eval_extract_preds = []
128 | extract_predictions = pickle.load(open(args.extraction_file, 'rb'))
129 | extract_dict = {}
130 | for pred in extract_predictions:
131 | extract_dict[pred.unique_id] = pred
132 | for eval_feature in eval_features:
133 | eval_extract_preds.append(extract_dict[eval_feature.unique_id])
134 | assert len(eval_extract_preds) == len(eval_features)
135 |
136 | logger.info("Num orig examples = %d", len(eval_examples))
137 | logger.info("Num split features = %d", len(eval_features))
138 | logger.info("Batch size = %d", args.predict_batch_size)
139 | all_input_ids = torch.tensor([f.input_ids for f in eval_features], dtype=torch.long)
140 | all_input_mask = torch.tensor([f.input_mask for f in eval_features], dtype=torch.long)
141 | all_segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long)
142 | all_span_starts = torch.tensor([f.start_indexes for f in eval_extract_preds], dtype=torch.long)
143 | all_span_ends = torch.tensor([f.end_indexes for f in eval_extract_preds], dtype=torch.long)
144 | all_label_masks = torch.tensor([f.span_masks for f in eval_extract_preds], dtype=torch.long)
145 | all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long)
146 | eval_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_span_starts, all_span_ends,
147 | all_label_masks, all_example_index)
148 | if args.local_rank == -1:
149 | eval_sampler = SequentialSampler(eval_data)
150 | else:
151 | eval_sampler = DistributedSampler(eval_data)
152 | eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.predict_batch_size)
153 | return eval_examples, eval_features, eval_dataloader
154 |
155 | def run_train_epoch(args, global_step, model, param_optimizer, train_dataloader,
156 | eval_examples, eval_features, eval_dataloader,
157 | optimizer, n_gpu, device, logger, log_path, save_path,
158 | save_checkpoints_steps, start_save_steps, best_f1):
159 | running_loss, count = 0.0, 0
160 | for step, batch in enumerate(train_dataloader):
161 | if n_gpu == 1:
162 | batch = tuple(t.to(device) for t in batch) # multi-gpu does scattering it-self
163 | input_ids, input_mask, segment_ids, span_starts, span_ends, labels, label_masks = batch
164 | loss = model('train', input_mask, input_ids=input_ids, token_type_ids=segment_ids,
165 | span_starts=span_starts, span_ends=span_ends, labels=labels, label_masks=label_masks)
166 | loss = post_process_loss(args, n_gpu, loss)
167 | loss.backward()
168 | running_loss += loss.item()
169 |
170 | if (step + 1) % args.gradient_accumulation_steps == 0:
171 | if args.fp16 or args.optimize_on_cpu:
172 | if args.fp16 and args.loss_scale != 1.0:
173 | # scale down gradients for fp16 training
174 | for param in model.parameters():
175 | param.grad.data = param.grad.data / args.loss_scale
176 | is_nan = set_optimizer_params_grad(param_optimizer, model.named_parameters(), test_nan=True)
177 | if is_nan:
178 | logger.info("FP16 TRAINING: Nan in gradients, reducing loss scaling")
179 | args.loss_scale = args.loss_scale / 2
180 | model.zero_grad()
181 | continue
182 | optimizer.step()
183 | copy_optimizer_params_to_model(model.named_parameters(), param_optimizer)
184 | else:
185 | optimizer.step()
186 | model.zero_grad()
187 | global_step += 1
188 | count += 1
189 |
190 | if global_step % save_checkpoints_steps == 0 and count != 0:
191 | logger.info("step: {}, loss: {:.4f}".format(global_step, running_loss / count))
192 |
193 | if global_step % save_checkpoints_steps == 0 and global_step > start_save_steps and count != 0: # eval & save model
194 | logger.info("***** Running evaluation *****")
195 | model.eval()
196 | metrics = evaluate(args, model, device, eval_examples, eval_features, eval_dataloader, logger)
197 | f = open(log_path, "a")
198 | print("step: {}, loss: {:.4f}, P: {:.4f}, R: {:.4f}, F1: {:.4f} "
199 | "(common: {}, retrieved: {}, relevant: {})"
200 | .format(global_step, running_loss / count, metrics['p'], metrics['r'],
201 | metrics['f1'], metrics['common'], metrics['retrieved'], metrics['relevant']), file=f)
202 | print(" ", file=f)
203 | f.close()
204 | running_loss, count = 0.0, 0
205 | model.train()
206 | if metrics['f1'] > best_f1:
207 | best_f1 = metrics['f1']
208 | torch.save({
209 | 'model': model.state_dict(),
210 | 'optimizer': optimizer.state_dict(),
211 | 'step': global_step
212 | }, save_path)
213 | if args.debug:
214 | break
215 | return global_step, model, best_f1
216 |
217 | def metric_max_over_ground_truths(metric_fn, term, polarity, gold_terms, gold_polarities):
218 | hit = 0
219 | for gold_term, gold_polarity in zip(gold_terms, gold_polarities):
220 | score = metric_fn(term, gold_term)
221 | if score and polarity == gold_polarity:
222 | hit = 1
223 | return hit
224 |
225 | def eval_absa(all_examples, all_features, all_results, do_lower_case, verbose_logging, logger):
226 | unique_id_to_result = {}
227 | for result in all_results:
228 | unique_id_to_result[result.unique_id] = result
229 |
230 | all_nbest_json = collections.OrderedDict()
231 | common, relevant, retrieved = 0., 0., 0.
232 | for (feature_index, feature) in enumerate(all_features):
233 | example = all_examples[feature.example_index]
234 | result = unique_id_to_result[feature.unique_id]
235 |
236 | pred_terms = []
237 | pred_polarities = []
238 | for start_index, end_index, cls_pred, span_mask in \
239 | zip(result.start_indexes, result.end_indexes, result.cls_pred, result.span_masks):
240 | if span_mask:
241 | final_text = wrapped_get_final_text(example, feature, start_index, end_index,
242 | do_lower_case, verbose_logging, logger)
243 | pred_terms.append(final_text)
244 | pred_polarities.append(id_to_label[cls_pred])
245 |
246 | prediction = {'pred_terms': pred_terms, 'pred_polarities': pred_polarities}
247 | all_nbest_json[example.example_id] = prediction
248 |
249 | for term, polarity in zip(pred_terms, pred_polarities):
250 | common += metric_max_over_ground_truths(exact_match_score, term, polarity, example.term_texts, example.polarities)
251 | retrieved += len(pred_terms)
252 | relevant += len(example.term_texts)
253 | p = common / retrieved if retrieved > 0 else 0.
254 | r = common / relevant
255 | f1 = (2 * p * r) / (p + r) if p > 0 and r > 0 else 0.
256 | return {'p': p, 'r': r, 'f1': f1, 'common': common, 'retrieved': retrieved, 'relevant': relevant}, all_nbest_json
257 |
258 | def evaluate(args, model, device, eval_examples, eval_features, eval_dataloader, logger, write_pred=False):
259 | all_results = []
260 | for batch in eval_dataloader:
261 | batch = tuple(t.to(device) for t in batch)
262 | input_ids, input_mask, segment_ids, span_starts, span_ends, label_masks, example_indices = batch
263 | with torch.no_grad():
264 | cls_logits = model('inference', input_mask, input_ids=input_ids, token_type_ids=segment_ids,
265 | span_starts=span_starts, span_ends=span_ends)
266 |
267 | for j, example_index in enumerate(example_indices):
268 | cls_pred = cls_logits[j].detach().cpu().numpy().argmax(axis=1).tolist()
269 | start_indexes = span_starts[j].detach().cpu().tolist()
270 | end_indexes = span_ends[j].detach().cpu().tolist()
271 | span_masks = label_masks[j].detach().cpu().tolist()
272 | eval_feature = eval_features[example_index.item()]
273 | unique_id = int(eval_feature.unique_id)
274 | all_results.append(RawFinalResult(unique_id=unique_id, start_indexes=start_indexes,
275 | end_indexes=end_indexes, cls_pred=cls_pred, span_masks=span_masks))
276 |
277 | metrics, all_nbest_json = eval_absa(eval_examples, eval_features, all_results,
278 | args.do_lower_case, args.verbose_logging, logger)
279 |
280 | if write_pred:
281 | output_file = os.path.join(args.output_dir, "predictions.json")
282 | with open(output_file, "w") as writer:
283 | writer.write(json.dumps(all_nbest_json, indent=4) + "\n")
284 | logger.info("Writing predictions to: %s" % (output_file))
285 | return metrics
286 |
287 | def main():
288 | parser = argparse.ArgumentParser()
289 |
290 | ## Required parameters
291 | parser.add_argument("--bert_config_file", default=None, type=str, required=True,
292 | help="The config json file corresponding to the pre-trained BERT model. "
293 | "This specifies the model architecture.")
294 | parser.add_argument("--vocab_file", default=None, type=str, required=True,
295 | help="The vocabulary file that the BERT model was trained on.")
296 | parser.add_argument("--output_dir", default=None, type=str, required=True,
297 | help="The output directory where the model checkpoints will be written.")
298 |
299 | ## Other parameters
300 | parser.add_argument("--debug", default=False, action='store_true', help="Whether to run in debug mode.")
301 | parser.add_argument("--data_dir", default='data/semeval_14', type=str, help="SemEval data dir")
302 | parser.add_argument("--train_file", default=None, type=str, help="SemEval xml for training")
303 | parser.add_argument("--predict_file", default=None, type=str, help="SemEval csv for prediction")
304 | parser.add_argument("--extraction_file", default=None, type=str, help="pkl file for extraction")
305 | parser.add_argument("--init_checkpoint", default=None, type=str,
306 | help="Initial checkpoint (usually from a pre-trained BERT model).")
307 | parser.add_argument("--do_lower_case", default=True, action='store_true',
308 | help="Whether to lower case the input text. Should be True for uncased "
309 | "models and False for cased models.")
310 | parser.add_argument("--max_seq_length", default=96, type=int,
311 | help="The maximum total input sequence length after WordPiece tokenization. Sequences "
312 | "longer than this will be truncated, and sequences shorter than this will be padded.")
313 | parser.add_argument("--do_train", default=False, action='store_true', help="Whether to run training.")
314 | parser.add_argument("--do_predict", default=False, action='store_true', help="Whether to run eval on the dev set.")
315 | parser.add_argument("--do_pipeline", default=False, action='store_true', help="Whether to run pipeline on the dev set.")
316 | parser.add_argument("--train_batch_size", default=32, type=int, help="Total batch size for training.")
317 | parser.add_argument("--predict_batch_size", default=32, type=int, help="Total batch size for predictions.")
318 | parser.add_argument("--learning_rate", default=2e-5, type=float, help="The initial learning rate for Adam.")
319 | parser.add_argument("--num_train_epochs", default=3.0, type=float,
320 | help="Total number of training epochs to perform.")
321 | parser.add_argument("--warmup_proportion", default=0.1, type=float,
322 | help="Proportion of training to perform linear learning rate warmup for. E.g., 0.1 = 10% "
323 | "of training.")
324 | parser.add_argument("--save_proportion", default=0.5, type=float,
325 | help="Proportion of steps to save models for. E.g., 0.5 = 50% "
326 | "of training.")
327 | parser.add_argument("--verbose_logging", default=False, action='store_true',
328 | help="If true, all of the warnings related to data processing will be printed. "
329 | "A number of warnings are expected for a normal SQuAD evaluation.")
330 | parser.add_argument("--no_cuda",
331 | default=False,
332 | action='store_true',
333 | help="Whether not to use CUDA when available")
334 | parser.add_argument('--seed',
335 | type=int,
336 | default=42,
337 | help="random seed for initialization")
338 | parser.add_argument('--gradient_accumulation_steps',
339 | type=int,
340 | default=1,
341 | help="Number of updates steps to accumulate before performing a backward/update pass.")
342 | parser.add_argument("--local_rank",
343 | type=int,
344 | default=-1,
345 | help="local_rank for distributed training on gpus")
346 | parser.add_argument('--optimize_on_cpu',
347 | default=False,
348 | action='store_true',
349 | help="Whether to perform optimization and keep the optimizer averages on CPU")
350 | parser.add_argument('--fp16',
351 | default=False,
352 | action='store_true',
353 | help="Whether to use 16-bit float precision instead of 32-bit")
354 | parser.add_argument('--loss_scale',
355 | type=float, default=128,
356 | help='Loss scaling, positive power of 2 values can improve fp16 convergence.')
357 |
358 | args = parser.parse_args()
359 |
360 | if not args.do_train and not args.do_predict and not args.do_pipeline:
361 | raise ValueError("At least one of `do_train` or `do_predict` must be True.")
362 |
363 | if args.do_train and not args.train_file:
364 | raise ValueError(
365 | "If `do_train` is True, then `train_file` must be specified.")
366 | if args.do_predict and not args.predict_file:
367 | raise ValueError(
368 | "If `do_predict` is True, then `predict_file` must be specified.")
369 | if args.do_pipeline and not args.extraction_file:
370 | raise ValueError(
371 | "If `do_pipeline` is True, then `extraction_file` must be specified.")
372 |
373 | if args.local_rank == -1 or args.no_cuda:
374 | device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
375 | n_gpu = torch.cuda.device_count()
376 | else:
377 | device = torch.device("cuda", args.local_rank)
378 | n_gpu = 1
379 | # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
380 | torch.distributed.init_process_group(backend='nccl')
381 | if args.fp16:
382 | logger.info("16-bits training currently not supported in distributed training")
383 | args.fp16 = False # (see https://github.com/pytorch/pytorch/pull/13496)
384 | logger.info("torch_version: {} device: {} n_gpu: {}, distributed training: {}, 16-bits training: {}".format(
385 | torch.__version__, device, n_gpu, bool(args.local_rank != -1), args.fp16))
386 |
387 | if args.gradient_accumulation_steps < 1:
388 | raise ValueError("Invalid gradient_accumulation_steps parameter: {}, should be >= 1".format(
389 | args.gradient_accumulation_steps))
390 |
391 | random.seed(args.seed)
392 | np.random.seed(args.seed)
393 | torch.manual_seed(args.seed)
394 | if n_gpu > 0:
395 | torch.cuda.manual_seed_all(args.seed)
396 |
397 | bert_config = BertConfig.from_json_file(args.bert_config_file)
398 |
399 | if args.max_seq_length > bert_config.max_position_embeddings:
400 | raise ValueError(
401 | "Cannot use sequence length %d because the BERT model "
402 | "was only trained up to sequence length %d" %
403 | (args.max_seq_length, bert_config.max_position_embeddings))
404 |
405 | tokenizer = tokenization.FullTokenizer(
406 | vocab_file=args.vocab_file, do_lower_case=args.do_lower_case)
407 |
408 | if not os.path.exists(args.output_dir):
409 | os.makedirs(args.output_dir)
410 | logger.info('output_dir: {}'.format(args.output_dir))
411 | save_path = os.path.join(args.output_dir, 'checkpoint.pth.tar')
412 | log_path = os.path.join(args.output_dir, 'performance.txt')
413 | network_path = os.path.join(args.output_dir, 'network.txt')
414 | parameter_path = os.path.join(args.output_dir, 'parameter.txt')
415 |
416 | f = open(parameter_path, "w")
417 | for arg in sorted(vars(args)):
418 | print("{}: {}".format(arg, getattr(args, arg)), file=f)
419 | f.close()
420 |
421 | logger.info("***** Preparing model *****")
422 | model = BertForSpanAspectClassification(bert_config)
423 | if args.init_checkpoint is not None and not os.path.isfile(save_path):
424 | model = bert_load_state_dict(model, torch.load(args.init_checkpoint, map_location='cpu'))
425 | logger.info("Loading model from pretrained checkpoint: {}".format(args.init_checkpoint))
426 |
427 | if args.fp16:
428 | model.half()
429 | model.to(device)
430 | if args.local_rank != -1:
431 | model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank],
432 | output_device=args.local_rank)
433 | elif n_gpu > 1:
434 | model = torch.nn.DataParallel(model)
435 |
436 | if os.path.isfile(save_path):
437 | checkpoint = torch.load(save_path)
438 | model.load_state_dict(checkpoint['model'])
439 | step = checkpoint['step']
440 | logger.info("Loading model from finetuned checkpoint: '{}' (step {})"
441 | .format(save_path, step))
442 |
443 | f = open(network_path, "w")
444 | for n, param in model.named_parameters():
445 | print("name: {}, size: {}, dtype: {}, requires_grad: {}"
446 | .format(n, param.size(), param.dtype, param.requires_grad), file=f)
447 | total_trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
448 | total_params = sum(p.numel() for p in model.parameters())
449 | print("Total trainable parameters: {}".format(total_trainable_params), file=f)
450 | print("Total parameters: {}".format(total_params), file=f)
451 | f.close()
452 |
453 | logger.info("***** Preparing data *****")
454 | train_dataloader, num_train_steps = None, None
455 | eval_examples, eval_features, eval_dataloader = None, None, None
456 | args.train_batch_size = int(args.train_batch_size / args.gradient_accumulation_steps)
457 | if args.do_train:
458 | logger.info("***** Preparing training *****")
459 | train_dataloader, num_train_steps = read_train_data(args, tokenizer, logger)
460 | logger.info("***** Preparing evaluation *****")
461 | eval_examples, eval_features, eval_dataloader = read_eval_data(args, tokenizer, logger)
462 |
463 | logger.info("***** Preparing optimizer *****")
464 | optimizer, param_optimizer = prepare_optimizer(args, model, num_train_steps)
465 |
466 | global_step = 0
467 | if os.path.isfile(save_path):
468 | checkpoint = torch.load(save_path)
469 | optimizer.load_state_dict(checkpoint['optimizer'])
470 | step = checkpoint['step']
471 | logger.info("Loading optimizer from finetuned checkpoint: '{}' (step {})".format(save_path, step))
472 | global_step = step
473 |
474 | if args.do_train:
475 | logger.info("***** Running training *****")
476 | best_f1 = 0
477 | save_checkpoints_steps = int(num_train_steps / (5 * args.num_train_epochs))
478 | start_save_steps = int(num_train_steps * args.save_proportion)
479 | if args.debug:
480 | args.num_train_epochs = 1
481 | save_checkpoints_steps = 20
482 | start_save_steps = 0
483 | model.train()
484 | for epoch in range(int(args.num_train_epochs)):
485 | logger.info("***** Epoch: {} *****".format(epoch+1))
486 | global_step, model, best_f1 = run_train_epoch(args, global_step, model, param_optimizer,
487 | train_dataloader, eval_examples, eval_features,
488 | eval_dataloader,
489 | optimizer, n_gpu, device, logger, log_path, save_path,
490 | save_checkpoints_steps, start_save_steps, best_f1)
491 |
492 | if args.do_predict:
493 | logger.info("***** Running prediction *****")
494 | if eval_dataloader is None:
495 | eval_examples, eval_features, eval_dataloader = read_eval_data(args, tokenizer, logger)
496 |
497 | # restore from best checkpoint
498 | if save_path and os.path.isfile(save_path) and args.do_train:
499 | checkpoint = torch.load(save_path)
500 | model.load_state_dict(checkpoint['model'])
501 | step = checkpoint['step']
502 | logger.info("Loading model from finetuned checkpoint: '{}' (step {})"
503 | .format(save_path, step))
504 |
505 | model.eval()
506 | metrics = evaluate(args, model, device, eval_examples, eval_features, eval_dataloader, logger, write_pred=True)
507 | print("step: {}, P: {:.4f}, R: {:.4f}, F1: {:.4f} (common: {}, retrieved: {}, relevant: {})"
508 | .format(global_step, metrics['p'], metrics['r'],
509 | metrics['f1'], metrics['common'], metrics['retrieved'], metrics['relevant']))
510 |
511 | if args.do_pipeline:
512 | logger.info("***** Running prediction *****")
513 | eval_examples, eval_features, eval_dataloader = pipeline_eval_data(args, tokenizer, logger)
514 |
515 | # restore from best checkpoint
516 | if save_path and os.path.isfile(save_path) and args.do_train:
517 | checkpoint = torch.load(save_path)
518 | model.load_state_dict(checkpoint['model'])
519 | step = checkpoint['step']
520 | logger.info("Loading model from finetuned checkpoint: '{}' (step {})"
521 | .format(save_path, step))
522 |
523 | model.eval()
524 | metrics = evaluate(args, model, device, eval_examples, eval_features, eval_dataloader, logger, write_pred=True)
525 | f = open(log_path, "a")
526 | print("pipeline, step: {}, P: {:.4f}, R: {:.4f}, F1: {:.4f} (common: {}, retrieved: {}, relevant: {})"
527 | .format(global_step, metrics['p'], metrics['r'],
528 | metrics['f1'], metrics['common'], metrics['retrieved'], metrics['relevant']), file=f)
529 | print(" ", file=f)
530 | f.close()
531 |
532 |
533 | if __name__=='__main__':
534 | main()
535 |
--------------------------------------------------------------------------------
/absa/run_extract_span.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
3 | #
4 | # Licensed under the Apache License, Version 2.0 (the "License");
5 | # you may not use this file except in compliance with the License.
6 | # You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 | """Run BERT on SemEval."""
16 |
17 | from __future__ import absolute_import
18 | from __future__ import division
19 | from __future__ import print_function
20 |
21 | import sys
22 | import os
23 | import json
24 | import pickle
25 | import argparse
26 | import collections
27 |
28 | import numpy as np
29 | import torch
30 | from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
31 | from torch.utils.data.distributed import DistributedSampler
32 |
33 | import bert.tokenization as tokenization
34 | from bert.modeling import BertConfig
35 | from bert.sentiment_modeling import BertForSpanAspectExtraction
36 |
37 | from squad.squad_evaluate import exact_match_score, metric_max_over_ground_truths
38 | from absa.utils import read_absa_data, convert_absa_data, convert_examples_to_features, RawFinalResult, RawSpanResult, \
39 | span_annotate_candidates, wrapped_get_final_text
40 | from absa.run_base import copy_optimizer_params_to_model, set_optimizer_params_grad, prepare_optimizer, post_process_loss, bert_load_state_dict
41 |
42 | try:
43 | import xml.etree.ElementTree as ET, getopt, logging, sys, random, re, copy
44 | from xml.sax.saxutils import escape
45 | except:
46 | sys.exit('Some package is missing... Perhaps ?')
47 |
48 | logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
49 | datefmt = '%m/%d/%Y %H:%M:%S',
50 | level = logging.INFO)
51 | logger = logging.getLogger(__name__)
52 |
53 | def read_train_data(args, tokenizer, logger):
54 | train_path = os.path.join(args.data_dir, args.train_file)
55 | train_set = read_absa_data(train_path)
56 | train_examples = convert_absa_data(dataset=train_set, verbose_logging=args.verbose_logging)
57 |
58 | train_features = convert_examples_to_features(train_examples, tokenizer, args.max_seq_length,
59 | args.verbose_logging, logger)
60 |
61 | num_train_steps = int(
62 | len(train_features) / args.train_batch_size / args.gradient_accumulation_steps * args.num_train_epochs)
63 | logger.info("Num orig examples = %d", len(train_examples))
64 | logger.info("Num split features = %d", len(train_features))
65 | logger.info("Batch size = %d", args.train_batch_size)
66 | logger.info("Num steps = %d", num_train_steps)
67 | all_input_ids = torch.tensor([f.input_ids for f in train_features], dtype=torch.long)
68 | all_input_mask = torch.tensor([f.input_mask for f in train_features], dtype=torch.long)
69 | all_segment_ids = torch.tensor([f.segment_ids for f in train_features], dtype=torch.long)
70 | all_start_positions = torch.tensor([f.start_positions for f in train_features], dtype=torch.long)
71 | all_end_positions = torch.tensor([f.end_positions for f in train_features], dtype=torch.long)
72 |
73 | train_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_start_positions, all_end_positions)
74 | if args.local_rank == -1:
75 | train_sampler = RandomSampler(train_data)
76 | else:
77 | train_sampler = DistributedSampler(train_data)
78 | train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=args.train_batch_size)
79 | return train_dataloader, num_train_steps
80 |
81 | def read_eval_data(args, tokenizer, logger):
82 | eval_path = os.path.join(args.data_dir, args.predict_file)
83 | eval_set = read_absa_data(eval_path)
84 | eval_examples = convert_absa_data(dataset=eval_set, verbose_logging=args.verbose_logging)
85 |
86 | eval_features = convert_examples_to_features(eval_examples, tokenizer, args.max_seq_length,
87 | args.verbose_logging, logger)
88 |
89 | logger.info("Num orig examples = %d", len(eval_examples))
90 | logger.info("Num split features = %d", len(eval_features))
91 | logger.info("Batch size = %d", args.predict_batch_size)
92 | all_input_ids = torch.tensor([f.input_ids for f in eval_features], dtype=torch.long)
93 | all_input_mask = torch.tensor([f.input_mask for f in eval_features], dtype=torch.long)
94 | all_segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long)
95 | all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long)
96 | eval_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_example_index)
97 | if args.local_rank == -1:
98 | eval_sampler = SequentialSampler(eval_data)
99 | else:
100 | eval_sampler = DistributedSampler(eval_data)
101 | eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.predict_batch_size)
102 | return eval_examples, eval_features, eval_dataloader
103 |
104 | def run_train_epoch(args, global_step, model, param_optimizer, train_dataloader,
105 | eval_examples, eval_features, eval_dataloader,
106 | optimizer, n_gpu, device, logger, log_path, save_path,
107 | save_checkpoints_steps, start_save_steps, best_f1):
108 | running_loss, count = 0.0, 0
109 | for step, batch in enumerate(train_dataloader):
110 | if n_gpu == 1:
111 | batch = tuple(t.to(device) for t in batch) # multi-gpu does scattering it-self
112 | input_ids, input_mask, segment_ids, start_positions, end_positions = batch
113 | loss = model(input_ids, segment_ids, input_mask, start_positions, end_positions)
114 | loss = post_process_loss(args, n_gpu, loss)
115 | loss.backward()
116 | running_loss += loss.item()
117 |
118 | if (step + 1) % args.gradient_accumulation_steps == 0:
119 | if args.fp16 or args.optimize_on_cpu:
120 | if args.fp16 and args.loss_scale != 1.0:
121 | # scale down gradients for fp16 training
122 | for param in model.parameters():
123 | param.grad.data = param.grad.data / args.loss_scale
124 | is_nan = set_optimizer_params_grad(param_optimizer, model.named_parameters(), test_nan=True)
125 | if is_nan:
126 | logger.info("FP16 TRAINING: Nan in gradients, reducing loss scaling")
127 | args.loss_scale = args.loss_scale / 2
128 | model.zero_grad()
129 | continue
130 | optimizer.step()
131 | copy_optimizer_params_to_model(model.named_parameters(), param_optimizer)
132 | else:
133 | optimizer.step()
134 | model.zero_grad()
135 | global_step += 1
136 | count += 1
137 |
138 | if global_step % save_checkpoints_steps == 0 and count != 0:
139 | logger.info("step: {}, loss: {:.4f}".format(global_step, running_loss / count))
140 |
141 | if global_step % save_checkpoints_steps == 0 and global_step > start_save_steps and count != 0: # eval & save model
142 | logger.info("***** Running evaluation *****")
143 | model.eval()
144 | metrics = evaluate(args, model, device, eval_examples, eval_features, eval_dataloader, logger)
145 | f = open(log_path, "a")
146 | print("step: {}, loss: {:.4f}, P: {:.4f}, R: {:.4f}, F1: {:.4f} (common: {}, retrieved: {}, relevant: {})"
147 | .format(global_step, running_loss / count, metrics['p'], metrics['r'],
148 | metrics['f1'], metrics['common'], metrics['retrieved'], metrics['relevant']), file=f)
149 | print(" ", file=f)
150 | f.close()
151 | running_loss, count = 0.0, 0
152 | model.train()
153 | if metrics['f1'] > best_f1:
154 | best_f1 = metrics['f1']
155 | torch.save({
156 | 'model': model.state_dict(),
157 | 'optimizer': optimizer.state_dict(),
158 | 'step': global_step
159 | }, save_path)
160 | if args.debug:
161 | break
162 | return global_step, model, best_f1
163 |
164 | def eval_aspect_extract(all_examples, all_features, all_results, do_lower_case, verbose_logging, logger):
165 | unique_id_to_result = {}
166 | for result in all_results:
167 | unique_id_to_result[result.unique_id] = result
168 |
169 | all_nbest_json = collections.OrderedDict()
170 | common, relevant, retrieved = 0., 0., 0.
171 | for (feature_index, feature) in enumerate(all_features):
172 | example = all_examples[feature.example_index]
173 | result = unique_id_to_result[feature.unique_id]
174 |
175 | pred_terms = []
176 | for start_index, end_index, span_mask in zip(result.start_indexes, result.end_indexes, result.span_masks):
177 | if span_mask:
178 | final_text = wrapped_get_final_text(example, feature, start_index, end_index,
179 | do_lower_case, verbose_logging, logger)
180 | pred_terms.append(final_text)
181 |
182 | prediction = {'pred': pred_terms, 'gold': example.term_texts}
183 | all_nbest_json[example.example_id] = prediction
184 |
185 | for pred_term in pred_terms:
186 | common += metric_max_over_ground_truths(exact_match_score, pred_term, example.term_texts)
187 | retrieved += len(pred_terms)
188 | relevant += len(example.term_texts)
189 | p = common / retrieved if retrieved > 0 else 0.
190 | r = common / relevant
191 | f1 = (2 * p * r) / (p + r) if p > 0 and r > 0 else 0.
192 |
193 | return {'p': p, 'r': r, 'f1': f1, 'common': common, 'retrieved': retrieved, 'relevant': relevant}, all_nbest_json
194 |
195 | def evaluate(args, model, device, eval_examples, eval_features, eval_dataloader, logger, write_pred=False, do_pipeline=False):
196 | all_results = []
197 | for batch in eval_dataloader:
198 | batch = tuple(t.to(device) for t in batch)
199 | input_ids, input_mask, segment_ids, example_indices = batch
200 | with torch.no_grad():
201 | batch_start_logits, batch_end_logits = model(input_ids, segment_ids, input_mask)
202 |
203 | batch_features, batch_results = [], []
204 | for j, example_index in enumerate(example_indices):
205 | start_logits = batch_start_logits[j].detach().cpu().tolist()
206 | end_logits = batch_end_logits[j].detach().cpu().tolist()
207 | eval_feature = eval_features[example_index.item()]
208 | unique_id = int(eval_feature.unique_id)
209 | batch_features.append(eval_feature)
210 | batch_results.append(RawSpanResult(unique_id=unique_id, start_logits=start_logits, end_logits=end_logits))
211 |
212 | span_starts, span_ends, _, label_masks = span_annotate_candidates(eval_examples, batch_features, batch_results,
213 | args.filter_type, False,
214 | args.use_heuristics, args.use_nms,
215 | args.logit_threshold, args.n_best_size,
216 | args.max_answer_length, args.do_lower_case,
217 | args.verbose_logging, logger)
218 |
219 | for j, example_index in enumerate(example_indices):
220 | start_indexes = span_starts[j]
221 | end_indexes = span_ends[j]
222 | span_masks = label_masks[j]
223 | eval_feature = eval_features[example_index.item()]
224 | unique_id = int(eval_feature.unique_id)
225 | all_results.append(RawFinalResult(unique_id=unique_id, start_indexes=start_indexes,
226 | end_indexes=end_indexes, cls_pred=None, span_masks=span_masks))
227 |
228 | metrics, all_nbest_json = eval_aspect_extract(eval_examples, eval_features, all_results,
229 | args.do_lower_case, args.verbose_logging, logger)
230 | if write_pred:
231 | output_file = os.path.join(args.output_dir, "predictions.json")
232 | with open(output_file, "w") as writer:
233 | writer.write(json.dumps(all_nbest_json, indent=4) + "\n")
234 | logger.info("Writing predictions to: %s" % (output_file))
235 | if do_pipeline:
236 | output_file = os.path.join(args.output_dir, "extraction_results.pkl")
237 | pickle.dump(all_results, open(output_file, 'wb'))
238 | return metrics
239 |
240 |
241 | def main():
242 | parser = argparse.ArgumentParser()
243 |
244 | ## Required parameters
245 | parser.add_argument("--bert_config_file", default=None, type=str, required=True,
246 | help="The config json file corresponding to the pre-trained BERT model. "
247 | "This specifies the model architecture.")
248 | parser.add_argument("--vocab_file", default=None, type=str, required=True,
249 | help="The vocabulary file that the BERT model was trained on.")
250 | parser.add_argument("--output_dir", default=None, type=str, required=True,
251 | help="The output directory where the model checkpoints will be written.")
252 |
253 | ## Other parameters
254 | parser.add_argument("--debug", default=False, action='store_true', help="Whether to run in debug mode.")
255 | parser.add_argument("--data_dir", default='data/semeval_14', type=str, help="SemEval data dir")
256 | parser.add_argument("--train_file", default=None, type=str, help="SemEval xml for training")
257 | parser.add_argument("--predict_file", default=None, type=str, help="SemEval csv for prediction")
258 | parser.add_argument("--init_checkpoint", default=None, type=str,
259 | help="Initial checkpoint (usually from a pre-trained BERT model).")
260 | parser.add_argument("--do_lower_case", default=True, action='store_true',
261 | help="Whether to lower case the input text. Should be True for uncased "
262 | "models and False for cased models.")
263 | parser.add_argument("--max_seq_length", default=96, type=int,
264 | help="The maximum total input sequence length after WordPiece tokenization. Sequences "
265 | "longer than this will be truncated, and sequences shorter than this will be padded.")
266 | parser.add_argument("--do_train", default=False, action='store_true', help="Whether to run training.")
267 | parser.add_argument("--do_predict", default=False, action='store_true', help="Whether to run eval on the dev set.")
268 | parser.add_argument("--do_pipeline", default=False, action='store_true', help="Whether to run pipeline on the dev set.")
269 | parser.add_argument("--train_batch_size", default=32, type=int, help="Total batch size for training.")
270 | parser.add_argument("--predict_batch_size", default=32, type=int, help="Total batch size for predictions.")
271 | parser.add_argument("--learning_rate", default=2e-5, type=float, help="The initial learning rate for Adam.")
272 | parser.add_argument("--num_train_epochs", default=3.0, type=float, help="Total number of training epochs to perform.")
273 | parser.add_argument("--warmup_proportion", default=0.1, type=float,
274 | help="Proportion of training to perform linear learning rate warmup for. E.g., 0.1 = 10% "
275 | "of training.")
276 | parser.add_argument("--save_proportion", default=0.5, type=float,
277 | help="Proportion of steps to save models for. E.g., 0.5 = 50% of training.")
278 | parser.add_argument("--n_best_size", default=20, type=int,
279 | help="The total number of n-best predictions to generate in the nbest_predictions.json "
280 | "output file.")
281 | parser.add_argument("--max_answer_length", default=12, type=int,
282 | help="The maximum length of an answer that can be generated. This is needed because the start "
283 | "and end predictions are not conditioned on one another.")
284 | parser.add_argument("--logit_threshold", default=7.5, type=float,
285 | help="Logit threshold for annotating labels.")
286 | parser.add_argument("--filter_type", default="f1", type=str, help="Which filter type to use")
287 | parser.add_argument("--use_heuristics", default=True, action='store_true',
288 | help="If true, use heuristic regularization on span length")
289 | parser.add_argument("--use_nms", default=True, action='store_true',
290 | help="If true, use nms to prune redundant spans")
291 | parser.add_argument("--verbose_logging", default=False, action='store_true',
292 | help="If true, all of the warnings related to data processing will be printed. "
293 | "A number of warnings are expected for a normal SQuAD evaluation.")
294 | parser.add_argument("--no_cuda",
295 | default=False,
296 | action='store_true',
297 | help="Whether not to use CUDA when available")
298 | parser.add_argument('--seed',
299 | type=int,
300 | default=42,
301 | help="random seed for initialization")
302 | parser.add_argument('--gradient_accumulation_steps',
303 | type=int,
304 | default=1,
305 | help="Number of updates steps to accumulate before performing a backward/update pass.")
306 | parser.add_argument("--local_rank",
307 | type=int,
308 | default=-1,
309 | help="local_rank for distributed training on gpus")
310 | parser.add_argument('--optimize_on_cpu',
311 | default=False,
312 | action='store_true',
313 | help="Whether to perform optimization and keep the optimizer averages on CPU")
314 | parser.add_argument('--fp16',
315 | default=False,
316 | action='store_true',
317 | help="Whether to use 16-bit float precision instead of 32-bit")
318 | parser.add_argument('--loss_scale',
319 | type=float, default=128,
320 | help='Loss scaling, positive power of 2 values can improve fp16 convergence.')
321 |
322 | args = parser.parse_args()
323 |
324 | if not args.do_train and not args.do_predict and not args.do_pipeline:
325 | raise ValueError("At least one of `do_train` or `do_predict` must be True.")
326 |
327 | if args.do_train and not args.train_file:
328 | raise ValueError(
329 | "If `do_train` is True, then `train_file` must be specified.")
330 | if args.do_predict and not args.predict_file:
331 | raise ValueError(
332 | "If `do_predict` is True, then `predict_file` must be specified.")
333 |
334 | if args.local_rank == -1 or args.no_cuda:
335 | device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
336 | n_gpu = torch.cuda.device_count()
337 | else:
338 | device = torch.device("cuda", args.local_rank)
339 | n_gpu = 1
340 | # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
341 | torch.distributed.init_process_group(backend='nccl')
342 | if args.fp16:
343 | logger.info("16-bits training currently not supported in distributed training")
344 | args.fp16 = False # (see https://github.com/pytorch/pytorch/pull/13496)
345 | logger.info("torch_version: {} device: {} n_gpu: {}, distributed training: {}, 16-bits training: {}".format(
346 | torch.__version__, device, n_gpu, bool(args.local_rank != -1), args.fp16))
347 |
348 | if args.gradient_accumulation_steps < 1:
349 | raise ValueError("Invalid gradient_accumulation_steps parameter: {}, should be >= 1".format(
350 | args.gradient_accumulation_steps))
351 |
352 | random.seed(args.seed)
353 | np.random.seed(args.seed)
354 | torch.manual_seed(args.seed)
355 | if n_gpu > 0:
356 | torch.cuda.manual_seed_all(args.seed)
357 |
358 | bert_config = BertConfig.from_json_file(args.bert_config_file)
359 |
360 | if args.max_seq_length > bert_config.max_position_embeddings:
361 | raise ValueError(
362 | "Cannot use sequence length %d because the BERT model "
363 | "was only trained up to sequence length %d" %
364 | (args.max_seq_length, bert_config.max_position_embeddings))
365 |
366 | tokenizer = tokenization.FullTokenizer(
367 | vocab_file=args.vocab_file, do_lower_case=args.do_lower_case)
368 |
369 | if not os.path.exists(args.output_dir):
370 | os.makedirs(args.output_dir)
371 | logger.info('output_dir: {}'.format(args.output_dir))
372 | save_path = os.path.join(args.output_dir, 'checkpoint.pth.tar')
373 | log_path = os.path.join(args.output_dir, 'performance.txt')
374 | network_path = os.path.join(args.output_dir, 'network.txt')
375 | parameter_path = os.path.join(args.output_dir, 'parameter.txt')
376 |
377 | f = open(parameter_path, "w")
378 | for arg in sorted(vars(args)):
379 | print("{}: {}".format(arg, getattr(args, arg)), file=f)
380 | f.close()
381 |
382 | logger.info("***** Preparing model *****")
383 | model = BertForSpanAspectExtraction(bert_config)
384 | if args.init_checkpoint is not None and not os.path.isfile(save_path):
385 | model = bert_load_state_dict(model, torch.load(args.init_checkpoint, map_location='cpu'))
386 | logger.info("Loading model from pretrained checkpoint: {}".format(args.init_checkpoint))
387 |
388 | if args.fp16:
389 | model.half()
390 | model.to(device)
391 | if args.local_rank != -1:
392 | model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank],
393 | output_device=args.local_rank)
394 | elif n_gpu > 1:
395 | model = torch.nn.DataParallel(model)
396 |
397 | if os.path.isfile(save_path):
398 | checkpoint = torch.load(save_path)
399 | model.load_state_dict(checkpoint['model'])
400 | step = checkpoint['step']
401 | logger.info("Loading model from finetuned checkpoint: '{}' (step {})"
402 | .format(save_path, step))
403 |
404 | f = open(network_path, "w")
405 | for n, param in model.named_parameters():
406 | print("name: {}, size: {}, dtype: {}, requires_grad: {}"
407 | .format(n, param.size(), param.dtype, param.requires_grad), file=f)
408 | total_trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
409 | total_params = sum(p.numel() for p in model.parameters())
410 | print("Total trainable parameters: {}".format(total_trainable_params), file=f)
411 | print("Total parameters: {}".format(total_params), file=f)
412 | f.close()
413 |
414 | logger.info("***** Preparing data *****")
415 | train_dataloader, num_train_steps = None, None
416 | eval_examples, eval_features, eval_dataloader = None, None, None
417 | args.train_batch_size = int(args.train_batch_size / args.gradient_accumulation_steps)
418 | if args.do_train:
419 | logger.info("***** Preparing training *****")
420 | train_dataloader, num_train_steps = read_train_data(args, tokenizer, logger)
421 | logger.info("***** Preparing evaluation *****")
422 | eval_examples, eval_features, eval_dataloader = read_eval_data(args, tokenizer, logger)
423 |
424 | logger.info("***** Preparing optimizer *****")
425 | optimizer, param_optimizer = prepare_optimizer(args, model, num_train_steps)
426 |
427 | global_step = 0
428 | if os.path.isfile(save_path):
429 | checkpoint = torch.load(save_path)
430 | optimizer.load_state_dict(checkpoint['optimizer'])
431 | step = checkpoint['step']
432 | logger.info("Loading optimizer from finetuned checkpoint: '{}' (step {})".format(save_path, step))
433 | global_step = step
434 |
435 | if args.do_train:
436 | logger.info("***** Running training *****")
437 | best_f1 = 0
438 | save_checkpoints_steps = int(num_train_steps / (5 * args.num_train_epochs))
439 | start_save_steps = int(num_train_steps * args.save_proportion)
440 | if args.debug:
441 | args.num_train_epochs = 1
442 | save_checkpoints_steps = 20
443 | start_save_steps = 0
444 | model.train()
445 | for epoch in range(int(args.num_train_epochs)):
446 | logger.info("***** Epoch: {} *****".format(epoch+1))
447 | global_step, model, best_f1 = run_train_epoch(args, global_step, model, param_optimizer,
448 | train_dataloader, eval_examples, eval_features, eval_dataloader,
449 | optimizer, n_gpu, device, logger, log_path, save_path,
450 | save_checkpoints_steps, start_save_steps, best_f1)
451 |
452 | if args.do_predict:
453 | logger.info("***** Running prediction *****")
454 | if eval_dataloader is None:
455 | eval_examples, eval_features, eval_dataloader = read_eval_data(args, tokenizer, logger)
456 |
457 | # restore from best checkpoint
458 | if save_path and os.path.isfile(save_path) and args.do_train:
459 | checkpoint = torch.load(save_path)
460 | model.load_state_dict(checkpoint['model'])
461 | step = checkpoint['step']
462 | logger.info("Loading model from finetuned checkpoint: '{}' (step {})"
463 | .format(save_path, step))
464 |
465 | model.eval()
466 | metrics = evaluate(args, model, device, eval_examples, eval_features, eval_dataloader, logger, write_pred=True)
467 | f = open(log_path, "a")
468 | print("threshold: {}, step: {}, P: {:.4f}, R: {:.4f}, F1: {:.4f} (common: {}, retrieved: {}, relevant: {})"
469 | .format(args.logit_threshold, global_step, metrics['p'], metrics['r'],
470 | metrics['f1'], metrics['common'], metrics['retrieved'], metrics['relevant']), file=f)
471 | print(" ", file=f)
472 | f.close()
473 |
474 | if args.do_pipeline:
475 | logger.info("***** Running pipeline *****")
476 | if eval_dataloader is None:
477 | eval_examples, eval_features, eval_dataloader = read_eval_data(args, tokenizer, logger)
478 |
479 | # restore from best checkpoint
480 | if save_path and os.path.isfile(save_path) and args.do_train:
481 | checkpoint = torch.load(save_path)
482 | model.load_state_dict(checkpoint['model'])
483 | step = checkpoint['step']
484 | logger.info("Loading model from finetuned checkpoint: '{}' (step {})"
485 | .format(save_path, step))
486 |
487 | model.eval()
488 | metrics = evaluate(args, model, device, eval_examples, eval_features, eval_dataloader, logger, write_pred=True,
489 | do_pipeline=True)
490 | print("step: {}, P: {:.4f}, R: {:.4f}, F1: {:.4f} (common: {}, retrieved: {}, relevant: {})"
491 | .format(global_step, metrics['p'], metrics['r'],
492 | metrics['f1'], metrics['common'], metrics['retrieved'], metrics['relevant']))
493 |
494 |
495 | if __name__=='__main__':
496 | main()
497 |
498 |
499 |
500 |
501 |
502 |
503 |
504 |
505 |
506 |
507 |
508 |
--------------------------------------------------------------------------------
/absa/run_joint_span.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
3 | #
4 | # Licensed under the Apache License, Version 2.0 (the "License");
5 | # you may not use this file except in compliance with the License.
6 | # You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 | """Run BERT on SemEval."""
16 |
17 | from __future__ import absolute_import
18 | from __future__ import division
19 | from __future__ import print_function
20 |
21 | import sys
22 | import os
23 | import json
24 | import argparse
25 |
26 | import numpy as np
27 | import torch
28 | from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
29 | from torch.utils.data.distributed import DistributedSampler
30 |
31 | import bert.tokenization as tokenization
32 | from bert.modeling import BertConfig
33 | from bert.sentiment_modeling import BertForJointSpanExtractAndClassification
34 |
35 | from absa.utils import read_absa_data, convert_absa_data, convert_examples_to_features, RawFinalResult, RawSpanResult, span_annotate_candidates
36 | from absa.run_base import copy_optimizer_params_to_model, set_optimizer_params_grad, prepare_optimizer, post_process_loss, bert_load_state_dict
37 | from absa.run_cls_span import eval_absa
38 |
39 | try:
40 | import xml.etree.ElementTree as ET, getopt, logging, sys, random, re, copy
41 | from xml.sax.saxutils import escape
42 | except:
43 | sys.exit('Some package is missing... Perhaps ?')
44 |
45 | logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
46 | datefmt = '%m/%d/%Y %H:%M:%S',
47 | level = logging.INFO)
48 | logger = logging.getLogger(__name__)
49 |
50 | def read_train_data(args, tokenizer, logger):
51 | train_path = os.path.join(args.data_dir, args.train_file)
52 | train_set = read_absa_data(train_path)
53 | train_examples = convert_absa_data(dataset=train_set, verbose_logging=args.verbose_logging)
54 | train_features = convert_examples_to_features(train_examples, tokenizer, args.max_seq_length,
55 | args.verbose_logging, logger)
56 |
57 | num_train_steps = int(
58 | len(train_features) / args.train_batch_size / args.gradient_accumulation_steps * args.num_train_epochs)
59 | logger.info("Num orig examples = %d", len(train_examples))
60 | logger.info("Num split features = %d", len(train_features))
61 | logger.info("Batch size = %d", args.train_batch_size)
62 | logger.info("Num steps = %d", num_train_steps)
63 | all_input_ids = torch.tensor([f.input_ids for f in train_features], dtype=torch.long)
64 | all_input_mask = torch.tensor([f.input_mask for f in train_features], dtype=torch.long)
65 | all_segment_ids = torch.tensor([f.segment_ids for f in train_features], dtype=torch.long)
66 | all_start_positions = torch.tensor([f.start_positions for f in train_features], dtype=torch.long)
67 | all_end_positions = torch.tensor([f.end_positions for f in train_features], dtype=torch.long)
68 | all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long)
69 |
70 | train_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_start_positions, all_end_positions, all_example_index)
71 | if args.local_rank == -1:
72 | train_sampler = RandomSampler(train_data)
73 | else:
74 | train_sampler = DistributedSampler(train_data)
75 | train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=args.train_batch_size)
76 | return train_examples, train_features, train_dataloader, num_train_steps
77 |
78 | def read_eval_data(args, tokenizer, logger):
79 | eval_path = os.path.join(args.data_dir, args.predict_file)
80 | eval_set = read_absa_data(eval_path)
81 | eval_examples = convert_absa_data(dataset=eval_set, verbose_logging=args.verbose_logging)
82 |
83 | eval_features = convert_examples_to_features(eval_examples, tokenizer, args.max_seq_length,
84 | args.verbose_logging, logger)
85 |
86 | logger.info("Num orig examples = %d", len(eval_examples))
87 | logger.info("Num split features = %d", len(eval_features))
88 | logger.info("Batch size = %d", args.predict_batch_size)
89 | all_input_ids = torch.tensor([f.input_ids for f in eval_features], dtype=torch.long)
90 | all_input_mask = torch.tensor([f.input_mask for f in eval_features], dtype=torch.long)
91 | all_segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long)
92 | all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long)
93 | eval_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_example_index)
94 | if args.local_rank == -1:
95 | eval_sampler = SequentialSampler(eval_data)
96 | else:
97 | eval_sampler = DistributedSampler(eval_data)
98 | eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.predict_batch_size)
99 | return eval_examples, eval_features, eval_dataloader
100 |
101 | def run_train_epoch(args, global_step, model, param_optimizer,
102 | train_examples, train_features, train_dataloader,
103 | eval_examples, eval_features, eval_dataloader,
104 | optimizer, n_gpu, device, logger, log_path, save_path,
105 | save_checkpoints_steps, start_save_steps, best_f1):
106 | running_loss, count = 0.0, 0
107 | for step, batch in enumerate(train_dataloader):
108 | if n_gpu == 1:
109 | batch = tuple(t.to(device) for t in batch) # multi-gpu does scattering it-self
110 | input_ids, input_mask, segment_ids, start_positions, end_positions, example_indices = batch
111 | batch_start_logits, batch_end_logits, _ = model('extract_inference', input_mask, input_ids=input_ids, token_type_ids=segment_ids)
112 |
113 | batch_features, batch_results = [], []
114 | for j, example_index in enumerate(example_indices):
115 | start_logits = batch_start_logits[j].detach().cpu().tolist()
116 | end_logits = batch_end_logits[j].detach().cpu().tolist()
117 | train_feature = train_features[example_index.item()]
118 | unique_id = int(train_feature.unique_id)
119 | batch_features.append(train_feature)
120 | batch_results.append(RawSpanResult(unique_id=unique_id, start_logits=start_logits, end_logits=end_logits))
121 |
122 | span_starts, span_ends, labels, label_masks = span_annotate_candidates(train_examples, batch_features,
123 | batch_results,
124 | args.filter_type, True,
125 | args.use_heuristics,
126 | args.use_nms,
127 | args.logit_threshold,
128 | args.n_best_size,
129 | args.max_answer_length,
130 | args.do_lower_case,
131 | args.verbose_logging, logger)
132 |
133 | span_starts = torch.tensor(span_starts, dtype=torch.long)
134 | span_ends = torch.tensor(span_ends, dtype=torch.long)
135 | labels = torch.tensor(labels, dtype=torch.long)
136 | label_masks = torch.tensor(label_masks, dtype=torch.long)
137 | span_starts = span_starts.to(device)
138 | span_ends = span_ends.to(device)
139 | labels = labels.to(device)
140 | label_masks = label_masks.to(device)
141 |
142 | loss = model('train', input_mask, input_ids=input_ids, token_type_ids=segment_ids,
143 | start_positions=start_positions, end_positions=end_positions,
144 | span_starts=span_starts, span_ends=span_ends,
145 | polarity_labels=labels, label_masks=label_masks)
146 | loss = post_process_loss(args, n_gpu, loss)
147 | loss.backward()
148 | running_loss += loss.item()
149 |
150 | if (step + 1) % args.gradient_accumulation_steps == 0:
151 | if args.fp16 or args.optimize_on_cpu:
152 | if args.fp16 and args.loss_scale != 1.0:
153 | # scale down gradients for fp16 training
154 | for param in model.parameters():
155 | param.grad.data = param.grad.data / args.loss_scale
156 | is_nan = set_optimizer_params_grad(param_optimizer, model.named_parameters(), test_nan=True)
157 | if is_nan:
158 | logger.info("FP16 TRAINING: Nan in gradients, reducing loss scaling")
159 | args.loss_scale = args.loss_scale / 2
160 | model.zero_grad()
161 | continue
162 | optimizer.step()
163 | copy_optimizer_params_to_model(model.named_parameters(), param_optimizer)
164 | else:
165 | optimizer.step()
166 | model.zero_grad()
167 | global_step += 1
168 | count += 1
169 |
170 | if global_step % save_checkpoints_steps == 0 and count != 0:
171 | logger.info("step: {}, loss: {:.4f}".format(global_step, running_loss / count))
172 |
173 | if global_step % save_checkpoints_steps == 0 and global_step > start_save_steps and count != 0: # eval & save model
174 | logger.info("***** Running evaluation *****")
175 | model.eval()
176 | metrics = evaluate(args, model, device, eval_examples, eval_features, eval_dataloader, logger)
177 | f = open(log_path, "a")
178 | print("step: {}, loss: {:.4f}, P: {:.4f}, R: {:.4f}, F1: {:.4f} (common: {}, retrieved: {}, relevant: {})"
179 | .format(global_step, running_loss / count, metrics['p'], metrics['r'],
180 | metrics['f1'], metrics['common'], metrics['retrieved'], metrics['relevant']), file=f)
181 | print(" ", file=f)
182 | f.close()
183 | running_loss, count = 0.0, 0
184 | model.train()
185 | if metrics['f1'] > best_f1:
186 | best_f1 = metrics['f1']
187 | torch.save({
188 | 'model': model.state_dict(),
189 | 'optimizer': optimizer.state_dict(),
190 | 'step': global_step
191 | }, save_path)
192 | if args.debug:
193 | break
194 | return global_step, model, best_f1
195 |
196 |
197 | def evaluate(args, model, device, eval_examples, eval_features, eval_dataloader, logger, write_pred=False):
198 | all_results = []
199 | for batch in eval_dataloader:
200 | batch = tuple(t.to(device) for t in batch)
201 | input_ids, input_mask, segment_ids, example_indices = batch
202 | with torch.no_grad():
203 | batch_start_logits, batch_end_logits, sequence_output = model('extract_inference', input_mask,
204 | input_ids=input_ids,
205 | token_type_ids=segment_ids)
206 |
207 | batch_features, batch_results = [], []
208 | for j, example_index in enumerate(example_indices):
209 | start_logits = batch_start_logits[j].detach().cpu().tolist()
210 | end_logits = batch_end_logits[j].detach().cpu().tolist()
211 | eval_feature = eval_features[example_index.item()]
212 | unique_id = int(eval_feature.unique_id)
213 | batch_features.append(eval_feature)
214 | batch_results.append(RawSpanResult(unique_id=unique_id, start_logits=start_logits, end_logits=end_logits))
215 |
216 | span_starts, span_ends, _, label_masks = span_annotate_candidates(eval_examples, batch_features, batch_results,
217 | args.filter_type, False,
218 | args.use_heuristics, args.use_nms,
219 | args.logit_threshold, args.n_best_size,
220 | args.max_answer_length, args.do_lower_case,
221 | args.verbose_logging, logger)
222 |
223 | span_starts = torch.tensor(span_starts, dtype=torch.long)
224 | span_ends = torch.tensor(span_ends, dtype=torch.long)
225 | span_starts = span_starts.to(device)
226 | span_ends = span_ends.to(device)
227 | sequence_output = sequence_output.to(device)
228 | with torch.no_grad():
229 | batch_ac_logits = model('classify_inference', input_mask, span_starts=span_starts,
230 | span_ends=span_ends, sequence_input=sequence_output) # [N, M, 4]
231 |
232 | for j, example_index in enumerate(example_indices):
233 | cls_pred = batch_ac_logits[j].detach().cpu().numpy().argmax(axis=1).tolist()
234 | start_indexes = span_starts[j].detach().cpu().tolist()
235 | end_indexes = span_ends[j].detach().cpu().tolist()
236 | span_masks = label_masks[j]
237 | eval_feature = eval_features[example_index.item()]
238 | unique_id = int(eval_feature.unique_id)
239 | all_results.append(RawFinalResult(unique_id=unique_id, start_indexes=start_indexes,
240 | end_indexes=end_indexes, cls_pred=cls_pred, span_masks=span_masks))
241 |
242 | metrics, all_nbest_json = eval_absa(eval_examples, eval_features, all_results,
243 | args.do_lower_case, args.verbose_logging, logger)
244 | if write_pred:
245 | output_file = os.path.join(args.output_dir, "predictions.json")
246 | with open(output_file, "w") as writer:
247 | writer.write(json.dumps(all_nbest_json, indent=4) + "\n")
248 | logger.info("Writing predictions to: %s" % (output_file))
249 | return metrics
250 |
251 |
252 | def main():
253 | parser = argparse.ArgumentParser()
254 |
255 | ## Required parameters
256 | parser.add_argument("--bert_config_file", default=None, type=str, required=True,
257 | help="The config json file corresponding to the pre-trained BERT model. "
258 | "This specifies the model architecture.")
259 | parser.add_argument("--vocab_file", default=None, type=str, required=True,
260 | help="The vocabulary file that the BERT model was trained on.")
261 | parser.add_argument("--output_dir", default=None, type=str, required=True,
262 | help="The output directory where the model checkpoints will be written.")
263 |
264 | ## Other parameters
265 | parser.add_argument("--debug", default=False, action='store_true', help="Whether to run in debug mode.")
266 | parser.add_argument("--data_dir", default='data/semeval_14', type=str, help="SemEval data dir")
267 | parser.add_argument("--train_file", default=None, type=str, help="SemEval xml for training")
268 | parser.add_argument("--predict_file", default=None, type=str, help="SemEval csv for prediction")
269 | parser.add_argument("--init_checkpoint", default=None, type=str,
270 | help="Initial checkpoint (usually from a pre-trained BERT model).")
271 | parser.add_argument("--do_lower_case", default=True, action='store_true',
272 | help="Whether to lower case the input text. Should be True for uncased "
273 | "models and False for cased models.")
274 | parser.add_argument("--max_seq_length", default=96, type=int,
275 | help="The maximum total input sequence length after WordPiece tokenization. Sequences "
276 | "longer than this will be truncated, and sequences shorter than this will be padded.")
277 | parser.add_argument("--do_train", default=False, action='store_true', help="Whether to run training.")
278 | parser.add_argument("--do_predict", default=False, action='store_true', help="Whether to run eval on the dev set.")
279 | parser.add_argument("--train_batch_size", default=32, type=int, help="Total batch size for training.")
280 | parser.add_argument("--predict_batch_size", default=32, type=int, help="Total batch size for predictions.")
281 | parser.add_argument("--learning_rate", default=2e-5, type=float, help="The initial learning rate for Adam.")
282 | parser.add_argument("--num_train_epochs", default=3.0, type=float, help="Total number of training epochs to perform.")
283 | parser.add_argument("--warmup_proportion", default=0.1, type=float,
284 | help="Proportion of training to perform linear learning rate warmup for. E.g., 0.1 = 10% "
285 | "of training.")
286 | parser.add_argument("--save_proportion", default=0.5, type=float,
287 | help="Proportion of steps to save models for. E.g., 0.5 = 50% of training.")
288 | parser.add_argument("--n_best_size", default=20, type=int,
289 | help="The total number of n-best predictions to generate in the nbest_predictions.json "
290 | "output file.")
291 | parser.add_argument("--max_answer_length", default=12, type=int,
292 | help="The maximum length of an answer that can be generated. This is needed because the start "
293 | "and end predictions are not conditioned on one another.")
294 | parser.add_argument("--logit_threshold", default=8., type=float,
295 | help="Logit threshold for annotating labels.")
296 | parser.add_argument("--filter_type", default="f1", type=str, help="Which filter type to use")
297 | parser.add_argument("--use_heuristics", default=True, action='store_true',
298 | help="If true, use heuristic regularization on span length")
299 | parser.add_argument("--use_nms", default=True, action='store_true',
300 | help="If true, use nms to prune redundant spans")
301 | parser.add_argument("--verbose_logging", default=False, action='store_true',
302 | help="If true, all of the warnings related to data processing will be printed. "
303 | "A number of warnings are expected for a normal SQuAD evaluation.")
304 | parser.add_argument("--no_cuda",
305 | default=False,
306 | action='store_true',
307 | help="Whether not to use CUDA when available")
308 | parser.add_argument('--seed',
309 | type=int,
310 | default=42,
311 | help="random seed for initialization")
312 | parser.add_argument('--gradient_accumulation_steps',
313 | type=int,
314 | default=1,
315 | help="Number of updates steps to accumulate before performing a backward/update pass.")
316 | parser.add_argument("--local_rank",
317 | type=int,
318 | default=-1,
319 | help="local_rank for distributed training on gpus")
320 | parser.add_argument('--optimize_on_cpu',
321 | default=False,
322 | action='store_true',
323 | help="Whether to perform optimization and keep the optimizer averages on CPU")
324 | parser.add_argument('--fp16',
325 | default=False,
326 | action='store_true',
327 | help="Whether to use 16-bit float precision instead of 32-bit")
328 | parser.add_argument('--loss_scale',
329 | type=float, default=128,
330 | help='Loss scaling, positive power of 2 values can improve fp16 convergence.')
331 |
332 | args = parser.parse_args()
333 |
334 | if not args.do_train and not args.do_predict:
335 | raise ValueError("At least one of `do_train` or `do_predict` must be True.")
336 |
337 | if args.do_train and not args.train_file:
338 | raise ValueError(
339 | "If `do_train` is True, then `train_file` must be specified.")
340 | if args.do_predict and not args.predict_file:
341 | raise ValueError(
342 | "If `do_predict` is True, then `predict_file` must be specified.")
343 |
344 | if args.local_rank == -1 or args.no_cuda:
345 | device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
346 | n_gpu = torch.cuda.device_count()
347 | else:
348 | device = torch.device("cuda", args.local_rank)
349 | n_gpu = 1
350 | # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
351 | torch.distributed.init_process_group(backend='nccl')
352 | if args.fp16:
353 | logger.info("16-bits training currently not supported in distributed training")
354 | args.fp16 = False # (see https://github.com/pytorch/pytorch/pull/13496)
355 | logger.info("torch_version: {} device: {} n_gpu: {}, distributed training: {}, 16-bits training: {}".format(
356 | torch.__version__, device, n_gpu, bool(args.local_rank != -1), args.fp16))
357 |
358 | if args.gradient_accumulation_steps < 1:
359 | raise ValueError("Invalid gradient_accumulation_steps parameter: {}, should be >= 1".format(
360 | args.gradient_accumulation_steps))
361 |
362 | random.seed(args.seed)
363 | np.random.seed(args.seed)
364 | torch.manual_seed(args.seed)
365 | if n_gpu > 0:
366 | torch.cuda.manual_seed_all(args.seed)
367 |
368 | bert_config = BertConfig.from_json_file(args.bert_config_file)
369 |
370 | if args.max_seq_length > bert_config.max_position_embeddings:
371 | raise ValueError(
372 | "Cannot use sequence length %d because the BERT model "
373 | "was only trained up to sequence length %d" %
374 | (args.max_seq_length, bert_config.max_position_embeddings))
375 |
376 | tokenizer = tokenization.FullTokenizer(
377 | vocab_file=args.vocab_file, do_lower_case=args.do_lower_case)
378 |
379 | if not os.path.exists(args.output_dir):
380 | os.makedirs(args.output_dir)
381 | logger.info('output_dir: {}'.format(args.output_dir))
382 | save_path = os.path.join(args.output_dir, 'checkpoint.pth.tar')
383 | log_path = os.path.join(args.output_dir, 'performance.txt')
384 | network_path = os.path.join(args.output_dir, 'network.txt')
385 | parameter_path = os.path.join(args.output_dir, 'parameter.txt')
386 |
387 | f = open(parameter_path, "w")
388 | for arg in sorted(vars(args)):
389 | print("{}: {}".format(arg, getattr(args, arg)), file=f)
390 | f.close()
391 |
392 | logger.info("***** Preparing model *****")
393 | model = BertForJointSpanExtractAndClassification(bert_config)
394 | if args.init_checkpoint is not None and not os.path.isfile(save_path):
395 | model = bert_load_state_dict(model, torch.load(args.init_checkpoint, map_location='cpu'))
396 | logger.info("Loading model from pretrained checkpoint: {}".format(args.init_checkpoint))
397 |
398 | if args.fp16:
399 | model.half()
400 | model.to(device)
401 | if args.local_rank != -1:
402 | model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank],
403 | output_device=args.local_rank)
404 | elif n_gpu > 1:
405 | model = torch.nn.DataParallel(model)
406 |
407 | if os.path.isfile(save_path):
408 | checkpoint = torch.load(save_path)
409 | model.load_state_dict(checkpoint['model'])
410 | step = checkpoint['step']
411 | logger.info("Loading model from finetuned checkpoint: '{}' (step {})"
412 | .format(save_path, step))
413 |
414 | f = open(network_path, "w")
415 | for n, param in model.named_parameters():
416 | print("name: {}, size: {}, dtype: {}, requires_grad: {}"
417 | .format(n, param.size(), param.dtype, param.requires_grad), file=f)
418 | total_trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
419 | total_params = sum(p.numel() for p in model.parameters())
420 | print("Total trainable parameters: {}".format(total_trainable_params), file=f)
421 | print("Total parameters: {}".format(total_params), file=f)
422 | f.close()
423 |
424 | logger.info("***** Preparing data *****")
425 | train_examples, train_features, train_dataloader, num_train_steps = None, None, None, None
426 | eval_examples, eval_features, eval_dataloader = None, None, None
427 | args.train_batch_size = int(args.train_batch_size / args.gradient_accumulation_steps)
428 | if args.do_train:
429 | logger.info("***** Preparing training *****")
430 | train_examples, train_features, train_dataloader, num_train_steps = read_train_data(args, tokenizer, logger)
431 | logger.info("***** Preparing evaluation *****")
432 | eval_examples, eval_features, eval_dataloader = read_eval_data(args, tokenizer, logger)
433 |
434 | logger.info("***** Preparing optimizer *****")
435 | optimizer, param_optimizer = prepare_optimizer(args, model, num_train_steps)
436 |
437 | global_step = 0
438 | if os.path.isfile(save_path):
439 | checkpoint = torch.load(save_path)
440 | optimizer.load_state_dict(checkpoint['optimizer'])
441 | step = checkpoint['step']
442 | logger.info("Loading optimizer from finetuned checkpoint: '{}' (step {})".format(save_path, step))
443 | global_step = step
444 |
445 | if args.do_train:
446 | logger.info("***** Running training *****")
447 | best_f1 = 0
448 | save_checkpoints_steps = int(num_train_steps / (5 * args.num_train_epochs))
449 | start_save_steps = int(num_train_steps * args.save_proportion)
450 | if args.debug:
451 | args.num_train_epochs = 1
452 | save_checkpoints_steps = 20
453 | start_save_steps = 0
454 | model.train()
455 | for epoch in range(int(args.num_train_epochs)):
456 | logger.info("***** Epoch: {} *****".format(epoch+1))
457 | global_step, model, best_f1 = run_train_epoch(args, global_step, model, param_optimizer,
458 | train_examples, train_features, train_dataloader,
459 | eval_examples, eval_features, eval_dataloader,
460 | optimizer, n_gpu, device, logger, log_path, save_path,
461 | save_checkpoints_steps, start_save_steps, best_f1)
462 |
463 | if args.do_predict:
464 | logger.info("***** Running prediction *****")
465 | if eval_dataloader is None:
466 | eval_examples, eval_features, eval_dataloader = read_eval_data(args, tokenizer, logger)
467 |
468 | # restore from best checkpoint
469 | if save_path and os.path.isfile(save_path) and args.do_train:
470 | checkpoint = torch.load(save_path)
471 | model.load_state_dict(checkpoint['model'])
472 | step = checkpoint['step']
473 | logger.info("Loading model from finetuned checkpoint: '{}' (step {})"
474 | .format(save_path, step))
475 |
476 | model.eval()
477 | metrics = evaluate(args, model, device, eval_examples, eval_features, eval_dataloader, logger, write_pred=True)
478 | f = open(log_path, "a")
479 | print("threshold: {}, step: {}, P: {:.4f}, R: {:.4f}, F1: {:.4f} (common: {}, retrieved: {}, relevant: {})"
480 | .format(args.logit_threshold, global_step, metrics['p'], metrics['r'],
481 | metrics['f1'], metrics['common'], metrics['retrieved'], metrics['relevant']), file=f)
482 | print(" ", file=f)
483 | f.close()
484 |
485 | if __name__=='__main__':
486 | main()
--------------------------------------------------------------------------------
/absa/utils.py:
--------------------------------------------------------------------------------
1 | import json
2 | import collections
3 | import numpy as np
4 |
5 | import bert.tokenization as tokenization
6 | from squad.squad_utils import get_final_text, _get_best_indexes
7 | from squad.squad_evaluate import exact_match_score, f1_score
8 |
9 | label_to_id = {'other': 0, 'neutral': 1, 'positive': 2, 'negative': 3, 'conflict': 4}
10 | id_to_label = {0: 'other', 1: 'neutral', 2: 'positive', 3: 'negative', 4: 'conflict'}
11 |
12 |
13 | class SemEvalExample(object):
14 | def __init__(self,
15 | example_id,
16 | sent_tokens,
17 | term_texts=None,
18 | start_positions=None,
19 | end_positions=None,
20 | polarities=None):
21 | self.example_id = example_id
22 | self.sent_tokens = sent_tokens
23 | self.term_texts = term_texts
24 | self.start_positions = start_positions
25 | self.end_positions = end_positions
26 | self.polarities = polarities
27 |
28 | def __str__(self):
29 | return self.__repr__()
30 |
31 | def __repr__(self):
32 | s = ""
33 | # s += "example_id: %s" % (tokenization.printable_text(self.example_id))
34 | s += ", sent_tokens: [%s]" % (" ".join(self.sent_tokens))
35 | if self.term_texts:
36 | s += ", term_texts: {}".format(self.term_texts)
37 | # if self.start_positions:
38 | # s += ", start_positions: {}".format(self.start_positions)
39 | # if self.end_positions:
40 | # s += ", end_positions: {}".format(self.end_positions)
41 | if self.polarities:
42 | s += ", polarities: {}".format(self.polarities)
43 | return s
44 |
45 |
46 | class InputFeatures(object):
47 | """A single set of features of data."""
48 |
49 | def __init__(self,
50 | unique_id,
51 | example_index,
52 | tokens,
53 | token_to_orig_map,
54 | input_ids,
55 | input_mask,
56 | segment_ids,
57 | start_positions=None,
58 | end_positions=None,
59 | start_indexes=None,
60 | end_indexes=None,
61 | bio_labels=None,
62 | polarity_positions=None,
63 | polarity_labels=None,
64 | label_masks=None):
65 | self.unique_id = unique_id
66 | self.example_index = example_index
67 | self.tokens = tokens
68 | self.token_to_orig_map = token_to_orig_map
69 | self.input_ids = input_ids
70 | self.input_mask = input_mask
71 | self.segment_ids = segment_ids
72 | self.start_positions = start_positions
73 | self.end_positions = end_positions
74 | self.start_indexes = start_indexes
75 | self.end_indexes = end_indexes
76 | self.bio_labels = bio_labels
77 | self.polarity_positions = polarity_positions
78 | self.polarity_labels = polarity_labels
79 | self.label_masks = label_masks
80 |
81 |
82 | def convert_examples_to_features(examples, tokenizer, max_seq_length, verbose_logging=False, logger=None):
83 | max_term_num = max([len(example.term_texts) for (example_index, example) in enumerate(examples)])
84 | max_sent_length, max_term_length = 0, 0
85 |
86 | unique_id = 1000000000
87 | features = []
88 | for (example_index, example) in enumerate(examples):
89 | tok_to_orig_index = []
90 | orig_to_tok_index = []
91 | all_doc_tokens = []
92 | for (i, token) in enumerate(example.sent_tokens):
93 | orig_to_tok_index.append(len(all_doc_tokens))
94 | sub_tokens = tokenizer.tokenize(token)
95 | for sub_token in sub_tokens:
96 | tok_to_orig_index.append(i)
97 | all_doc_tokens.append(sub_token)
98 | if len(all_doc_tokens) > max_sent_length:
99 | max_sent_length = len(all_doc_tokens)
100 |
101 | tok_start_positions = []
102 | tok_end_positions = []
103 | for start_position, end_position in \
104 | zip(example.start_positions, example.end_positions):
105 | tok_start_position = orig_to_tok_index[start_position]
106 | if end_position < len(example.sent_tokens) - 1:
107 | tok_end_position = orig_to_tok_index[end_position + 1] - 1
108 | else:
109 | tok_end_position = len(all_doc_tokens) - 1
110 | tok_start_positions.append(tok_start_position)
111 | tok_end_positions.append(tok_end_position)
112 |
113 | # Account for [CLS] and [SEP] with "- 2"
114 | if len(all_doc_tokens) > max_seq_length - 2:
115 | all_doc_tokens = all_doc_tokens[0:(max_seq_length - 2)]
116 |
117 | tokens = []
118 | token_to_orig_map = {}
119 | segment_ids = []
120 | tokens.append("[CLS]")
121 | segment_ids.append(0)
122 |
123 | for index, token in enumerate(all_doc_tokens):
124 | token_to_orig_map[len(tokens)] = tok_to_orig_index[index]
125 | tokens.append(token)
126 | segment_ids.append(0)
127 | tokens.append("[SEP]")
128 | segment_ids.append(0)
129 |
130 | input_ids = tokenizer.convert_tokens_to_ids(tokens)
131 | input_mask = [1] * len(input_ids)
132 |
133 | while len(input_ids) < max_seq_length:
134 | input_ids.append(0)
135 | input_mask.append(0)
136 | segment_ids.append(0)
137 |
138 | assert len(input_ids) == max_seq_length
139 | assert len(input_mask) == max_seq_length
140 | assert len(segment_ids) == max_seq_length
141 |
142 | # For distant supervision, we annotate the positions of all answer spans
143 | start_positions = [0] * len(input_ids)
144 | end_positions = [0] * len(input_ids)
145 | bio_labels = [0] * len(input_ids)
146 | polarity_positions = [0] * len(input_ids)
147 | start_indexes, end_indexes = [], []
148 | for tok_start_position, tok_end_position, polarity in zip(tok_start_positions, tok_end_positions, example.polarities):
149 | if (tok_start_position >= 0 and tok_end_position <= (max_seq_length - 1)):
150 | start_position = tok_start_position + 1 # [CLS]
151 | end_position = tok_end_position + 1 # [CLS]
152 | start_positions[start_position] = 1
153 | end_positions[end_position] = 1
154 | start_indexes.append(start_position)
155 | end_indexes.append(end_position)
156 | term_length = tok_end_position - tok_start_position + 1
157 | max_term_length = term_length if term_length > max_term_length else max_term_length
158 | bio_labels[start_position] = 1 # 'B'
159 | if start_position < end_position:
160 | for idx in range(start_position + 1, end_position + 1):
161 | bio_labels[idx] = 2 # 'I'
162 | for idx in range(start_position, end_position + 1):
163 | polarity_positions[idx] = label_to_id[polarity]
164 |
165 | polarity_labels = [label_to_id[polarity] for polarity in example.polarities]
166 | label_masks = [1] * len(polarity_labels)
167 |
168 | while len(start_indexes) < max_term_num:
169 | start_indexes.append(0)
170 | end_indexes.append(0)
171 | polarity_labels.append(0)
172 | label_masks.append(0)
173 |
174 | assert len(start_indexes) == max_term_num
175 | assert len(end_indexes) == max_term_num
176 | assert len(polarity_labels) == max_term_num
177 | assert len(label_masks) == max_term_num
178 |
179 | if example_index < 1 and verbose_logging:
180 | logger.info("*** Example ***")
181 | logger.info("unique_id: %s" % (unique_id))
182 | logger.info("example_index: %s" % (example_index))
183 | logger.info("tokens: {}".format(tokens))
184 | logger.info("token_to_orig_map: {}".format(token_to_orig_map))
185 | logger.info("start_indexes: {}".format(start_indexes))
186 | logger.info("end_indexes: {}".format(end_indexes))
187 | logger.info("bio_labels: {}".format(bio_labels))
188 | logger.info("polarity_positions: {}".format(polarity_positions))
189 | logger.info("polarity_labels: {}".format(polarity_labels))
190 |
191 | features.append(
192 | InputFeatures(
193 | unique_id=unique_id,
194 | example_index=example_index,
195 | tokens=tokens,
196 | token_to_orig_map=token_to_orig_map,
197 | input_ids=input_ids,
198 | input_mask=input_mask,
199 | segment_ids=segment_ids,
200 | start_positions=start_positions,
201 | end_positions=end_positions,
202 | start_indexes=start_indexes,
203 | end_indexes=end_indexes,
204 | bio_labels=bio_labels,
205 | polarity_positions=polarity_positions,
206 | polarity_labels=polarity_labels,
207 | label_masks=label_masks))
208 | unique_id += 1
209 | logger.info("Max sentence length: {}".format(max_sent_length))
210 | logger.info("Max term length: {}".format(max_term_length))
211 | logger.info("Max term num: {}".format(max_term_num))
212 | return features
213 |
214 |
215 | RawSpanResult = collections.namedtuple("RawSpanResult",
216 | ["unique_id", "start_logits", "end_logits"])
217 |
218 | RawSpanCollapsedResult = collections.namedtuple("RawSpanCollapsedResult",
219 | ["unique_id", "neu_start_logits", "neu_end_logits", "pos_start_logits", "pos_end_logits",
220 | "neg_start_logits", "neg_end_logits"])
221 |
222 | RawBIOResult = collections.namedtuple("RawBIOResult", ["unique_id", "bio_pred"])
223 |
224 | RawBIOClsResult = collections.namedtuple("RawBIOClsResult", ["unique_id", "start_indexes", "end_indexes", "bio_pred", "span_masks"])
225 |
226 | RawFinalResult = collections.namedtuple("RawFinalResult",
227 | ["unique_id", "start_indexes", "end_indexes", "cls_pred", "span_masks"])
228 |
229 |
230 | def wrapped_get_final_text(example, feature, start_index, end_index, do_lower_case, verbose_logging, logger):
231 | tok_tokens = feature.tokens[start_index:(end_index + 1)]
232 | orig_doc_start = feature.token_to_orig_map[start_index]
233 | orig_doc_end = feature.token_to_orig_map[end_index]
234 | orig_tokens = example.sent_tokens[orig_doc_start:(orig_doc_end + 1)]
235 | tok_text = " ".join(tok_tokens)
236 |
237 | # De-tokenize WordPieces that have been split off.
238 | tok_text = tok_text.replace(" ##", "")
239 | tok_text = tok_text.replace("##", "")
240 |
241 | # Clean whitespace
242 | tok_text = tok_text.strip()
243 | tok_text = " ".join(tok_text.split())
244 | orig_text = " ".join(orig_tokens)
245 |
246 | final_text = get_final_text(tok_text, orig_text, do_lower_case, verbose_logging, logger)
247 | return final_text
248 |
249 |
250 | def span_annotate_candidates(all_examples, batch_features, batch_results, filter_type, is_training, use_heuristics, use_nms,
251 | logit_threshold, n_best_size, max_answer_length, do_lower_case, verbose_logging, logger):
252 | """Annotate top-k candidate answers into features."""
253 | unique_id_to_result = {}
254 | for result in batch_results:
255 | unique_id_to_result[result.unique_id] = result
256 |
257 | _PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name
258 | "PrelimPrediction",
259 | ["feature_index", "start_index", "end_index", "start_logit", "end_logit"])
260 |
261 | batch_span_starts, batch_span_ends, batch_labels, batch_label_masks = [], [], [], []
262 | for (feature_index, feature) in enumerate(batch_features):
263 | example = all_examples[feature.example_index]
264 | result = unique_id_to_result[feature.unique_id]
265 |
266 | seen_predictions = {}
267 | span_starts, span_ends, labels, label_masks = [], [], [], []
268 | if is_training:
269 | # add ground-truth terms
270 | for start_index, end_index, polarity_label, mask in \
271 | zip(feature.start_indexes, feature.end_indexes, feature.polarity_labels, feature.label_masks):
272 | if mask and start_index in feature.token_to_orig_map and end_index in feature.token_to_orig_map:
273 | final_text = wrapped_get_final_text(example, feature, start_index, end_index,
274 | do_lower_case, verbose_logging, logger)
275 | if final_text in seen_predictions:
276 | continue
277 | seen_predictions[final_text] = True
278 |
279 | span_starts.append(start_index)
280 | span_ends.append(end_index)
281 | labels.append(polarity_label)
282 | label_masks.append(1)
283 | else:
284 | prelim_predictions_per_feature = []
285 | start_indexes = _get_best_indexes(result.start_logits, n_best_size)
286 | end_indexes = _get_best_indexes(result.end_logits, n_best_size)
287 | for start_index in start_indexes:
288 | for end_index in end_indexes:
289 | # We could hypothetically create invalid predictions, e.g., predict
290 | # that the start of the span is in the question. We throw out all
291 | # invalid predictions.
292 | if start_index >= len(feature.tokens):
293 | continue
294 | if end_index >= len(feature.tokens):
295 | continue
296 | if start_index not in feature.token_to_orig_map:
297 | continue
298 | if end_index not in feature.token_to_orig_map:
299 | continue
300 | if end_index < start_index:
301 | continue
302 | length = end_index - start_index + 1
303 | if length > max_answer_length:
304 | continue
305 | start_logit = result.start_logits[start_index]
306 | end_logit = result.end_logits[end_index]
307 | if start_logit + end_logit < logit_threshold:
308 | continue
309 |
310 | prelim_predictions_per_feature.append(
311 | _PrelimPrediction(
312 | feature_index=feature_index,
313 | start_index=start_index,
314 | end_index=end_index,
315 | start_logit=start_logit,
316 | end_logit=end_logit))
317 |
318 | if use_heuristics:
319 | prelim_predictions_per_feature = sorted(
320 | prelim_predictions_per_feature,
321 | key=lambda x: (x.start_logit + x.end_logit - (x.end_index - x.start_index + 1)),
322 | reverse=True)
323 | else:
324 | prelim_predictions_per_feature = sorted(
325 | prelim_predictions_per_feature,
326 | key=lambda x: (x.start_logit + x.end_logit),
327 | reverse=True)
328 |
329 | for i, pred_i in enumerate(prelim_predictions_per_feature):
330 | if len(span_starts) >= int(n_best_size)/2:
331 | break
332 | final_text = wrapped_get_final_text(example, feature, pred_i.start_index, pred_i.end_index,
333 | do_lower_case, verbose_logging, logger)
334 | if final_text in seen_predictions:
335 | continue
336 | seen_predictions[final_text] = True
337 |
338 | span_starts.append(pred_i.start_index)
339 | span_ends.append(pred_i.end_index)
340 | labels.append(0)
341 | label_masks.append(1)
342 |
343 | # filter out redundant candidates
344 | if (i+1) < len(prelim_predictions_per_feature) and use_nms:
345 | indexes = []
346 | for j, pred_j in enumerate(prelim_predictions_per_feature[(i+1):]):
347 | filter_text = wrapped_get_final_text(example, feature, pred_j.start_index, pred_j.end_index,
348 | do_lower_case, verbose_logging, logger)
349 | if filter_type == 'em':
350 | if exact_match_score(final_text, filter_text):
351 | indexes.append(i + j + 1)
352 | elif filter_type == 'f1':
353 | if f1_score(final_text, filter_text) > 0:
354 | indexes.append(i + j + 1)
355 | else:
356 | raise Exception
357 | [prelim_predictions_per_feature.pop(index - k) for k, index in enumerate(indexes)]
358 |
359 | # Pad to fixed length
360 | while len(span_starts) < int(n_best_size):
361 | span_starts.append(0)
362 | span_ends.append(0)
363 | labels.append(0)
364 | label_masks.append(0)
365 | assert len(span_starts) == int(n_best_size)
366 | assert len(span_ends) == int(n_best_size)
367 | assert len(labels) == int(n_best_size)
368 | assert len(label_masks) == int(n_best_size)
369 |
370 | batch_span_starts.append(span_starts)
371 | batch_span_ends.append(span_ends)
372 | batch_labels.append(labels)
373 | batch_label_masks.append(label_masks)
374 | return batch_span_starts, batch_span_ends, batch_labels, batch_label_masks
375 |
376 |
377 | def ts2start_end(ts_tag_sequence):
378 | starts, ends = [], []
379 | n_tag = len(ts_tag_sequence)
380 | prev_pos, prev_sentiment = '$$$', '$$$'
381 | tag_on = False
382 | for i in range(n_tag):
383 | cur_ts_tag = ts_tag_sequence[i]
384 | if cur_ts_tag != 'O':
385 | cur_pos, cur_sentiment = cur_ts_tag.split('-')
386 | else:
387 | cur_pos, cur_sentiment = 'O', '$$$'
388 | assert cur_pos == 'O' or cur_pos == 'T'
389 | if cur_pos == 'T':
390 | if prev_pos != 'T':
391 | # cur tag is at the beginning of the opinion target
392 | starts.append(i)
393 | tag_on = True
394 | else:
395 | if cur_sentiment != prev_sentiment:
396 | # prev sentiment is not equal to current sentiment
397 | ends.append(i - 1)
398 | starts.append(i)
399 | tag_on = True
400 | else:
401 | if prev_pos == 'T':
402 | ends.append(i - 1)
403 | tag_on = False
404 | prev_pos = cur_pos
405 | prev_sentiment = cur_sentiment
406 | if tag_on:
407 | ends.append(n_tag-1)
408 | assert len(starts) == len(ends), (len(starts), len(ends), ts_tag_sequence)
409 | return starts, ends
410 |
411 |
412 | def ts2polarity(words, ts_tag_sequence, starts, ends):
413 | polarities = []
414 | for start, end in zip(starts, ends):
415 | cur_ts_tag = ts_tag_sequence[start]
416 | cur_pos, cur_sentiment = cur_ts_tag.split('-')
417 | assert cur_pos == 'T'
418 | prev_sentiment = cur_sentiment
419 | if start < end:
420 | for idx in range(start, end + 1):
421 | cur_ts_tag = ts_tag_sequence[idx]
422 | cur_pos, cur_sentiment = cur_ts_tag.split('-')
423 | assert cur_pos == 'T'
424 | assert cur_sentiment == prev_sentiment, (words, ts_tag_sequence, start, end)
425 | prev_sentiment = cur_sentiment
426 | polarities.append(cur_sentiment)
427 | return polarities
428 |
429 |
430 | def pos2term(words, starts, ends):
431 | term_texts = []
432 | for start, end in zip(starts, ends):
433 | term_texts.append(' '.join(words[start:end+1]))
434 | return term_texts
435 |
436 |
437 | def convert_absa_data(dataset, verbose_logging=False):
438 | examples = []
439 | n_records = len(dataset)
440 | for i in range(n_records):
441 | words = dataset[i]['words']
442 | ts_tags = dataset[i]['ts_raw_tags']
443 | starts, ends = ts2start_end(ts_tags)
444 | polarities = ts2polarity(words, ts_tags, starts, ends)
445 | term_texts = pos2term(words, starts, ends)
446 |
447 | if term_texts != []:
448 | new_polarities = []
449 | for polarity in polarities:
450 | if polarity == 'POS':
451 | new_polarities.append('positive')
452 | elif polarity == 'NEG':
453 | new_polarities.append('negative')
454 | elif polarity == 'NEU':
455 | new_polarities.append('neutral')
456 | else:
457 | raise Exception
458 | assert len(term_texts) == len(starts)
459 | assert len(term_texts) == len(new_polarities)
460 | example = SemEvalExample(str(i), words, term_texts, starts, ends, new_polarities)
461 | examples.append(example)
462 | if i < 50 and verbose_logging:
463 | print(example)
464 | print("Convert %s examples" % len(examples))
465 | return examples
466 |
467 |
468 | def read_absa_data(path):
469 | """
470 | read data from the specified path
471 | :param path: path of dataset
472 | :return:
473 | """
474 | dataset = []
475 | with open(path, encoding='UTF-8') as fp:
476 | for line in fp:
477 | record = {}
478 | sent, tag_string = line.strip().split('####')
479 | record['sentence'] = sent
480 | word_tag_pairs = tag_string.split(' ')
481 | # tag sequence for targeted sentiment
482 | ts_tags = []
483 | # tag sequence for opinion target extraction
484 | ote_tags = []
485 | # word sequence
486 | words = []
487 | for item in word_tag_pairs:
488 | # valid label is: O, T-POS, T-NEG, T-NEU
489 | eles = item.split('=')
490 | if len(eles) == 2:
491 | word, tag = eles
492 | elif len(eles) > 2:
493 | tag = eles[-1]
494 | word = (len(eles) - 2) * "="
495 | words.append(word.lower())
496 | if tag == 'O':
497 | ote_tags.append('O')
498 | ts_tags.append('O')
499 | elif tag == 'T-POS':
500 | ote_tags.append('T')
501 | ts_tags.append('T-POS')
502 | elif tag == 'T-NEG':
503 | ote_tags.append('T')
504 | ts_tags.append('T-NEG')
505 | elif tag == 'T-NEU':
506 | ote_tags.append('T')
507 | ts_tags.append('T-NEU')
508 | else:
509 | raise Exception('Invalid tag %s!!!' % tag)
510 | record['words'] = words.copy()
511 | record['ote_raw_tags'] = ote_tags.copy()
512 | record['ts_raw_tags'] = ts_tags.copy()
513 | dataset.append(record)
514 | print("Obtain %s records from %s" % (len(dataset), path))
515 | return dataset
--------------------------------------------------------------------------------
/bert/modeling.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
3 | #
4 | # Licensed under the Apache License, Version 2.0 (the "License");
5 | # you may not use this file except in compliance with the License.
6 | # You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 | """PyTorch BERT model."""
16 |
17 | from __future__ import absolute_import
18 | from __future__ import division
19 | from __future__ import print_function
20 |
21 | import copy
22 | import json
23 | import math
24 | import six
25 | import torch
26 | import torch.nn as nn
27 | from torch.nn import CrossEntropyLoss
28 |
29 |
30 | def gelu(x):
31 | """Implementation of the gelu activation function.
32 | For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):
33 | 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
34 | """
35 | return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
36 |
37 |
38 | class BertConfig(object):
39 | """Configuration class to store the configuration of a `BertModel`.
40 | """
41 | def __init__(self,
42 | vocab_size,
43 | hidden_size=768,
44 | num_hidden_layers=12,
45 | num_attention_heads=12,
46 | intermediate_size=3072,
47 | hidden_act="gelu",
48 | hidden_dropout_prob=0.1,
49 | attention_probs_dropout_prob=0.1,
50 | max_position_embeddings=512,
51 | type_vocab_size=16,
52 | initializer_range=0.02):
53 | """Constructs BertConfig.
54 |
55 | Args:
56 | vocab_size: Vocabulary size of `inputs_ids` in `BertModel`.
57 | hidden_size: Size of the encoder layers and the pooler layer.
58 | num_hidden_layers: Number of hidden layers in the Transformer encoder.
59 | num_attention_heads: Number of attention heads for each attention layer in
60 | the Transformer encoder.
61 | intermediate_size: The size of the "intermediate" (i.e., feed-forward)
62 | layer in the Transformer encoder.
63 | hidden_act: The non-linear activation function (function or string) in the
64 | encoder and pooler.
65 | hidden_dropout_prob: The dropout probabilitiy for all fully connected
66 | layers in the embeddings, encoder, and pooler.
67 | attention_probs_dropout_prob: The dropout ratio for the attention
68 | probabilities.
69 | max_position_embeddings: The maximum sequence length that this model might
70 | ever be used with. Typically set this to something large just in case
71 | (e.g., 512 or 1024 or 2048).
72 | type_vocab_size: The vocabulary size of the `token_type_ids` passed into
73 | `BertModel`.
74 | initializer_range: The sttdev of the truncated_normal_initializer for
75 | initializing all weight matrices.
76 | """
77 | self.vocab_size = vocab_size
78 | self.hidden_size = hidden_size
79 | self.num_hidden_layers = num_hidden_layers
80 | self.num_attention_heads = num_attention_heads
81 | self.hidden_act = hidden_act
82 | self.intermediate_size = intermediate_size
83 | self.hidden_dropout_prob = hidden_dropout_prob
84 | self.attention_probs_dropout_prob = attention_probs_dropout_prob
85 | self.max_position_embeddings = max_position_embeddings
86 | self.type_vocab_size = type_vocab_size
87 | self.initializer_range = initializer_range
88 |
89 | @classmethod
90 | def from_dict(cls, json_object):
91 | """Constructs a `BertConfig` from a Python dictionary of parameters."""
92 | config = BertConfig(vocab_size=None)
93 | for (key, value) in six.iteritems(json_object):
94 | config.__dict__[key] = value
95 | return config
96 |
97 | @classmethod
98 | def from_json_file(cls, json_file):
99 | """Constructs a `BertConfig` from a json file of parameters."""
100 | with open(json_file, "r") as reader:
101 | text = reader.read()
102 | return cls.from_dict(json.loads(text))
103 |
104 | def to_dict(self):
105 | """Serializes this instance to a Python dictionary."""
106 | output = copy.deepcopy(self.__dict__)
107 | return output
108 |
109 | def to_json_string(self):
110 | """Serializes this instance to a JSON string."""
111 | return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"
112 |
113 |
114 | class BERTLayerNorm(nn.Module):
115 | def __init__(self, config, variance_epsilon=1e-12):
116 | """Construct a layernorm module in the TF style (epsilon inside the square root).
117 | """
118 | super(BERTLayerNorm, self).__init__()
119 | self.gamma = nn.Parameter(torch.ones(config.hidden_size))
120 | self.beta = nn.Parameter(torch.zeros(config.hidden_size))
121 | self.variance_epsilon = variance_epsilon
122 |
123 | def forward(self, x):
124 | u = x.mean(-1, keepdim=True)
125 | s = (x - u).pow(2).mean(-1, keepdim=True)
126 | x = (x - u) / torch.sqrt(s + self.variance_epsilon)
127 | return self.gamma * x + self.beta
128 |
129 |
130 | class BERTEmbeddings(nn.Module):
131 | def __init__(self, config):
132 | super(BERTEmbeddings, self).__init__()
133 | """Construct the embedding module from word, position and token_type embeddings.
134 | """
135 | self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
136 | self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
137 | self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
138 |
139 | # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
140 | # any TensorFlow checkpoint file
141 | self.LayerNorm = BERTLayerNorm(config)
142 | self.dropout = nn.Dropout(config.hidden_dropout_prob)
143 |
144 | def forward(self, input_ids, token_type_ids=None):
145 | seq_length = input_ids.size(1)
146 | position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device)
147 | position_ids = position_ids.unsqueeze(0).expand_as(input_ids)
148 | if token_type_ids is None:
149 | token_type_ids = torch.zeros_like(input_ids)
150 |
151 | words_embeddings = self.word_embeddings(input_ids)
152 | position_embeddings = self.position_embeddings(position_ids)
153 | token_type_embeddings = self.token_type_embeddings(token_type_ids)
154 |
155 | embeddings = words_embeddings + position_embeddings + token_type_embeddings
156 | embeddings = self.LayerNorm(embeddings)
157 | embeddings = self.dropout(embeddings)
158 | return embeddings
159 |
160 |
161 | class BERTSelfAttention(nn.Module):
162 | def __init__(self, config):
163 | super(BERTSelfAttention, self).__init__()
164 | if config.hidden_size % config.num_attention_heads != 0:
165 | raise ValueError(
166 | "The hidden size (%d) is not a multiple of the number of attention "
167 | "heads (%d)" % (config.hidden_size, config.num_attention_heads))
168 | self.num_attention_heads = config.num_attention_heads
169 | self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
170 | self.all_head_size = self.num_attention_heads * self.attention_head_size
171 |
172 | self.query = nn.Linear(config.hidden_size, self.all_head_size)
173 | self.key = nn.Linear(config.hidden_size, self.all_head_size)
174 | self.value = nn.Linear(config.hidden_size, self.all_head_size)
175 |
176 | self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
177 |
178 | def transpose_for_scores(self, x):
179 | new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
180 | x = x.view(*new_x_shape)
181 | return x.permute(0, 2, 1, 3)
182 |
183 | def forward(self, hidden_states, attention_mask):
184 | mixed_query_layer = self.query(hidden_states) # [N, L, H]
185 | mixed_key_layer = self.key(hidden_states)
186 | mixed_value_layer = self.value(hidden_states)
187 |
188 | query_layer = self.transpose_for_scores(mixed_query_layer) # [N, K, L, H//K]
189 | key_layer = self.transpose_for_scores(mixed_key_layer)
190 | value_layer = self.transpose_for_scores(mixed_value_layer)
191 |
192 | # Take the dot product between "query" and "key" to get the raw attention scores.
193 | attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) # [N, K, L, L]
194 | attention_scores = attention_scores / math.sqrt(self.attention_head_size)
195 | # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
196 | attention_scores = attention_scores + attention_mask
197 |
198 | # Normalize the attention scores to probabilities.
199 | attention_probs = nn.Softmax(dim=-1)(attention_scores)
200 |
201 | # This is actually dropping out entire tokens to attend to, which might
202 | # seem a bit unusual, but is taken from the original Transformer paper.
203 | attention_probs = self.dropout(attention_probs)
204 |
205 | context_layer = torch.matmul(attention_probs, value_layer) # [N, K, L, H//K]
206 | context_layer = context_layer.permute(0, 2, 1, 3).contiguous() # [N, L, K, H//K]
207 | new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
208 | context_layer = context_layer.view(*new_context_layer_shape) # [N, L, H]
209 | return context_layer
210 |
211 |
212 | class BERTSelfOutput(nn.Module):
213 | def __init__(self, config):
214 | super(BERTSelfOutput, self).__init__()
215 | self.dense = nn.Linear(config.hidden_size, config.hidden_size)
216 | self.LayerNorm = BERTLayerNorm(config)
217 | self.dropout = nn.Dropout(config.hidden_dropout_prob)
218 |
219 | def forward(self, hidden_states, input_tensor):
220 | hidden_states = self.dense(hidden_states)
221 | hidden_states = self.dropout(hidden_states)
222 | hidden_states = self.LayerNorm(hidden_states + input_tensor)
223 | return hidden_states
224 |
225 |
226 | class BERTAttention(nn.Module):
227 | def __init__(self, config):
228 | super(BERTAttention, self).__init__()
229 | self.self = BERTSelfAttention(config)
230 | self.output = BERTSelfOutput(config)
231 |
232 | def forward(self, input_tensor, attention_mask):
233 | self_output = self.self(input_tensor, attention_mask)
234 | attention_output = self.output(self_output, input_tensor)
235 | return attention_output
236 |
237 |
238 | class BERTIntermediate(nn.Module):
239 | def __init__(self, config):
240 | super(BERTIntermediate, self).__init__()
241 | self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
242 | self.intermediate_act_fn = gelu
243 |
244 | def forward(self, hidden_states):
245 | hidden_states = self.dense(hidden_states)
246 | hidden_states = self.intermediate_act_fn(hidden_states)
247 | return hidden_states
248 |
249 |
250 | class BERTOutput(nn.Module):
251 | def __init__(self, config):
252 | super(BERTOutput, self).__init__()
253 | self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
254 | self.LayerNorm = BERTLayerNorm(config)
255 | self.dropout = nn.Dropout(config.hidden_dropout_prob)
256 |
257 | def forward(self, hidden_states, input_tensor):
258 | hidden_states = self.dense(hidden_states)
259 | hidden_states = self.dropout(hidden_states)
260 | hidden_states = self.LayerNorm(hidden_states + input_tensor)
261 | return hidden_states
262 |
263 |
264 | class BERTLayer(nn.Module):
265 | def __init__(self, config):
266 | super(BERTLayer, self).__init__()
267 | self.attention = BERTAttention(config)
268 | self.intermediate = BERTIntermediate(config)
269 | self.output = BERTOutput(config)
270 |
271 | def forward(self, hidden_states, attention_mask):
272 | attention_output = self.attention(hidden_states, attention_mask)
273 | intermediate_output = self.intermediate(attention_output)
274 | layer_output = self.output(intermediate_output, attention_output)
275 | return layer_output
276 |
277 |
278 | class BERTEncoder(nn.Module):
279 | def __init__(self, config):
280 | super(BERTEncoder, self).__init__()
281 | layer = BERTLayer(config)
282 | self.layer = nn.ModuleList([copy.deepcopy(layer) for _ in range(config.num_hidden_layers)])
283 |
284 | def forward(self, hidden_states, attention_mask):
285 | all_encoder_layers = []
286 | for layer_module in self.layer:
287 | hidden_states = layer_module(hidden_states, attention_mask)
288 | all_encoder_layers.append(hidden_states)
289 | return all_encoder_layers
290 |
291 |
292 | class BERTPooler(nn.Module):
293 | def __init__(self, config):
294 | super(BERTPooler, self).__init__()
295 | self.dense = nn.Linear(config.hidden_size, config.hidden_size)
296 | self.activation = nn.Tanh()
297 |
298 | def forward(self, hidden_states):
299 | # We "pool" the model by simply taking the hidden state corresponding
300 | # to the first token.
301 | first_token_tensor = hidden_states[:, 0]
302 | pooled_output = self.dense(first_token_tensor)
303 | pooled_output = self.activation(pooled_output)
304 | return pooled_output
305 |
306 |
307 | class BertModel(nn.Module):
308 | """BERT model ("Bidirectional Embedding Representations from a Transformer").
309 |
310 | Example usage:
311 | ```python
312 | # Already been converted into WordPiece token ids
313 | input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
314 | input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
315 | token_type_ids = torch.LongTensor([[0, 0, 1], [0, 2, 0]])
316 |
317 | config = modeling.BertConfig(vocab_size=32000, hidden_size=512,
318 | num_hidden_layers=8, num_attention_heads=6, intermediate_size=1024)
319 |
320 | model = modeling.BertModel(config=config)
321 | all_encoder_layers, pooled_output = model(input_ids, token_type_ids, input_mask)
322 | ```
323 | """
324 | def __init__(self, config: BertConfig):
325 | """Constructor for BertModel.
326 |
327 | Args:
328 | config: `BertConfig` instance.
329 | """
330 | super(BertModel, self).__init__()
331 | self.embeddings = BERTEmbeddings(config)
332 | self.encoder = BERTEncoder(config)
333 | self.pooler = BERTPooler(config)
334 |
335 | def forward(self, input_ids, token_type_ids=None, attention_mask=None):
336 | if attention_mask is None:
337 | attention_mask = torch.ones_like(input_ids)
338 | if token_type_ids is None:
339 | token_type_ids = torch.zeros_like(input_ids)
340 |
341 | # We create a 3D attention mask from a 2D tensor mask.
342 | # Sizes are [batch_size, 1, 1, to_seq_length]
343 | # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
344 | # this attention mask is more simple than the triangular masking of causal attention
345 | # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
346 | extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
347 |
348 | # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
349 | # masked positions, this operation will create a tensor which is 0.0 for
350 | # positions we want to attend and -10000.0 for masked positions.
351 | # Since we are adding it to the raw scores before the softmax, this is
352 | # effectively the same as removing these entirely.
353 | extended_attention_mask = extended_attention_mask.to(dtype=next(self.parameters()).dtype) # fp16 compatibility
354 | extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
355 |
356 | embedding_output = self.embeddings(input_ids, token_type_ids)
357 | all_encoder_layers = self.encoder(embedding_output, extended_attention_mask)
358 | sequence_output = all_encoder_layers[-1]
359 | pooled_output = self.pooler(sequence_output)
360 | return all_encoder_layers, pooled_output
361 |
362 |
363 | class BertForSequenceClassification(nn.Module):
364 | """BERT model for classification.
365 | This module is composed of the BERT model with a linear layer on top of
366 | the pooled output.
367 |
368 | Example usage:
369 | ```python
370 | # Already been converted into WordPiece token ids
371 | input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
372 | input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
373 | token_type_ids = torch.LongTensor([[0, 0, 1], [0, 2, 0]])
374 |
375 | config = BertConfig(vocab_size=32000, hidden_size=512,
376 | num_hidden_layers=8, num_attention_heads=6, intermediate_size=1024)
377 |
378 | num_labels = 2
379 |
380 | model = BertForSequenceClassification(config, num_labels)
381 | logits = model(input_ids, token_type_ids, input_mask)
382 | ```
383 | """
384 | def __init__(self, config, num_labels):
385 | super(BertForSequenceClassification, self).__init__()
386 | self.bert = BertModel(config)
387 | self.dropout = nn.Dropout(config.hidden_dropout_prob)
388 | self.classifier = nn.Linear(config.hidden_size, num_labels)
389 |
390 | def init_weights(module):
391 | if isinstance(module, (nn.Linear, nn.Embedding)):
392 | # Slightly different from the TF version which uses truncated_normal for initialization
393 | # cf https://github.com/pytorch/pytorch/pull/5617
394 | module.weight.data.normal_(mean=0.0, std=config.initializer_range)
395 | elif isinstance(module, BERTLayerNorm):
396 | module.beta.data.normal_(mean=0.0, std=config.initializer_range)
397 | module.gamma.data.normal_(mean=0.0, std=config.initializer_range)
398 | if isinstance(module, nn.Linear):
399 | module.bias.data.zero_()
400 | self.apply(init_weights)
401 |
402 | def forward(self, input_ids, token_type_ids, attention_mask, labels=None):
403 | _, pooled_output = self.bert(input_ids, token_type_ids, attention_mask)
404 | pooled_output = self.dropout(pooled_output)
405 | logits = self.classifier(pooled_output)
406 |
407 | if labels is not None:
408 | loss_fct = CrossEntropyLoss()
409 | loss = loss_fct(logits, labels)
410 | return loss, logits
411 | else:
412 | return logits
413 |
414 |
415 | class BertForQuestionAnswering(nn.Module):
416 | """BERT model for Question Answering (span extraction).
417 | This module is composed of the BERT model with a linear layer on top of
418 | the sequence output that computes start_logits and end_logits
419 |
420 | Example usage:
421 | ```python
422 | # Already been converted into WordPiece token ids
423 | input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
424 | input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
425 | token_type_ids = torch.LongTensor([[0, 0, 1], [0, 2, 0]])
426 |
427 | config = BertConfig(vocab_size=32000, hidden_size=512,
428 | num_hidden_layers=8, num_attention_heads=6, intermediate_size=1024)
429 |
430 | model = BertForQuestionAnswering(config)
431 | start_logits, end_logits = model(input_ids, token_type_ids, input_mask)
432 | ```
433 | """
434 | def __init__(self, config):
435 | super(BertForQuestionAnswering, self).__init__()
436 | self.bert = BertModel(config)
437 | # TODO check with Google if it's normal there is no dropout on the token classifier of SQuAD in the TF version
438 | # self.dropout = nn.Dropout(config.hidden_dropout_prob)
439 | self.qa_outputs = nn.Linear(config.hidden_size, 2)
440 |
441 | def init_weights(module):
442 | if isinstance(module, (nn.Linear, nn.Embedding)):
443 | # Slightly different from the TF version which uses truncated_normal for initialization
444 | # cf https://github.com/pytorch/pytorch/pull/5617
445 | module.weight.data.normal_(mean=0.0, std=config.initializer_range)
446 | elif isinstance(module, BERTLayerNorm):
447 | module.beta.data.normal_(mean=0.0, std=config.initializer_range)
448 | module.gamma.data.normal_(mean=0.0, std=config.initializer_range)
449 | if isinstance(module, nn.Linear):
450 | module.bias.data.zero_()
451 | self.apply(init_weights)
452 |
453 | def forward(self, input_ids, token_type_ids, attention_mask, start_positions=None, end_positions=None):
454 | all_encoder_layers, _ = self.bert(input_ids, token_type_ids, attention_mask)
455 | sequence_output = all_encoder_layers[-1]
456 | logits = self.qa_outputs(sequence_output)
457 | start_logits, end_logits = logits.split(1, dim=-1)
458 | start_logits = start_logits.squeeze(-1)
459 | end_logits = end_logits.squeeze(-1)
460 |
461 | if start_positions is not None and end_positions is not None:
462 | # If we are on multi-GPU, split add a dimension
463 | if len(start_positions.size()) > 1:
464 | start_positions = start_positions.squeeze(-1)
465 | if len(end_positions.size()) > 1:
466 | end_positions = end_positions.squeeze(-1)
467 | # sometimes the start/end positions are outside our model inputs, we ignore these terms
468 | ignored_index = start_logits.size(1)
469 | start_positions.clamp_(0, ignored_index)
470 | end_positions.clamp_(0, ignored_index)
471 |
472 | loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
473 | start_loss = loss_fct(start_logits, start_positions)
474 | end_loss = loss_fct(end_logits, end_positions)
475 | total_loss = (start_loss + end_loss) / 2
476 | return total_loss
477 | else:
478 | return start_logits, end_logits
--------------------------------------------------------------------------------
/bert/optimization.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
3 | #
4 | # Licensed under the Apache License, Version 2.0 (the "License");
5 | # you may not use this file except in compliance with the License.
6 | # You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 | """PyTorch optimization for BERT model."""
16 |
17 | import math
18 | import torch
19 | from torch.optim import Optimizer
20 | from torch.nn.utils import clip_grad_norm_
21 |
22 | def warmup_cosine(x, warmup=0.002):
23 | if x < warmup:
24 | return x/warmup
25 | return 0.5 * (1.0 + torch.cos(math.pi * x))
26 |
27 | def warmup_constant(x, warmup=0.002):
28 | if x < warmup:
29 | return x/warmup
30 | return 1.0
31 |
32 | def warmup_linear(x, warmup=0.002):
33 | if x < warmup:
34 | return x/warmup
35 | return 1.0 - x
36 |
37 | SCHEDULES = {
38 | 'warmup_cosine':warmup_cosine,
39 | 'warmup_constant':warmup_constant,
40 | 'warmup_linear':warmup_linear,
41 | }
42 |
43 |
44 | class BERTAdam(Optimizer):
45 | """Implements BERT version of Adam algorithm with weight decay fix (and no ).
46 | Params:
47 | lr: learning rate
48 | warmup: portion of t_total for the warmup, -1 means no warmup. Default: -1
49 | t_total: total number of training steps for the learning
50 | rate schedule, -1 means constant learning rate. Default: -1
51 | schedule: schedule to use for the warmup (see above). Default: 'warmup_linear'
52 | b1: Adams b1. Default: 0.9
53 | b2: Adams b2. Default: 0.999
54 | e: Adams epsilon. Default: 1e-6
55 | weight_decay_rate: Weight decay. Default: 0.01
56 | max_grad_norm: Maximum norm for the gradients (-1 means no clipping). Default: 1.0
57 | """
58 | def __init__(self, params, lr, warmup=-1, t_total=-1, schedule='warmup_linear',
59 | b1=0.9, b2=0.999, e=1e-6, weight_decay_rate=0.01,
60 | max_grad_norm=1.0):
61 | if not lr >= 0.0:
62 | raise ValueError("Invalid learning rate: {} - should be >= 0.0".format(lr))
63 | if schedule not in SCHEDULES:
64 | raise ValueError("Invalid schedule parameter: {}".format(schedule))
65 | if not 0.0 <= warmup < 1.0 and not warmup == -1:
66 | raise ValueError("Invalid warmup: {} - should be in [0.0, 1.0[ or -1".format(warmup))
67 | if not 0.0 <= b1 < 1.0:
68 | raise ValueError("Invalid b1 parameter: {} - should be in [0.0, 1.0[".format(b1))
69 | if not 0.0 <= b2 < 1.0:
70 | raise ValueError("Invalid b2 parameter: {} - should be in [0.0, 1.0[".format(b2))
71 | if not e >= 0.0:
72 | raise ValueError("Invalid epsilon value: {} - should be >= 0.0".format(e))
73 | defaults = dict(lr=lr, schedule=schedule, warmup=warmup, t_total=t_total,
74 | b1=b1, b2=b2, e=e, weight_decay_rate=weight_decay_rate,
75 | max_grad_norm=max_grad_norm)
76 | super(BERTAdam, self).__init__(params, defaults)
77 |
78 | def get_lr(self):
79 | lr = []
80 | for group in self.param_groups:
81 | for p in group['params']:
82 | state = self.state[p]
83 | if len(state) == 0:
84 | return [0]
85 | if group['t_total'] != -1:
86 | schedule_fct = SCHEDULES[group['schedule']]
87 | lr_scheduled = group['lr'] * schedule_fct(state['step']/group['t_total'], group['warmup'])
88 | else:
89 | lr_scheduled = group['lr']
90 | lr.append(lr_scheduled)
91 | return lr
92 |
93 | def step(self, closure=None):
94 | """Performs a single optimization step.
95 |
96 | Arguments:
97 | closure (callable, optional): A closure that reevaluates the model
98 | and returns the loss.
99 | """
100 | loss = None
101 | if closure is not None:
102 | loss = closure()
103 |
104 | for group in self.param_groups:
105 | for p in group['params']:
106 | if p.grad is None:
107 | continue
108 | grad = p.grad.data
109 | if grad.is_sparse:
110 | raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead')
111 |
112 | state = self.state[p]
113 |
114 | # State initialization
115 | if len(state) == 0:
116 | state['step'] = 0
117 | # Exponential moving average of gradient values
118 | state['next_m'] = torch.zeros_like(p.data)
119 | # Exponential moving average of squared gradient values
120 | state['next_v'] = torch.zeros_like(p.data)
121 |
122 | next_m, next_v = state['next_m'], state['next_v']
123 | beta1, beta2 = group['b1'], group['b2']
124 |
125 | # Add grad clipping
126 | if group['max_grad_norm'] > 0:
127 | clip_grad_norm_(p, group['max_grad_norm'])
128 |
129 | # Decay the first and second moment running average coefficient
130 | # In-place operations to update the averages at the same time
131 | next_m.mul_(beta1).add_(1 - beta1, grad)
132 | next_v.mul_(beta2).addcmul_(1 - beta2, grad, grad)
133 | update = next_m / (next_v.sqrt() + group['e'])
134 |
135 | # Just adding the square of the weights to the loss function is *not*
136 | # the correct way of using L2 regularization/weight decay with Adam,
137 | # since that will interact with the m and v parameters in strange ways.
138 | #
139 | # Instead we want ot decay the weights in a manner that doesn't interact
140 | # with the m/v parameters. This is equivalent to adding the square
141 | # of the weights to the loss with plain (non-momentum) SGD.
142 | if group['weight_decay_rate'] > 0.0:
143 | update += group['weight_decay_rate'] * p.data
144 |
145 | if group['t_total'] != -1:
146 | schedule_fct = SCHEDULES[group['schedule']]
147 | lr_scheduled = group['lr'] * schedule_fct(state['step']/group['t_total'], group['warmup'])
148 | else:
149 | lr_scheduled = group['lr']
150 |
151 | update_with_lr = lr_scheduled * update
152 | p.data.add_(-update_with_lr)
153 |
154 | state['step'] += 1
155 |
156 | # step_size = lr_scheduled * math.sqrt(bias_correction2) / bias_correction1
157 | # bias_correction1 = 1 - beta1 ** state['step']
158 | # bias_correction2 = 1 - beta2 ** state['step']
159 |
160 | return loss
161 |
--------------------------------------------------------------------------------
/bert/tokenization.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
3 | #
4 | # Licensed under the Apache License, Version 2.0 (the "License");
5 | # you may not use this file except in compliance with the License.
6 | # You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 | """Tokenization classes."""
16 |
17 | from __future__ import absolute_import
18 | from __future__ import division
19 | from __future__ import print_function
20 |
21 | import collections
22 | import unicodedata
23 | import six
24 |
25 |
26 | def convert_to_unicode(text):
27 | """Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
28 | if six.PY3:
29 | if isinstance(text, str):
30 | return text
31 | elif isinstance(text, bytes):
32 | return text.decode("utf-8", "ignore")
33 | else:
34 | raise ValueError("Unsupported string type: %s" % (type(text)))
35 | elif six.PY2:
36 | if isinstance(text, str):
37 | return text.decode("utf-8", "ignore")
38 | elif isinstance(text, unicode):
39 | return text
40 | else:
41 | raise ValueError("Unsupported string type: %s" % (type(text)))
42 | else:
43 | raise ValueError("Not running on Python2 or Python 3?")
44 |
45 |
46 | def printable_text(text):
47 | """Returns text encoded in a way suitable for print or `tf.logging`."""
48 |
49 | # These functions want `str` for both Python2 and Python3, but in one case
50 | # it's a Unicode string and in the other it's a byte string.
51 | if six.PY3:
52 | if isinstance(text, str):
53 | return text
54 | elif isinstance(text, bytes):
55 | return text.decode("utf-8", "ignore")
56 | else:
57 | raise ValueError("Unsupported string type: %s" % (type(text)))
58 | elif six.PY2:
59 | if isinstance(text, str):
60 | return text
61 | elif isinstance(text, unicode):
62 | return text.encode("utf-8")
63 | else:
64 | raise ValueError("Unsupported string type: %s" % (type(text)))
65 | else:
66 | raise ValueError("Not running on Python2 or Python 3?")
67 |
68 |
69 | def load_vocab(vocab_file):
70 | """Loads a vocabulary file into a dictionary."""
71 | vocab = collections.OrderedDict()
72 | index = 0
73 | with open(vocab_file, "r", encoding="utf-8") as reader:
74 | while True:
75 | token = convert_to_unicode(reader.readline())
76 | if not token:
77 | break
78 | token = token.strip()
79 | vocab[token] = index
80 | index += 1
81 | return vocab
82 |
83 |
84 | def convert_tokens_to_ids(vocab, tokens):
85 | """Converts a sequence of tokens into ids using the vocab."""
86 | ids = []
87 | for token in tokens:
88 | ids.append(vocab[token])
89 | return ids
90 |
91 |
92 | def whitespace_tokenize(text):
93 | """Runs basic whitespace cleaning and splitting on a peice of text."""
94 | text = text.strip()
95 | if not text:
96 | return []
97 | tokens = text.split()
98 | return tokens
99 |
100 |
101 | class FullTokenizer(object):
102 | """Runs end-to-end tokenziation."""
103 |
104 | def __init__(self, vocab_file, do_lower_case=True):
105 | self.vocab = load_vocab(vocab_file)
106 | self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case)
107 | self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab)
108 |
109 | def tokenize(self, text):
110 | split_tokens = []
111 | for token in self.basic_tokenizer.tokenize(text):
112 | for sub_token in self.wordpiece_tokenizer.tokenize(token):
113 | split_tokens.append(sub_token)
114 |
115 | return split_tokens
116 |
117 | def convert_tokens_to_ids(self, tokens):
118 | return convert_tokens_to_ids(self.vocab, tokens)
119 |
120 |
121 | class BasicTokenizer(object):
122 | """Runs basic tokenization (punctuation splitting, lower casing, etc.)."""
123 |
124 | def __init__(self, do_lower_case=True):
125 | """Constructs a BasicTokenizer.
126 |
127 | Args:
128 | do_lower_case: Whether to lower case the input.
129 | """
130 | self.do_lower_case = do_lower_case
131 |
132 | def tokenize(self, text):
133 | """Tokenizes a piece of text."""
134 | text = convert_to_unicode(text)
135 | text = self._clean_text(text)
136 | # This was added on November 1st, 2018 for the multilingual and Chinese
137 | # models. This is also applied to the English models now, but it doesn't
138 | # matter since the English models were not trained on any Chinese data
139 | # and generally don't have any Chinese data in them (there are Chinese
140 | # characters in the vocabulary because Wikipedia does have some Chinese
141 | # words in the English Wikipedia.).
142 | text = self._tokenize_chinese_chars(text)
143 | orig_tokens = whitespace_tokenize(text)
144 | split_tokens = []
145 | for token in orig_tokens:
146 | if self.do_lower_case:
147 | token = token.lower()
148 | token = self._run_strip_accents(token)
149 | split_tokens.extend(self._run_split_on_punc(token))
150 |
151 | output_tokens = whitespace_tokenize(" ".join(split_tokens))
152 | return output_tokens
153 |
154 | def _run_strip_accents(self, text):
155 | """Strips accents from a piece of text."""
156 | text = unicodedata.normalize("NFD", text)
157 | output = []
158 | for char in text:
159 | cat = unicodedata.category(char)
160 | if cat == "Mn":
161 | continue
162 | output.append(char)
163 | return "".join(output)
164 |
165 | def _run_split_on_punc(self, text):
166 | """Splits punctuation on a piece of text."""
167 | chars = list(text)
168 | i = 0
169 | start_new_word = True
170 | output = []
171 | while i < len(chars):
172 | char = chars[i]
173 | if _is_punctuation(char):
174 | output.append([char])
175 | start_new_word = True
176 | else:
177 | if start_new_word:
178 | output.append([])
179 | start_new_word = False
180 | output[-1].append(char)
181 | i += 1
182 |
183 | return ["".join(x) for x in output]
184 |
185 | def _tokenize_chinese_chars(self, text):
186 | """Adds whitespace around any CJK character."""
187 | output = []
188 | for char in text:
189 | cp = ord(char)
190 | if self._is_chinese_char(cp):
191 | output.append(" ")
192 | output.append(char)
193 | output.append(" ")
194 | else:
195 | output.append(char)
196 | return "".join(output)
197 |
198 | def _is_chinese_char(self, cp):
199 | """Checks whether CP is the codepoint of a CJK character."""
200 | # This defines a "chinese character" as anything in the CJK Unicode block:
201 | # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
202 | #
203 | # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
204 | # despite its name. The modern Korean Hangul alphabet is a different block,
205 | # as is Japanese Hiragana and Katakana. Those alphabets are used to write
206 | # space-separated words, so they are not treated specially and handled
207 | # like the all of the other languages.
208 | if ((cp >= 0x4E00 and cp <= 0x9FFF) or #
209 | (cp >= 0x3400 and cp <= 0x4DBF) or #
210 | (cp >= 0x20000 and cp <= 0x2A6DF) or #
211 | (cp >= 0x2A700 and cp <= 0x2B73F) or #
212 | (cp >= 0x2B740 and cp <= 0x2B81F) or #
213 | (cp >= 0x2B820 and cp <= 0x2CEAF) or
214 | (cp >= 0xF900 and cp <= 0xFAFF) or #
215 | (cp >= 0x2F800 and cp <= 0x2FA1F)): #
216 | return True
217 |
218 | return False
219 |
220 | def _clean_text(self, text):
221 | """Performs invalid character removal and whitespace cleanup on text."""
222 | output = []
223 | for char in text:
224 | cp = ord(char)
225 | if cp == 0 or cp == 0xfffd or _is_control(char):
226 | continue
227 | if _is_whitespace(char):
228 | output.append(" ")
229 | else:
230 | output.append(char)
231 | return "".join(output)
232 |
233 |
234 | class WordpieceTokenizer(object):
235 | """Runs WordPiece tokenization."""
236 |
237 | def __init__(self, vocab, unk_token="[UNK]", max_input_chars_per_word=100):
238 | self.vocab = vocab
239 | self.unk_token = unk_token
240 | self.max_input_chars_per_word = max_input_chars_per_word
241 |
242 | def tokenize(self, text):
243 | """Tokenizes a piece of text into its word pieces.
244 |
245 | This uses a greedy longest-match-first algorithm to perform tokenization
246 | using the given vocabulary.
247 |
248 | For example:
249 | input = "unaffable"
250 | output = ["un", "##aff", "##able"]
251 |
252 | Args:
253 | text: A single token or whitespace separated tokens. This should have
254 | already been passed through `BasicTokenizer.
255 |
256 | Returns:
257 | A list of wordpiece tokens.
258 | """
259 |
260 | text = convert_to_unicode(text)
261 |
262 | output_tokens = []
263 | for token in whitespace_tokenize(text):
264 | chars = list(token)
265 | if len(chars) > self.max_input_chars_per_word:
266 | output_tokens.append(self.unk_token)
267 | continue
268 |
269 | is_bad = False
270 | start = 0
271 | sub_tokens = []
272 | while start < len(chars):
273 | end = len(chars)
274 | cur_substr = None
275 | while start < end:
276 | substr = "".join(chars[start:end])
277 | if start > 0:
278 | substr = "##" + substr
279 | if substr in self.vocab:
280 | cur_substr = substr
281 | break
282 | end -= 1
283 | if cur_substr is None:
284 | is_bad = True
285 | break
286 | sub_tokens.append(cur_substr)
287 | start = end
288 |
289 | if is_bad:
290 | output_tokens.append(self.unk_token)
291 | else:
292 | output_tokens.extend(sub_tokens)
293 | return output_tokens
294 |
295 |
296 | def _is_whitespace(char):
297 | """Checks whether `chars` is a whitespace character."""
298 | # \t, \n, and \r are technically contorl characters but we treat them
299 | # as whitespace since they are generally considered as such.
300 | if char == " " or char == "\t" or char == "\n" or char == "\r":
301 | return True
302 | cat = unicodedata.category(char)
303 | if cat == "Zs":
304 | return True
305 | return False
306 |
307 |
308 | def _is_control(char):
309 | """Checks whether `chars` is a control character."""
310 | # These are technically control characters but we count them as whitespace
311 | # characters.
312 | if char == "\t" or char == "\n" or char == "\r":
313 | return False
314 | cat = unicodedata.category(char)
315 | if cat.startswith("C"):
316 | return True
317 | return False
318 |
319 |
320 | def _is_punctuation(char):
321 | """Checks whether `chars` is a punctuation character."""
322 | cp = ord(char)
323 | # We treat all non-letter/number ASCII as punctuation.
324 | # Characters such as "^", "$", and "`" are not in the Unicode
325 | # Punctuation class but we treat them as punctuation anyways, for
326 | # consistency.
327 | if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or
328 | (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)):
329 | return True
330 | cat = unicodedata.category(char)
331 | if cat.startswith("P"):
332 | return True
333 | return False
334 |
--------------------------------------------------------------------------------
/image/framework.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/huminghao16/SpanABSA/66369af840599df2a886d4ad1db1ceec53c0649f/image/framework.PNG
--------------------------------------------------------------------------------
/squad/__pycache__/squad_evaluate.cpython-35.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/huminghao16/SpanABSA/66369af840599df2a886d4ad1db1ceec53c0649f/squad/__pycache__/squad_evaluate.cpython-35.pyc
--------------------------------------------------------------------------------
/squad/__pycache__/squad_evaluate.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/huminghao16/SpanABSA/66369af840599df2a886d4ad1db1ceec53c0649f/squad/__pycache__/squad_evaluate.cpython-36.pyc
--------------------------------------------------------------------------------
/squad/__pycache__/squad_utils.cpython-35.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/huminghao16/SpanABSA/66369af840599df2a886d4ad1db1ceec53c0649f/squad/__pycache__/squad_utils.cpython-35.pyc
--------------------------------------------------------------------------------
/squad/__pycache__/squad_utils.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/huminghao16/SpanABSA/66369af840599df2a886d4ad1db1ceec53c0649f/squad/__pycache__/squad_utils.cpython-36.pyc
--------------------------------------------------------------------------------
/squad/squad_evaluate.py:
--------------------------------------------------------------------------------
1 | """ Official evaluation script for v1.1 of the SQuAD dataset. [Changed name for external importing]"""
2 | from __future__ import print_function
3 | from collections import Counter
4 | import string
5 | import re
6 | import argparse
7 | import json
8 | import sys
9 |
10 |
11 | def span_len(span):
12 | return span[1] - span[0]
13 |
14 | def span_overlap(s1, s2):
15 | start = max(s1[0], s2[0])
16 | stop = min(s1[1], s2[1])
17 | if stop > start:
18 | return start, stop
19 | return None
20 |
21 | def span_prec(true_span, pred_span):
22 | overlap = span_overlap(true_span, pred_span)
23 | if overlap is None:
24 | return 0.
25 | return span_len(overlap) / span_len(pred_span)
26 |
27 | def span_recall(true_span, pred_span):
28 | overlap = span_overlap(true_span, pred_span)
29 | if overlap is None:
30 | return 0.
31 | return span_len(overlap) / span_len(true_span)
32 |
33 | def span_f1(true_span, pred_span):
34 | p = span_prec(true_span, pred_span)
35 | r = span_recall(true_span, pred_span)
36 | if p == 0 or r == 0:
37 | return 0.0
38 | return 2. * p * r / (p + r)
39 |
40 |
41 | def normalize_answer(s):
42 | """Lower text and remove punctuation, articles and extra whitespace."""
43 | def remove_articles(text):
44 | return re.sub(r'\b(a|an|the)\b', ' ', text)
45 |
46 | def white_space_fix(text):
47 | return ' '.join(text.split())
48 |
49 | def remove_punc(text):
50 | exclude = set(string.punctuation)
51 | return ''.join(ch for ch in text if ch not in exclude)
52 |
53 | def lower(text):
54 | return text.lower()
55 |
56 | return white_space_fix(remove_articles(remove_punc(lower(s))))
57 |
58 |
59 | def f1_score(prediction, ground_truth):
60 | prediction_tokens = normalize_answer(prediction).split()
61 | ground_truth_tokens = normalize_answer(ground_truth).split()
62 | common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
63 | num_same = sum(common.values())
64 | if num_same == 0:
65 | return 0
66 | precision = 1.0 * num_same / len(prediction_tokens)
67 | recall = 1.0 * num_same / len(ground_truth_tokens)
68 | f1 = (2 * precision * recall) / (precision + recall)
69 | return f1
70 |
71 |
72 | def exact_match_score(prediction, ground_truth):
73 | return (normalize_answer(prediction) == normalize_answer(ground_truth))
74 |
75 |
76 | def metric_max_over_ground_truths(metric_fn, prediction, ground_truths):
77 | scores_for_ground_truths = []
78 | for ground_truth in ground_truths:
79 | score = metric_fn(prediction, ground_truth)
80 | scores_for_ground_truths.append(score)
81 | return max(scores_for_ground_truths)
82 |
83 |
84 | def evaluate(dataset, predictions):
85 | f1 = exact_match = total = 0
86 | missing_count = 0
87 | for article in dataset:
88 | for paragraph in article['paragraphs']:
89 | for qa in paragraph['qas']:
90 | total += 1
91 | if qa['id'] not in predictions:
92 | missing_count += 1
93 | # message = 'Unanswered question ' + qa['id'] + \
94 | # ' will receive score 0.'
95 | # print(message, file=sys.stderr)
96 | continue
97 | ground_truths = list(map(lambda x: x['text'], qa['answers']))
98 | prediction = predictions[qa['id']]
99 | exact_match += metric_max_over_ground_truths(
100 | exact_match_score, prediction, ground_truths)
101 | f1 += metric_max_over_ground_truths(
102 | f1_score, prediction, ground_truths)
103 |
104 | exact_match = 100.0 * exact_match / (total-missing_count)
105 | f1 = 100.0 * f1 / (total-missing_count)
106 | print("missing prediction on %d examples" % (missing_count))
107 | return {'exact_match': exact_match, 'f1': f1}
108 |
109 |
110 | def merge_eval(main_eval, new_eval):
111 | for k in new_eval:
112 | main_eval['%s' % (k)] = new_eval[k]
113 |
114 |
115 | if __name__ == '__main__':
116 | expected_version = '1.1'
117 | parser = argparse.ArgumentParser(
118 | description='Evaluation for SQuAD ' + expected_version)
119 | parser.add_argument('dataset_file', help='Dataset file')
120 | parser.add_argument('prediction_file', help='Prediction File')
121 | args = parser.parse_args()
122 | with open(args.dataset_file) as dataset_file:
123 | dataset_json = json.load(dataset_file)
124 | # if (dataset_json['version'] != expected_version):
125 | # print('Evaluation expects v-' + expected_version +
126 | # ', but got dataset with v-' + dataset_json['version'],
127 | # file=sys.stderr)
128 | dataset = dataset_json['data']
129 | with open(args.prediction_file) as prediction_file:
130 | predictions = json.load(prediction_file)
131 | print(json.dumps(evaluate(dataset, predictions)))
132 |
133 | # prediction = '1854–1855'
134 | # ground_truths = ['1854']
135 | # print(metric_max_over_ground_truths(
136 | # f1_score, prediction, ground_truths))
137 |
--------------------------------------------------------------------------------
/squad/squad_utils.py:
--------------------------------------------------------------------------------
1 | import json
2 | import math
3 | import six
4 | import collections
5 |
6 | import bert.tokenization as tokenization
7 |
8 |
9 | class SquadExample(object):
10 | """A single training/test example for simple sequence classification."""
11 |
12 | def __init__(self,
13 | qas_id,
14 | question_text,
15 | doc_tokens,
16 | orig_answer_text=None,
17 | start_position=None,
18 | end_position=None):
19 | self.qas_id = qas_id
20 | self.question_text = question_text
21 | self.doc_tokens = doc_tokens
22 | self.orig_answer_text = orig_answer_text
23 | self.start_position = start_position
24 | self.end_position = end_position
25 |
26 | def __str__(self):
27 | return self.__repr__()
28 |
29 | def __repr__(self):
30 | s = ""
31 | s += "qas_id: %s" % (tokenization.printable_text(self.qas_id))
32 | s += ", question_text: %s" % (
33 | tokenization.printable_text(self.question_text))
34 | s += ", doc_tokens: [%s]" % (" ".join(self.doc_tokens))
35 | if self.start_position:
36 | s += ", start_position: %d" % (self.start_position)
37 | if self.start_position:
38 | s += ", end_position: %d" % (self.end_position)
39 | return s
40 |
41 |
42 | class InputFeatures(object):
43 | """A single set of features of data."""
44 |
45 | def __init__(self,
46 | unique_id,
47 | example_index,
48 | doc_span_index,
49 | tokens,
50 | token_to_orig_map,
51 | token_is_max_context,
52 | input_ids,
53 | input_mask,
54 | segment_ids,
55 | start_position=None,
56 | end_position=None):
57 | self.unique_id = unique_id
58 | self.example_index = example_index
59 | self.doc_span_index = doc_span_index
60 | self.tokens = tokens
61 | self.token_to_orig_map = token_to_orig_map
62 | self.token_is_max_context = token_is_max_context
63 | self.input_ids = input_ids
64 | self.input_mask = input_mask
65 | self.segment_ids = segment_ids
66 | self.start_position = start_position
67 | self.end_position = end_position
68 |
69 |
70 | def read_squad_examples(input_file, is_training, logger):
71 | """Read a SQuAD json file into a list of SquadExample."""
72 | with open(input_file, "r") as reader:
73 | input_data = json.load(reader)["data"]
74 |
75 | def is_whitespace(c):
76 | if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
77 | return True
78 | return False
79 |
80 | examples = []
81 | for entry in input_data:
82 | for paragraph in entry["paragraphs"]:
83 | paragraph_text = paragraph["context"]
84 | doc_tokens = []
85 | char_to_word_offset = []
86 | prev_is_whitespace = True
87 | for c in paragraph_text:
88 | if is_whitespace(c):
89 | prev_is_whitespace = True
90 | else:
91 | if prev_is_whitespace:
92 | doc_tokens.append(c) # add a new word
93 | else:
94 | doc_tokens[-1] += c # add a new character
95 | prev_is_whitespace = False
96 | char_to_word_offset.append(len(doc_tokens) - 1)
97 |
98 | for qa in paragraph["qas"]:
99 | qas_id = qa["id"]
100 | question_text = qa["question"]
101 | start_position = None
102 | end_position = None
103 | orig_answer_text = None
104 | if is_training:
105 | if len(qa["answers"]) != 1:
106 | raise ValueError(
107 | "For training, each question should have exactly 1 answer.")
108 | answer = qa["answers"][0]
109 | orig_answer_text = answer["text"]
110 | answer_offset = answer["answer_start"]
111 | answer_length = len(orig_answer_text)
112 | start_position = char_to_word_offset[answer_offset]
113 | end_position = char_to_word_offset[answer_offset + answer_length - 1]
114 | # Only add answers where the text can be exactly recovered from the
115 | # document. If this CAN'T happen it's likely due to weird Unicode
116 | # stuff so we will just skip the example.
117 | #
118 | # Note that this means for training mode, every example is NOT
119 | # guaranteed to be preserved.
120 | actual_text = " ".join(doc_tokens[start_position:(end_position + 1)])
121 | cleaned_answer_text = " ".join(
122 | tokenization.whitespace_tokenize(orig_answer_text))
123 | if actual_text.find(cleaned_answer_text) == -1:
124 | logger.warning("Could not find answer: '%s' vs. '%s'",
125 | actual_text, cleaned_answer_text)
126 | continue
127 |
128 | example = SquadExample(
129 | qas_id=qas_id,
130 | question_text=question_text,
131 | doc_tokens=doc_tokens,
132 | orig_answer_text=orig_answer_text,
133 | start_position=start_position,
134 | end_position=end_position)
135 | examples.append(example)
136 | return examples
137 |
138 |
139 | def convert_examples_to_features(examples, tokenizer, max_seq_length,
140 | doc_stride, max_query_length, is_training, verbose_logging=False, logger=None):
141 | """Loads a data file into a list of `InputBatch`s."""
142 |
143 | unique_id = 1000000000
144 |
145 | features = []
146 | for (example_index, example) in enumerate(examples):
147 | query_tokens = tokenizer.tokenize(example.question_text)
148 |
149 | if len(query_tokens) > max_query_length:
150 | query_tokens = query_tokens[0:max_query_length]
151 |
152 | tok_to_orig_index = []
153 | orig_to_tok_index = []
154 | all_doc_tokens = []
155 | for (i, token) in enumerate(example.doc_tokens):
156 | orig_to_tok_index.append(len(all_doc_tokens))
157 | sub_tokens = tokenizer.tokenize(token)
158 | for sub_token in sub_tokens:
159 | tok_to_orig_index.append(i)
160 | all_doc_tokens.append(sub_token)
161 |
162 | tok_start_position = None
163 | tok_end_position = None
164 | if is_training:
165 | tok_start_position = orig_to_tok_index[example.start_position]
166 | if example.end_position < len(example.doc_tokens) - 1:
167 | tok_end_position = orig_to_tok_index[example.end_position + 1] - 1
168 | else:
169 | tok_end_position = len(all_doc_tokens) - 1
170 | (tok_start_position, tok_end_position) = _improve_answer_span(
171 | all_doc_tokens, tok_start_position, tok_end_position, tokenizer,
172 | example.orig_answer_text)
173 |
174 | # The -3 accounts for [CLS], [SEP] and [SEP]
175 | max_tokens_for_doc = max_seq_length - len(query_tokens) - 3
176 |
177 | # We can have documents that are longer than the maximum sequence length.
178 | # To deal with this we do a sliding window approach, where we take chunks
179 | # of the up to our max length with a stride of `doc_stride`.
180 | _DocSpan = collections.namedtuple( # pylint: disable=invalid-name
181 | "DocSpan", ["start", "length"])
182 | doc_spans = []
183 | start_offset = 0
184 | while start_offset < len(all_doc_tokens):
185 | length = len(all_doc_tokens) - start_offset
186 | if length > max_tokens_for_doc:
187 | length = max_tokens_for_doc
188 | doc_spans.append(_DocSpan(start=start_offset, length=length))
189 | if start_offset + length == len(all_doc_tokens):
190 | break
191 | start_offset += min(length, doc_stride)
192 |
193 | for (doc_span_index, doc_span) in enumerate(doc_spans):
194 | tokens = []
195 | token_to_orig_map = {}
196 | token_is_max_context = {}
197 | segment_ids = []
198 | tokens.append("[CLS]")
199 | segment_ids.append(0)
200 | for token in query_tokens:
201 | tokens.append(token)
202 | segment_ids.append(0)
203 | tokens.append("[SEP]")
204 | segment_ids.append(0)
205 |
206 | for i in range(doc_span.length):
207 | split_token_index = doc_span.start + i
208 | token_to_orig_map[len(tokens)] = tok_to_orig_index[split_token_index]
209 |
210 | is_max_context = _check_is_max_context(doc_spans, doc_span_index,
211 | split_token_index)
212 | token_is_max_context[len(tokens)] = is_max_context
213 | tokens.append(all_doc_tokens[split_token_index])
214 | segment_ids.append(1)
215 | tokens.append("[SEP]")
216 | segment_ids.append(1)
217 |
218 | input_ids = tokenizer.convert_tokens_to_ids(tokens)
219 |
220 | # The mask has 1 for real tokens and 0 for padding tokens. Only real
221 | # tokens are attended to.
222 | input_mask = [1] * len(input_ids)
223 |
224 | # Zero-pad up to the sequence length.
225 | while len(input_ids) < max_seq_length:
226 | input_ids.append(0)
227 | input_mask.append(0)
228 | segment_ids.append(0)
229 |
230 | assert len(input_ids) == max_seq_length
231 | assert len(input_mask) == max_seq_length
232 | assert len(segment_ids) == max_seq_length
233 |
234 | start_position = None
235 | end_position = None
236 | if is_training:
237 | # For training, if our document chunk does not contain an annotation
238 | # we throw it out, since there is nothing to predict.
239 | doc_start = doc_span.start
240 | doc_end = doc_span.start + doc_span.length - 1
241 | out_of_span = False
242 | if not (tok_start_position >= doc_start and tok_end_position <= doc_end):
243 | out_of_span = True
244 |
245 | if out_of_span:
246 | start_position = 0
247 | end_position = 0
248 | else:
249 | doc_offset = len(query_tokens) + 2
250 | start_position = tok_start_position - doc_start + doc_offset
251 | end_position = tok_end_position - doc_start + doc_offset
252 |
253 | if example_index < 2 and verbose_logging:
254 | logger.info("*** Example ***")
255 | logger.info("unique_id: %s" % (unique_id))
256 | logger.info("example_index: %s" % (example_index))
257 | logger.info("doc_span_index: %s" % (doc_span_index))
258 | logger.info("tokens: %s" % " ".join(
259 | [tokenization.printable_text(x) for x in tokens]))
260 | logger.info("token_to_orig_map: %s" % " ".join(
261 | ["%d:%d" % (x, y) for (x, y) in six.iteritems(token_to_orig_map)]))
262 | logger.info("token_is_max_context: %s" % " ".join([
263 | "%d:%s" % (x, y) for (x, y) in six.iteritems(token_is_max_context)
264 | ]))
265 | logger.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
266 | logger.info(
267 | "input_mask: %s" % " ".join([str(x) for x in input_mask]))
268 | logger.info(
269 | "segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
270 | if is_training:
271 | answer_text = " ".join(tokens[start_position:(end_position + 1)])
272 | logger.info("start_position: %d" % (start_position))
273 | logger.info("end_position: %d" % (end_position))
274 | logger.info("answer: %s" % (tokenization.printable_text(answer_text)))
275 |
276 | features.append(
277 | InputFeatures(
278 | unique_id=unique_id,
279 | example_index=example_index,
280 | doc_span_index=doc_span_index,
281 | tokens=tokens,
282 | token_to_orig_map=token_to_orig_map,
283 | token_is_max_context=token_is_max_context,
284 | input_ids=input_ids,
285 | input_mask=input_mask,
286 | segment_ids=segment_ids,
287 | start_position=start_position,
288 | end_position=end_position))
289 | unique_id += 1
290 |
291 | if len(features) % 5000 == 0:
292 | logger.info("Processing features: %d" % (len(features)))
293 |
294 | return features
295 |
296 |
297 | def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer,
298 | orig_answer_text):
299 | """Returns tokenized answer spans that better match the annotated answer."""
300 |
301 | # The SQuAD annotations are character based. We first project them to
302 | # whitespace-tokenized words. But then after WordPiece tokenization, we can
303 | # often find a "better match". For example:
304 | #
305 | # Question: What year was John Smith born?
306 | # Context: The leader was John Smith (1895-1943).
307 | # Answer: 1895
308 | #
309 | # The original whitespace-tokenized answer will be "(1895-1943).". However
310 | # after tokenization, our tokens will be "( 1895 - 1943 ) .". So we can match
311 | # the exact answer, 1895.
312 | #
313 | # However, this is not always possible. Consider the following:
314 | #
315 | # Question: What country is the top exporter of electornics?
316 | # Context: The Japanese electronics industry is the lagest in the world.
317 | # Answer: Japan
318 | #
319 | # In this case, the annotator chose "Japan" as a character sub-span of
320 | # the word "Japanese". Since our WordPiece tokenizer does not split
321 | # "Japanese", we just use "Japanese" as the annotation. This is fairly rare
322 | # in SQuAD, but does happen.
323 | tok_answer_text = " ".join(tokenizer.tokenize(orig_answer_text))
324 |
325 | for new_start in range(input_start, input_end + 1):
326 | for new_end in range(input_end, new_start - 1, -1):
327 | text_span = " ".join(doc_tokens[new_start:(new_end + 1)])
328 | if text_span == tok_answer_text:
329 | return (new_start, new_end)
330 |
331 | return (input_start, input_end)
332 |
333 |
334 | def _check_is_max_context(doc_spans, cur_span_index, position):
335 | """Check if this is the 'max context' doc span for the token."""
336 |
337 | # Because of the sliding window approach taken to scoring documents, a single
338 | # token can appear in multiple documents. E.g.
339 | # Doc: the man went to the store and bought a gallon of milk
340 | # Span A: the man went to the
341 | # Span B: to the store and bought
342 | # Span C: and bought a gallon of
343 | # ...
344 | #
345 | # Now the word 'bought' will have two scores from spans B and C. We only
346 | # want to consider the score with "maximum context", which we define as
347 | # the *minimum* of its left and right context (the *sum* of left and
348 | # right context will always be the same, of course).
349 | #
350 | # In the example the maximum context for 'bought' would be span C since
351 | # it has 1 left context and 3 right context, while span B has 4 left context
352 | # and 0 right context.
353 | best_score = None
354 | best_span_index = None
355 | for (span_index, doc_span) in enumerate(doc_spans):
356 | end = doc_span.start + doc_span.length - 1
357 | if position < doc_span.start:
358 | continue
359 | if position > end:
360 | continue
361 | num_left_context = position - doc_span.start
362 | num_right_context = end - position
363 | score = min(num_left_context, num_right_context) + 0.01 * doc_span.length
364 | if best_score is None or score > best_score:
365 | best_score = score
366 | best_span_index = span_index
367 |
368 | return cur_span_index == best_span_index
369 |
370 |
371 | RawResult = collections.namedtuple("RawResult",
372 | ["unique_id", "start_logits", "end_logits"])
373 |
374 |
375 | def write_predictions(all_examples, all_features, all_results, n_best_size,
376 | max_answer_length, do_lower_case, do_max_context, verbose_logging, logger):
377 | """Write final predictions to the json file."""
378 |
379 | example_index_to_features = collections.defaultdict(list)
380 | for feature in all_features:
381 | example_index_to_features[feature.example_index].append(feature)
382 |
383 | unique_id_to_result = {}
384 | for result in all_results:
385 | unique_id_to_result[result.unique_id] = result
386 |
387 | _PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name
388 | "PrelimPrediction",
389 | ["feature_index", "start_index", "end_index", "start_logit", "end_logit"])
390 |
391 | all_predictions = collections.OrderedDict()
392 | all_nbest_json = collections.OrderedDict()
393 | for (example_index, example) in enumerate(all_examples):
394 | features = example_index_to_features[example_index]
395 |
396 | prelim_predictions = []
397 | for (feature_index, feature) in enumerate(features):
398 | result = unique_id_to_result[feature.unique_id]
399 |
400 | start_indexes = _get_best_indexes(result.start_logits, n_best_size)
401 | end_indexes = _get_best_indexes(result.end_logits, n_best_size)
402 | for start_index in start_indexes:
403 | for end_index in end_indexes:
404 | # We could hypothetically create invalid predictions, e.g., predict
405 | # that the start of the span is in the question. We throw out all
406 | # invalid predictions.
407 | if start_index >= len(feature.tokens):
408 | continue
409 | if end_index >= len(feature.tokens):
410 | continue
411 | if start_index not in feature.token_to_orig_map:
412 | continue
413 | if end_index not in feature.token_to_orig_map:
414 | continue
415 | if do_max_context and not feature.token_is_max_context.get(start_index, False):
416 | continue
417 | if end_index < start_index:
418 | continue
419 | length = end_index - start_index + 1
420 | if length > max_answer_length:
421 | continue
422 | prelim_predictions.append(
423 | _PrelimPrediction(
424 | feature_index=feature_index,
425 | start_index=start_index,
426 | end_index=end_index,
427 | start_logit=result.start_logits[start_index],
428 | end_logit=result.end_logits[end_index]))
429 |
430 | prelim_predictions = sorted(
431 | prelim_predictions,
432 | key=lambda x: (x.start_logit + x.end_logit),
433 | reverse=True)
434 |
435 | _NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name
436 | "NbestPrediction", ["text", "start_logit", "end_logit"])
437 |
438 | seen_predictions = {}
439 | nbest = []
440 | for pred in prelim_predictions:
441 | if len(nbest) >= n_best_size:
442 | break
443 | feature = features[pred.feature_index]
444 |
445 | tok_tokens = feature.tokens[pred.start_index:(pred.end_index + 1)]
446 | orig_doc_start = feature.token_to_orig_map[pred.start_index]
447 | orig_doc_end = feature.token_to_orig_map[pred.end_index]
448 | orig_tokens = example.doc_tokens[orig_doc_start:(orig_doc_end + 1)]
449 | tok_text = " ".join(tok_tokens)
450 |
451 | # De-tokenize WordPieces that have been split off.
452 | tok_text = tok_text.replace(" ##", "")
453 | tok_text = tok_text.replace("##", "")
454 |
455 | # Clean whitespace
456 | tok_text = tok_text.strip()
457 | tok_text = " ".join(tok_text.split())
458 | orig_text = " ".join(orig_tokens)
459 |
460 | final_text = get_final_text(tok_text, orig_text, do_lower_case, verbose_logging, logger)
461 | if final_text in seen_predictions:
462 | continue
463 |
464 | seen_predictions[final_text] = True
465 | nbest.append(
466 | _NbestPrediction(
467 | text=final_text,
468 | start_logit=pred.start_logit,
469 | end_logit=pred.end_logit))
470 |
471 | # In very rare edge cases we could have no valid predictions. So we
472 | # just create a nonce prediction in this case to avoid failure.
473 | if not nbest:
474 | nbest.append(
475 | _NbestPrediction(text="empty", start_logit=0.0, end_logit=0.0))
476 |
477 | assert len(nbest) >= 1
478 |
479 | total_scores = []
480 | for entry in nbest:
481 | total_scores.append(entry.start_logit + entry.end_logit)
482 |
483 | probs = _compute_softmax(total_scores)
484 |
485 | nbest_json = []
486 | for (i, entry) in enumerate(nbest):
487 | output = collections.OrderedDict()
488 | output["text"] = entry.text
489 | output["probability"] = probs[i]
490 | output["start_logit"] = entry.start_logit
491 | output["end_logit"] = entry.end_logit
492 | nbest_json.append(output)
493 |
494 | assert len(nbest_json) >= 1
495 |
496 | all_predictions[example.qas_id] = nbest_json[0]["text"]
497 | all_nbest_json[example.qas_id] = nbest_json
498 |
499 | return all_predictions, all_nbest_json
500 |
501 |
502 | def get_final_text(pred_text, orig_text, do_lower_case, verbose_logging=False, logger=None):
503 | """Project the tokenized prediction back to the original text."""
504 |
505 | # When we created the data, we kept track of the alignment between original
506 | # (whitespace tokenized) tokens and our WordPiece tokenized tokens. So
507 | # now `orig_text` contains the span of our original text corresponding to the
508 | # span that we predicted.
509 | #
510 | # However, `orig_text` may contain extra characters that we don't want in
511 | # our prediction.
512 | #
513 | # For example, let's say:
514 | # pred_text = steve smith
515 | # orig_text = Steve Smith's
516 | #
517 | # We don't want to return `orig_text` because it contains the extra "'s".
518 | #
519 | # We don't want to return `pred_text` because it's already been normalized
520 | # (the SQuAD eval script also does punctuation stripping/lower casing but
521 | # our tokenizer does additional normalization like stripping accent
522 | # characters).
523 | #
524 | # What we really want to return is "Steve Smith".
525 | #
526 | # Therefore, we have to apply a semi-complicated alignment heruistic between
527 | # `pred_text` and `orig_text` to get a character-to-charcter alignment. This
528 | # can fail in certain cases in which case we just return `orig_text`.
529 |
530 | def _strip_spaces(text):
531 | ns_chars = []
532 | ns_to_s_map = collections.OrderedDict()
533 | for (i, c) in enumerate(text):
534 | if c == " ":
535 | continue
536 | ns_to_s_map[len(ns_chars)] = i
537 | ns_chars.append(c)
538 | ns_text = "".join(ns_chars)
539 | return (ns_text, ns_to_s_map)
540 |
541 | # We first tokenize `orig_text`, strip whitespace from the result
542 | # and `pred_text`, and check if they are the same length. If they are
543 | # NOT the same length, the heuristic has failed. If they are the same
544 | # length, we assume the characters are one-to-one aligned.
545 | tokenizer = tokenization.BasicTokenizer(do_lower_case=do_lower_case)
546 |
547 | tok_text = " ".join(tokenizer.tokenize(orig_text))
548 |
549 | start_position = tok_text.find(pred_text)
550 | if start_position == -1:
551 | if verbose_logging:
552 | logger.info(
553 | "Unable to find text: '%s' in '%s'" % (pred_text, orig_text))
554 | return orig_text
555 | end_position = start_position + len(pred_text) - 1
556 |
557 | (orig_ns_text, orig_ns_to_s_map) = _strip_spaces(orig_text)
558 | (tok_ns_text, tok_ns_to_s_map) = _strip_spaces(tok_text)
559 |
560 | if len(orig_ns_text) != len(tok_ns_text):
561 | if verbose_logging:
562 | logger.info("Length not equal after stripping spaces: '%s' vs '%s'",
563 | orig_ns_text, tok_ns_text)
564 | return orig_text
565 |
566 | # We then project the characters in `pred_text` back to `orig_text` using
567 | # the character-to-character alignment.
568 | tok_s_to_ns_map = {}
569 | for (i, tok_index) in six.iteritems(tok_ns_to_s_map):
570 | tok_s_to_ns_map[tok_index] = i
571 |
572 | orig_start_position = None
573 | if start_position in tok_s_to_ns_map:
574 | ns_start_position = tok_s_to_ns_map[start_position]
575 | if ns_start_position in orig_ns_to_s_map:
576 | orig_start_position = orig_ns_to_s_map[ns_start_position]
577 |
578 | if orig_start_position is None:
579 | if verbose_logging:
580 | logger.info("Couldn't map start position")
581 | return orig_text
582 |
583 | orig_end_position = None
584 | if end_position in tok_s_to_ns_map:
585 | ns_end_position = tok_s_to_ns_map[end_position]
586 | if ns_end_position in orig_ns_to_s_map:
587 | orig_end_position = orig_ns_to_s_map[ns_end_position]
588 |
589 | if orig_end_position is None:
590 | if verbose_logging:
591 | logger.info("Couldn't map end position")
592 | return orig_text
593 |
594 | output_text = orig_text[orig_start_position:(orig_end_position + 1)]
595 | return output_text
596 |
597 |
598 | def _get_best_indexes(logits, n_best_size):
599 | """Get the n-best logits from a list."""
600 | index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)
601 |
602 | best_indexes = []
603 | for i in range(len(index_and_score)):
604 | if i >= n_best_size:
605 | break
606 | best_indexes.append(index_and_score[i][0])
607 | return best_indexes
608 |
609 |
610 | def _compute_softmax(scores):
611 | """Compute softmax probability over raw logits."""
612 | if not scores:
613 | return []
614 |
615 | max_score = None
616 | for score in scores:
617 | if max_score is None or score > max_score:
618 | max_score = score
619 |
620 | exp_scores = []
621 | total_sum = 0.0
622 | for score in scores:
623 | x = math.exp(score - max_score)
624 | exp_scores.append(x)
625 | total_sum += x
626 |
627 | probs = []
628 | for score in exp_scores:
629 | probs.append(score / total_sum)
630 | return probs
--------------------------------------------------------------------------------