├── LICENSE.md ├── README.md ├── docker └── techqa │ ├── Dockerfile │ ├── README.md │ ├── environment-techqa.yml │ └── submission.sh ├── requirements.txt ├── run_techqa.py ├── synthetic └── README.md ├── techqa_evaluation.py ├── techqa_metrics.py └── techqa_processor.py /LICENSE.md: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Building a Baseline Model for the TechQA dataset 2 | 3 | This repo contains the code to train and run a baseline model against the TechQA dataset released in the ACL 2020 paper: [The TechQA dataset](https://arxiv.org/abs/1911.02984) 4 | 5 | The TechQA train and dev data along with 800,000 TechNotes are available [here](https://huggingface.co/datasets/PrimeQA/TechQA). 6 | Note: You need to go to "Files and versions" -> then download the tar gz file. The download may take some time depending on your internet speed. There are several large files in the tar ball. 7 | Also, note, that the TechQA leaderboard has been sunset. However, you're welcome to use the data. Please cite [the paper](https://arxiv.org/abs/1911.02984) in your publications/ experiments. 8 | 9 | ## Installation 10 | 11 | 12 | After cloning this repo, install dependencies using 13 | ``` 14 | pip install -r requirements.txt 15 | ``` 16 | 17 | If you want to run with `fp16`, you need to install [Apex]( https://github.com/NVIDIA/apex.git) 18 | 19 | ## Training a model 20 | 21 | In order to train a model on TechQA, use the script below. 22 | 23 | Note: Since TechQA is smaller dataset, it is better to start with a model that is already trained on a bigger QA dataset. Here, we start with BERT-Large trained on Squad. 24 | 25 | ``` 26 | python run_techqa.py \ 27 | --model_type bert \ 28 | --model_name_or_path bert-large-uncased-whole-word-masking-finetuned-squad \ 29 | --do_lower_case \ 30 | --learning_rate 5.5e-6 \ 31 | --do_train \ 32 | --num_train_epochs 20 \ 33 | --train_file \ 34 | --do_eval \ 35 | --predict_file \ 36 | --input_corpus_file \ 37 | --overwrite_output_dir \ 38 | --output_dir \ 39 | --add_doc_title_to_passage 40 | ``` 41 | 42 | You can add the `--fp16` flag if you have apex installed. 43 | 44 | To evaluate a model, you can run: 45 | 46 | ``` 47 | python run_techqa.py \ 48 | --model_type bert \ 49 | --model_name_or_path \ 50 | --do_lower_case \ 51 | --do_eval \ 52 | --predict_file \ 53 | --input_corpus_file \ 54 | --overwrite_output_dir \ 55 | --output_dir \ 56 | --add_doc_title_to_passage 57 | ``` 58 | 59 | 60 | ## Contact 61 | 62 | For help or issues, please submit a GitHub issue. 63 | 64 | For direct communication, please contact Avi Sil (avi@us.ibm.com). 65 | 66 | -------------------------------------------------------------------------------- /docker/techqa/Dockerfile: -------------------------------------------------------------------------------- 1 | # Start with nvidia pytorch image (ensures working pytorch + CUDA) 2 | FROM nvcr.io/nvidia/pytorch:19.04-py3 3 | 4 | # Setup tmp workdirs 5 | ENV SYMLINK_DIR /symlinked_data 6 | ENV TMP_OUTPUT_DIR /tmp_outputs 7 | RUN mkdir "${SYMLINK_DIR}" 8 | RUN mkdir "${TMP_OUTPUT_DIR}" 9 | ENV PYTHONPATH "." 10 | 11 | # Copy model code and install 12 | ADD . /techqa_model 13 | WORKDIR /techqa_model 14 | 15 | # Model Location 16 | ENV MODEL_WEIGHTS "models/" 17 | ENV MODEL_TYPE "bert" 18 | 19 | # Data Files 20 | ENV DEV_QUERY_FILE /var/spool/TechQA/input/questions.json 21 | ENV DEV_INPUT_CORPUS /var/spool/TechQA/input/documents.json 22 | ENV DEV_OUTPUT_FILE /var/spool/TechQA/output/sys_output.json 23 | 24 | # Install python packages 25 | RUN conda env update -n base -f docker/techqa/environment-techqa.yml 26 | RUN echo ". /opt/conda/etc/profile.d/conda.sh" >> ~/.bashrc 27 | RUN echo "conda activate base" >> ~/.bashrc 28 | 29 | CMD bash docker/techqa/submission.sh "${DEV_QUERY_FILE}" "${DEV_INPUT_CORPUS}" "${DEV_OUTPUT_FILE}" -------------------------------------------------------------------------------- /docker/techqa/README.md: -------------------------------------------------------------------------------- 1 | # Note: the TechQA leaderboard has been sunset since April 2023. 2 | 3 | The dataset is available [here](https://ibm.biz/techqa_data). 4 | 5 | 6 | 7 | # TechQA Submission Docker 8 | 9 | This page contains instructions about how to make a docker submission to the [TechQA leaderboard](https://leaderboard.techqa.us-east.containers.appdomain.cloud) 10 | 11 | This docker image runs a single model for prediction and can decode on GPUs. Note that this docker setup has only been tested with BERT models (not RoBERTa etc.), so other models may require modification of these files to work. 12 | 13 | Note: All submissions to the leaderboard run without any network access. Please make sure to have downloaded all external resources during image construction. For example, if you need a standard public BERT model, it must be in the image you submit because the image will not be able to download it from the network. 14 | 15 | ## Building Image 16 | 17 | 1) Move the trained model, vocabulary and tokenizer files into the folder `models`. You may need to create the `models` directory if this is your first time building the image. A sample `models` folder with a BERT model would have the following files: `config.json, pytorch_model.bin, special_tokens_map.json, tokenizer_config.json, vocab.txt` 18 | 19 | 2) Update the `MODEL_TYPE` environment variable in the [Dockerfile](./Dockerfile) if needed. 20 | 3) Update the [submission script](./submission.sh) with any command line parameters that need to be changed for 21 | your submission (e.g. `threshold`, `add_doc_title`, etc.) 22 | 4) Run from project's top level directory: 23 | ```docker build -f ./docker/techqa/Dockerfile -t techqa: .``` 24 | 25 | ## Running Image 26 | 27 | To test the image on the validation set, run: 28 | 29 | ``` 30 | nvidia-docker run --rm -e CUDA_VISIBLE_DEVICES=0 --network none -v :/var/spool/TechQA/input/:ro -v :/var/spool/TechQA/output -e DEV_INPUT_CORPUS=/var/spool/TechQA/input/documents.json techqa: 31 | ``` 32 | 33 | ## Notes 34 | 35 | - If you want to see how the image performs without network access, 36 | add `--network none` to the `docker run` command. 37 | - Replace `CUDA_VISIBLE_DEVICES` with the comma-separated GPU ids to run on, 38 | or omit to run on all GPUS. 39 | - Remove `--rm` to prevent container from being removed after stopping. 40 | - You can override the input query file with `-e DEV_QUERY_FILE=/var/spool/TechQA/input/validation_questions.json`, 41 | the same can be done for corpus file `DEV_INPUT_CORPUS` and output file `DEV_OUTPUT_FILE` (defaults in the [Dockerfile](./Dockerfile)). 42 | - If you have Docker 19.03 or later, `nvidia-docker` is no longer needed as NVIDIA GPUs are natively supported in Docker. 43 | See the [documentation](https://github.com/NVIDIA/nvidia-docker#quickstart) for more information. 44 | - It is good etiquette to run our commands within the container as a user other than root. Please consider doing so. See the [USER command](https://docs.docker.com/engine/reference/builder/#user) in the docker documentation for details and examples. 45 | 46 | ## Submitting to TechQA leaderboard 47 | 48 | 1) Build Image 49 | 2) Test Image 50 | 3) Push image to your docker registry 51 | 4) Go to the submission site: https://leaderboard.techqa.us-east.containers.appdomain.cloud 52 | 5) Login to your account (which you created to access the training set, dev set and Technotes corpus). 53 | 6) Click on the `Create Submission` button to see the submission form. 54 | 55 | -------------------------------------------------------------------------------- /docker/techqa/environment-techqa.yml: -------------------------------------------------------------------------------- 1 | name: base 2 | channels: 3 | - defaults 4 | - conda-forge 5 | dependencies: 6 | - python=3.6 7 | - boto3 8 | - transformers=2.5.1 9 | - tensorflow=1.13 10 | - tensorboardx=1.7 11 | - pyyaml=3.13 12 | - tornado=5 13 | - git 14 | - configargparse=0.14 15 | - nltk=3.4 16 | - pandas=0.24 17 | - pandasql=0.7 18 | - xlrd=1.2 19 | - pip: 20 | - sacremoses 21 | - sentencepiece -------------------------------------------------------------------------------- /docker/techqa/submission.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -xeo pipefail 3 | . /opt/conda/etc/profile.d/conda.sh 4 | conda activate base 5 | 6 | set -u # This is after conda setup as conda setup has unbound vars which trigger it 7 | 8 | if [[ "$#" -ne 3 ]]; then 9 | echo "Usage: bash submission.sh QUERY_FILE INPUT_CORPUS OUTPUT_FILE" 10 | fi 11 | 12 | QUERY_FILE="${1}" 13 | CORPUS_FILE="${2}" 14 | OUTPUT_FILE="${3}" 15 | 16 | SCRIPT_LOCATION="run_techqa.py" 17 | 18 | # Input data in readonly volume, need to symlink into container for featurization to work 19 | function symlink_and_return_name() { 20 | SOURCE="$(realpath ${1})" 21 | TARGET_DIR="$(realpath ${2})" 22 | TARGET="${TARGET_DIR}/$(basename ${SOURCE})" 23 | ln -s "${SOURCE}" "${TARGET}" 24 | echo "${TARGET}" 25 | } 26 | 27 | SYMLINKED_QUERY_PATH=$(symlink_and_return_name "${QUERY_FILE}" "${SYMLINK_DIR}") 28 | SYMLINKED_CORPUS_PATH=$(symlink_and_return_name "${CORPUS_FILE}" "${SYMLINK_DIR}") 29 | 30 | python ${SCRIPT_LOCATION} \ 31 | --model_type "${MODEL_TYPE}" --model_name_or_path "${MODEL_WEIGHTS}" --do_lower_case \ 32 | --tokenizer_name "${MODEL_WEIGHTS}" \ 33 | --fp16 --do_eval --predict_file ${SYMLINKED_QUERY_PATH} --input_corpus_file ${SYMLINKED_CORPUS_PATH} \ 34 | --overwrite_output_dir --output_dir ${TMP_OUTPUT_DIR} --add_doc_title_to_passage --threshold 23.912109375 35 | 36 | # Copy predictions 37 | cp ${TMP_OUTPUT_DIR}/predictions.json ${OUTPUT_FILE} -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | torch==1.2.0 2 | transformers==2.5.1 3 | tensorboardX==1.7 -------------------------------------------------------------------------------- /run_techqa.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import glob 3 | import logging 4 | import os 5 | from os import path 6 | import random 7 | import timeit 8 | import json 9 | from functools import partial 10 | import numpy as np 11 | import torch 12 | from math import ceil 13 | from torch.utils.data import DataLoader, RandomSampler 14 | from torch.utils.data.distributed import DistributedSampler 15 | from tqdm import tqdm, trange 16 | 17 | from transformers import ( 18 | WEIGHTS_NAME, 19 | AdamW, 20 | BertConfig, 21 | BertForQuestionAnswering, 22 | BertTokenizer, 23 | RobertaConfig, 24 | RobertaForQuestionAnswering, 25 | RobertaTokenizer, 26 | get_linear_schedule_with_warmup 27 | ) 28 | from techqa_metrics import predict_output 29 | from techqa_processor import load_and_cache_examples 30 | 31 | try: 32 | from torch.utils.tensorboard import SummaryWriter 33 | except ImportError: 34 | from tensorboardX import SummaryWriter 35 | 36 | 37 | logger = logging.getLogger(__name__) 38 | 39 | ALL_MODELS = sum( 40 | ( 41 | tuple(BertConfig.pretrained_config_archive_map.keys()) 42 | for conf in (BertConfig, RobertaConfig) 43 | ), 44 | (), 45 | ) 46 | 47 | MODEL_CLASSES = { 48 | "bert": (BertConfig, BertForQuestionAnswering, BertTokenizer), 49 | "roberta": (RobertaConfig, RobertaForQuestionAnswering, RobertaTokenizer), 50 | } 51 | 52 | OUTPUT_DIRNAME_FOR_MODEL_WEIGHTS = 'pytorch_model_epoch_%d' 53 | 54 | TEXT_ENCODING = 'utf-8' 55 | 56 | def set_seed(args): 57 | random.seed(args.seed) 58 | np.random.seed(args.seed) 59 | torch.manual_seed(args.seed) 60 | if args.n_gpu > 0: 61 | torch.cuda.manual_seed_all(args.seed) 62 | 63 | def load_model(args, model_class, config): 64 | model = model_class.from_pretrained( 65 | args.model_name_or_path, 66 | from_tf=bool(".ckpt" in args.model_name_or_path), 67 | config=config, 68 | cache_dir=args.cache_dir if args.cache_dir else None, 69 | ) 70 | 71 | if args.local_rank == 0: 72 | # Make sure only the first process in distributed training will download model & vocab 73 | torch.distributed.barrier() 74 | 75 | model.to(args.device) 76 | 77 | if args.do_train: 78 | 79 | parameters_to_optimize = list(model.named_parameters()) 80 | no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight'] 81 | optimizer_grouped_parameters = [ 82 | {'params': [p for n, p in parameters_to_optimize if 83 | not any(nd in n for nd in no_decay)], 84 | 'weight_decay': args.weight_decay}, 85 | {'params': [p for n, p in parameters_to_optimize if any(nd in n for nd in no_decay)], 86 | 'weight_decay': 0.0} 87 | ] 88 | optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, 89 | eps=args.adam_epsilon, betas=(args.adam_beta1, args.adam_beta2), correct_bias=False) 90 | else: 91 | optimizer = None 92 | 93 | if args.fp16: 94 | if optimizer is not None: 95 | model, optimizer = amp.initialize(model, optimizer, opt_level=args.fp16_opt_level) 96 | else: 97 | model = amp.initialize(model, opt_level=args.fp16_opt_level) 98 | 99 | # multi-gpu training (should be after apex fp16 initialization) 100 | if args.n_gpu > 1: 101 | model = torch.nn.DataParallel(model) 102 | 103 | # Distributed training (should be after apex fp16 initialization) 104 | if args.local_rank != -1: 105 | model = torch.nn.parallel.DistributedDataParallel( 106 | model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True 107 | ) 108 | 109 | return model, optimizer 110 | 111 | 112 | def train(args, train_dataset, model, optimizer, tokenizer, model_evaluator): 113 | """ Train the model """ 114 | if args.local_rank in [-1, 0]: 115 | tb_writer = SummaryWriter(logdir=path.join(args.output_dir, 'tensorboard')) 116 | 117 | args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) 118 | train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 else DistributedSampler(train_dataset) 119 | train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size) 120 | 121 | if args.max_steps > 0: 122 | t_total = args.max_steps 123 | args.num_train_epochs = args.max_steps // (len(train_dataloader) // args.gradient_accumulation_steps) + 1 124 | else: 125 | t_total = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs 126 | 127 | # Prepare optimizer and schedule (linear warmup and decay) 128 | warmup_steps = ceil(args.warmup_proportion * t_total) 129 | scheduler = get_linear_schedule_with_warmup( 130 | optimizer, num_warmup_steps=warmup_steps, num_training_steps=t_total 131 | ) 132 | 133 | # Train! 134 | logger.info("***** Running training *****") 135 | logger.info(" Num examples = %d", len(train_dataset)) 136 | logger.info(" Num Epochs = %d", args.num_train_epochs) 137 | logger.info(" Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size) 138 | logger.info( 139 | " Total train batch size (w. parallel, distributed & accumulation) = %d", 140 | args.train_batch_size 141 | * args.gradient_accumulation_steps 142 | * (torch.distributed.get_world_size() if args.local_rank != -1 else 1), 143 | ) 144 | logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps) 145 | logger.info(" Total optimization steps = %d", t_total) 146 | 147 | global_step = 1 148 | epochs_trained = 0 149 | steps_trained_in_current_epoch = 0 150 | # Check if continuing training from a checkpoint 151 | if os.path.exists(args.model_name_or_path): 152 | try: 153 | # set global_step to gobal_step of last saved checkpoint from model path 154 | checkpoint_suffix = args.model_name_or_path.split("-")[-1].split("/")[0] 155 | global_step = int(checkpoint_suffix) 156 | epochs_trained = global_step // (len(train_dataloader) // args.gradient_accumulation_steps) 157 | steps_trained_in_current_epoch = global_step % (len(train_dataloader) // args.gradient_accumulation_steps) 158 | 159 | logger.info(" Continuing training from checkpoint, will skip to saved global_step") 160 | logger.info(" Continuing training from epoch %d", epochs_trained) 161 | logger.info(" Continuing training from global step %d", global_step) 162 | logger.info(" Will skip the first %d steps in the first epoch", steps_trained_in_current_epoch) 163 | except ValueError: 164 | logger.info(" Starting fine-tuning.") 165 | 166 | tr_loss, logging_loss = 0.0, 0.0 167 | model.zero_grad() 168 | train_iterator = trange( 169 | epochs_trained, int(args.num_train_epochs), desc="Epoch", disable=args.local_rank not in [-1, 0] 170 | ) 171 | # Added here for reproductibility 172 | set_seed(args) 173 | 174 | for _ in train_iterator: 175 | train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 else DistributedSampler(train_dataset) 176 | train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size) 177 | epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0]) 178 | for step, batch in enumerate(epoch_iterator): 179 | 180 | # Skip past any already trained steps if resuming training 181 | if steps_trained_in_current_epoch > 0: 182 | steps_trained_in_current_epoch -= 1 183 | continue 184 | 185 | model.train() 186 | batch = tuple(t.to(args.device) for t in batch) 187 | 188 | inputs = { 189 | "input_ids": batch[0], 190 | "attention_mask": batch[1], 191 | "token_type_ids": batch[2], 192 | "start_positions": batch[3], 193 | "end_positions": batch[4], 194 | } 195 | 196 | if args.model_type in ["roberta"]: 197 | del inputs["token_type_ids"] 198 | 199 | outputs = model(**inputs) 200 | # model outputs are always tuple in transformers (see doc) 201 | loss = outputs[0] 202 | 203 | if args.n_gpu > 1: 204 | loss = loss.mean() # mean() to average on multi-gpu parallel (not distributed) training 205 | if args.gradient_accumulation_steps > 1: 206 | loss = loss / args.gradient_accumulation_steps 207 | 208 | if args.fp16: 209 | with amp.scale_loss(loss, optimizer) as scaled_loss: 210 | scaled_loss.backward() 211 | else: 212 | loss.backward() 213 | 214 | tr_loss += loss.item() 215 | if (step + 1) % args.gradient_accumulation_steps == 0: 216 | if args.fp16: 217 | torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm) 218 | else: 219 | torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm) 220 | 221 | optimizer.step() 222 | scheduler.step() # Update learning rate schedule 223 | model.zero_grad() 224 | global_step += 1 225 | 226 | # Log metrics 227 | if args.local_rank in [-1, 0] and args.logging_steps > 0 and global_step % args.logging_steps == 0: 228 | # Only evaluate when single GPU otherwise metrics may not average well 229 | if args.local_rank == -1 and args.evaluate_during_training: 230 | results = evaluate(args, model, tokenizer) 231 | for key, value in results.items(): 232 | tb_writer.add_scalar("eval_{}".format(key), value, global_step) 233 | tb_writer.add_scalar("lr", scheduler.get_lr()[0], global_step) 234 | tb_writer.add_scalar("loss", (tr_loss - logging_loss) / args.logging_steps, global_step) 235 | logging_loss = tr_loss 236 | 237 | if args.max_steps > 0 and global_step > args.max_steps: 238 | epoch_iterator.close() 239 | break 240 | 241 | epochs_trained += 1 242 | if model_evaluator is not None: 243 | # Evaluate model after each epoch 244 | model_evaluator(model=model, epoch=epochs_trained) 245 | 246 | if args.local_rank in [-1, 0]: 247 | output_dir = path.join(args.output_dir, 248 | OUTPUT_DIRNAME_FOR_MODEL_WEIGHTS % epochs_trained) 249 | logging.debug('Saving model %s to output dir: %s' % (model, output_dir)) 250 | # Create output directory if needed 251 | if not os.path.exists(output_dir): 252 | os.makedirs(output_dir) 253 | 254 | # Save a trained model, configuration and tokenizer using `save_pretrained()`. 255 | # They can then be reloaded using `from_pretrained()` 256 | # Take care of distributed/parallel training 257 | model_to_save = model.module if hasattr(model, "module") else model 258 | model_to_save.save_pretrained(output_dir) 259 | tokenizer.save_pretrained(output_dir) 260 | 261 | if args.max_steps > 0 and global_step > args.max_steps: 262 | train_iterator.close() 263 | break 264 | 265 | if args.local_rank in [-1, 0]: 266 | tb_writer.close() 267 | 268 | return model 269 | 270 | def main(): 271 | parser = argparse.ArgumentParser() 272 | 273 | # Required parameters 274 | parser.add_argument( 275 | "--model_type", 276 | default=None, 277 | type=str, 278 | required=True, 279 | help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()), 280 | ) 281 | parser.add_argument( 282 | "--model_name_or_path", 283 | default=None, 284 | type=str, 285 | required=True, 286 | help="Path to pre-trained model or shortcut name selected in the list: " + ", ".join(ALL_MODELS), 287 | ) 288 | parser.add_argument( 289 | "--output_dir", 290 | default=None, 291 | type=str, 292 | required=True, 293 | help="The output directory where the model checkpoints and predictions will be written.", 294 | ) 295 | 296 | # Other parameters 297 | parser.add_argument( 298 | "--data_dir", 299 | default=None, 300 | type=str, 301 | help="The input data dir. Should contain the .json files for the task." 302 | + "If no data dir or train/predict files are specified, will run with tensorflow_datasets.", 303 | ) 304 | parser.add_argument( 305 | "--train_file", 306 | default=None, 307 | type=str, 308 | help="The input training file. If a data dir is specified, will look for the file there" 309 | + "If no data dir or train/predict files are specified, will run with tensorflow_datasets.", 310 | ) 311 | parser.add_argument( 312 | "--predict_file", 313 | default=None, 314 | type=str, 315 | help="The input evaluation file. If a data dir is specified, will look for the file there" 316 | + "If no data dir or train/predict files are specified, will run with tensorflow_datasets.", 317 | ) 318 | parser.add_argument('--input_corpus_file', 319 | type=str, required=True, 320 | help="json file containing the corpus as a dictionary with doc id as key") 321 | parser.add_argument( 322 | "--config_name", default="", type=str, help="Pretrained config name or path if not the same as model_name" 323 | ) 324 | parser.add_argument( 325 | "--tokenizer_name", 326 | default="", 327 | type=str, 328 | help="Pretrained tokenizer name or path if not the same as model_name", 329 | ) 330 | parser.add_argument( 331 | "--cache_dir", 332 | default="", 333 | type=str, 334 | help="Where do you want to store the pre-trained models downloaded from s3", 335 | ) 336 | parser.add_argument('--threshold', type=float, default=None, 337 | help='Optionally provide a threshold to use for deciding whether to predict actual span' 338 | ' or leave question unanswered. If one is not provided, the "best" one is chosen' 339 | ' based on the ground truth in the query file. ') 340 | 341 | parser.add_argument( 342 | "--max_seq_length", 343 | default=512, 344 | type=int, 345 | help="The maximum total input sequence length after WordPiece tokenization. Sequences " 346 | "longer than this will be truncated, and sequences shorter than this will be padded.", 347 | ) 348 | parser.add_argument( 349 | "--doc_stride", 350 | default=192, 351 | type=int, 352 | help="When splitting up a long document into chunks, how much stride to take between chunks.", 353 | ) 354 | parser.add_argument( 355 | "--max_query_length", 356 | default=200, 357 | type=int, 358 | help="The maximum number of tokens for the question. Questions longer than this will " 359 | "be truncated to this length.", 360 | ) 361 | parser.add_argument("--do_train", action="store_true", help="Whether to run training.") 362 | parser.add_argument("--do_eval", action="store_true", help="Whether to run eval on the dev set.") 363 | parser.add_argument( 364 | "--evaluate_during_training", action="store_true", help="Run evaluation during training at each logging step." 365 | ) 366 | parser.add_argument( 367 | "--do_lower_case", action="store_true", help="Set this flag if you are using an uncased model." 368 | ) 369 | 370 | parser.add_argument("--per_gpu_train_batch_size", default=4, type=int, help="Batch size per GPU/CPU for training.") 371 | parser.add_argument("--predict_batch_size", default=16, type=int, 372 | help="Total batch size for predictions.") 373 | parser.add_argument("--learning_rate", default=4e-5, type=float, help="The initial learning rate for Adam.") 374 | parser.add_argument( 375 | "--gradient_accumulation_steps", 376 | type=int, 377 | default=16, 378 | help="Number of updates steps to accumulate before performing a backward/update pass.", 379 | ) 380 | parser.add_argument("--weight_decay", default=0.0, type=float, help="Weight decay if we apply some.") 381 | parser.add_argument("--adam_epsilon", default=1e-8, type=float, 382 | help="Epsilon for Adam optimizer.") 383 | parser.add_argument("--adam_beta1", default=0.9, type=float, help="Beta_1 for Adam optimizer.") 384 | parser.add_argument("--adam_beta2", default=0.999, type=float, help='Beta_2 for Adam optimizer') 385 | parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.") 386 | parser.add_argument( 387 | "--num_train_epochs", default=20.0, type=float, help="Total number of training epochs to perform." 388 | ) 389 | parser.add_argument( 390 | "--max_steps", 391 | default=-1, 392 | type=int, 393 | help="If > 0: set total number of training steps to perform. Override num_train_epochs.", 394 | ) 395 | parser.add_argument("--warmup_proportion", default=0.1, type=float, 396 | help="Proportion of training to perform linear learning rate warmup for" 397 | " Bert Adam. E.g., 0.1=10%% of training.") 398 | parser.add_argument("--n_best_size", default=20, type=int, 399 | help="The number (each) of start/end logits to track per feature when scoring.") 400 | parser.add_argument("--n_to_predict", default=20, type=int, 401 | help="The number of predictions to save for each " 402 | "example for analysis / ensembling (aka the `k` for the top k " 403 | "predictions setting). NOTE: these additional predictions are not" 404 | " used for evaluation...only the top answer is used for evaluation") 405 | parser.add_argument( 406 | "--max_answer_length", 407 | default=250, 408 | type=int, 409 | help="The maximum length of an answer that can be generated. This is needed because the start " 410 | "and end predictions are not conditioned on one another.", 411 | ) 412 | parser.add_argument( 413 | "--verbose_logging", 414 | action="store_true", 415 | help="If true, all of the warnings related to data processing will be printed. " 416 | "A number of warnings are expected for a normal SQuAD evaluation.", 417 | ) 418 | 419 | parser.add_argument("--logging_steps", type=int, default=500, help="Log every X updates steps.") 420 | parser.add_argument("--save_steps", type=int, default=500, help="Save checkpoint every X updates steps.") 421 | parser.add_argument( 422 | "--eval_all_checkpoints", 423 | action="store_true", 424 | help="Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number", 425 | ) 426 | parser.add_argument("--no_cuda", action="store_true", help="Whether not to use CUDA when available") 427 | parser.add_argument( 428 | "--overwrite_output_dir", action="store_true", help="Overwrite the content of the output directory" 429 | ) 430 | parser.add_argument( 431 | "--overwrite_cache", action="store_true", help="Overwrite the cached training and evaluation sets" 432 | ) 433 | parser.add_argument("--seed", type=int, default=42, help="random seed for initialization") 434 | 435 | parser.add_argument('--negative_sampling_prob_when_has_answer', 436 | type=float, default=0.1, 437 | help="Only used when preparing training features, not for decoding. " 438 | " This ratio will be used when the example has a short answer, but" 439 | " the span does not. Specifically we will keep NO_ANSWER spans" 440 | " with probability ${negative_sampling_prob_when_has_answer}") 441 | 442 | parser.add_argument('--negative_sampling_prob_when_no_answer', 443 | type=float, default=0.15, 444 | help="Only used when preparing training features, not for decoding. " 445 | "This ratio will be used when the example has NO short answer. " 446 | "Specifically we will keep spans from this example " 447 | "with probability ${negative_sampling_prob_when_has_answer}") 448 | parser.add_argument('--add_doc_title_to_passage', 449 | action='store_true', 450 | help="Whether to add document title to each passage in feature generation") 451 | 452 | parser.add_argument("--local_rank", type=int, default=-1, help="local_rank for distributed training on gpus") 453 | parser.add_argument( 454 | "--fp16", 455 | action="store_true", 456 | help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit", 457 | ) 458 | parser.add_argument( 459 | "--fp16_opt_level", 460 | type=str, 461 | default="O1", 462 | help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." 463 | "See details at https://nvidia.github.io/apex/amp.html", 464 | ) 465 | parser.add_argument("--server_ip", type=str, default="", help="Can be used for distant debugging.") 466 | parser.add_argument("--server_port", type=str, default="", help="Can be used for distant debugging.") 467 | 468 | parser.add_argument("--threads", type=int, default=1, help="multiple threads for converting example to features") 469 | args = parser.parse_args() 470 | 471 | if args.doc_stride >= args.max_seq_length - args.max_query_length: 472 | logger.warning( 473 | "WARNING - You've set a doc stride which may be superior to the document length in some " 474 | "examples. This could result in errors when building features from the examples. Please reduce the doc " 475 | "stride or increase the maximum length to ensure the features are correctly built." 476 | ) 477 | 478 | if args.fp16: 479 | try: 480 | from apex import amp 481 | # HACK: dirty trick to import amp once so that it's accessible outside this method 482 | globals()['amp'] = amp 483 | except ImportError: 484 | raise ImportError( 485 | "Please install apex from https://www.github.com/nvidia/apex to use fp16 training.") 486 | 487 | if ( 488 | os.path.exists(args.output_dir) 489 | and os.listdir(args.output_dir) 490 | and args.do_train 491 | and not args.overwrite_output_dir 492 | ): 493 | raise ValueError( 494 | "Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.".format( 495 | args.output_dir 496 | ) 497 | ) 498 | 499 | # Setup CUDA, GPU & distributed training 500 | if args.local_rank == -1 or args.no_cuda: 501 | device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu") 502 | args.n_gpu = 0 if args.no_cuda else torch.cuda.device_count() 503 | else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs 504 | torch.cuda.set_device(args.local_rank) 505 | device = torch.device("cuda", args.local_rank) 506 | torch.distributed.init_process_group(backend="nccl") 507 | args.n_gpu = 1 508 | args.device = device 509 | 510 | # Setup logging 511 | logging.basicConfig( 512 | format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", 513 | datefmt="%m/%d/%Y %H:%M:%S", 514 | level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN, 515 | ) 516 | logger.warning( 517 | "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", 518 | args.local_rank, 519 | device, 520 | args.n_gpu, 521 | bool(args.local_rank != -1), 522 | args.fp16, 523 | ) 524 | 525 | # Set seed 526 | set_seed(args) 527 | 528 | # Load pretrained model and tokenizer 529 | if args.local_rank not in [-1, 0]: 530 | # Make sure only the first process in distributed training will download model & vocab 531 | torch.distributed.barrier() 532 | 533 | args.model_type = args.model_type.lower() 534 | config_class, model_class, tokenizer_class = MODEL_CLASSES[args.model_type] 535 | config = config_class.from_pretrained( 536 | args.config_name if args.config_name else args.model_name_or_path, 537 | cache_dir=args.cache_dir if args.cache_dir else None, 538 | ) 539 | tokenizer = tokenizer_class.from_pretrained( 540 | args.tokenizer_name if args.tokenizer_name else args.model_name_or_path, 541 | do_lower_case=args.do_lower_case, 542 | cache_dir=args.cache_dir if args.cache_dir else None, 543 | ) 544 | 545 | logger.info("Training/evaluation parameters %s", args) 546 | 547 | # Before we do anything with models, we want to ensure that we get fp16 execution of torch.einsum if args.fp16 is set. 548 | # Otherwise it'll default to "promote" mode, and we'll get fp32 operations. Note that running `--fp16_opt_level="O2"` will 549 | # remove the need for this code, but it is still valid. 550 | if args.fp16: 551 | try: 552 | import apex 553 | 554 | apex.amp.register_half_function(torch, "einsum") 555 | except ImportError: 556 | raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.") 557 | 558 | model, optimizer = load_model(args, model_class, config) 559 | 560 | if args.do_train: 561 | train_dataset = load_and_cache_examples(args, tokenizer, evaluate=False, output_examples=False) 562 | 563 | if args.do_eval: 564 | test_dataset, test_features, gold_dict = load_and_cache_examples(args, tokenizer, evaluate=True, output_examples=True) 565 | with open(args.input_corpus_file, encoding=TEXT_ENCODING) as infile: 566 | corpus = json.load(infile) 567 | 568 | model_evaluator = partial( 569 | predict_output, 570 | model_type=args.model_type, device=args.device, eval_features=test_features, 571 | eval_dataset=test_dataset, 572 | predict_batch_size=args.predict_batch_size, 573 | nbest_size=args.n_best_size, n_to_predict=args.n_to_predict, 574 | max_answer_length=args.max_answer_length, output_dir=args.output_dir, 575 | gold_dict=gold_dict, 576 | corpus=corpus, 577 | threshold=args.threshold) 578 | else: 579 | model_evaluator = None 580 | 581 | # Create output directory if needed 582 | if not os.path.exists(args.output_dir) and args.local_rank in [-1, 0]: 583 | os.makedirs(args.output_dir) 584 | # Good practice: save your training arguments together with the trained model 585 | torch.save(args, os.path.join(args.output_dir, "training_args.bin")) 586 | 587 | # Training 588 | if args.do_train: 589 | model = train(args, train_dataset, model, optimizer, tokenizer, model_evaluator) 590 | 591 | if model_evaluator is not None: 592 | model_evaluator(model=model) 593 | 594 | if __name__ == "__main__": 595 | main() -------------------------------------------------------------------------------- /synthetic/README.md: -------------------------------------------------------------------------------- 1 | This repo contains scripts to create the synthetic data used in the EMNLP 2020 paper "Multi-Stage Pre-training for Low-Resource Domain Adaptation" 2 | -------------------------------------------------------------------------------- /techqa_evaluation.py: -------------------------------------------------------------------------------- 1 | import collections 2 | import json 3 | import logging 4 | import sys 5 | 6 | import argparse 7 | from typing import Dict, List, Tuple, Optional, Union 8 | 9 | _NEGATIVE_INFINITY = float('-inf') 10 | _DEFAULT_TOP_K = 5 11 | 12 | 13 | class EVAL_OPTS(): 14 | def __init__(self, data_file, pred_file, out_file="", top_k=5, 15 | out_image_dir=None, verbose=False): 16 | self.data_file = data_file 17 | self.pred_file = pred_file 18 | self.out_file = out_file 19 | self.verbose = verbose 20 | self.top_k = top_k 21 | 22 | 23 | OPTS = EVAL_OPTS(data_file=None, pred_file=None) 24 | 25 | ScoresById = Dict[str, Union[int, float]] 26 | TopKScoresById = Dict[str, List[Union[int, float]]] 27 | 28 | 29 | def parse_args(): 30 | parser = argparse.ArgumentParser( 31 | """ 32 | Official evaluation script for TechQA v1. It will produce the following metrics: 33 | 34 | - "QA_F1": Calculated for precision/recall based on character offset. The threshold 35 | provided in the prediction json will be applied to predict NO ANSWER in cases 36 | where the prediction score < threshold. 37 | 38 | - "IR_Precision": Calculated based on doc id match. The threshold provided in the 39 | prediction json will be applied to predict NO ANSWER in cases where the prediction 40 | score < threshold. 41 | 42 | - "HasAns_QA_F1": Same as `QA_F1`, but calculated only on answerable questions. 43 | Thresholds are ignored for this calculation. 44 | 45 | - "HasAns_Top_k_QA_F1": The max `QA_F1` based on the top `k` predictions calculated 46 | only on answerable questions. Thresholds are ignored for this calculation. 47 | By default k=%d. 48 | 49 | - "HasAns_IR_Precision": Same as `IR_Precision`, but calculated only on answerable 50 | questions. Thresholds are ignored for this calculation. 51 | 52 | - "HasAns_Top_k_IR_Precision": The max `IR_Precision` based on the top `k` predictions 53 | calculated only on answerable questions. Thresholds are ignored for this calculation. 54 | By default k=%d. 55 | 56 | - "Best_QA_F1": Same as `QA_F1`, but instead of applying the provided threshold, it 57 | will scan for the `optimal` threshold based on the evaluation set. 58 | 59 | - "Best_QA_F1_Threshold": The threshold identified during the search for `Best_QA_F1` 60 | 61 | - "_Total_Questions": All metrics will be accompanied by a `_Total_Questions` count of 62 | the number of queries used to compute the statistic. 63 | """ % (_DEFAULT_TOP_K, _DEFAULT_TOP_K)) 64 | parser.add_argument('data_file', metavar='dev_vX.json', 65 | help='Input competition query annotations JSON file.') 66 | parser.add_argument('pred_file', metavar='pred.json', 67 | help= 68 | """ 69 | Model predictions JSON file in the format: 70 | { 71 | "threshold": 0, 72 | "predictions": { 73 | "QID1": [ 74 | { 75 | "doc_id": "swg234", 76 | "score": 3.4, 77 | "start_offset": 0, 78 | "end_offset": 100 79 | }, 80 | { 81 | "doc_id": "swg234", 82 | "score": 3, 83 | "start_offset": 50, 84 | "end_offset": 100 85 | }... 86 | ], 87 | "QID2": [ 88 | { 89 | "doc_id": "", 90 | "score": 0, 91 | "start_offset": -1, 92 | "end_offset": -1 93 | }, 94 | { 95 | "doc_id": "swg123", 96 | "score": -1, 97 | "start_offset": 20, 98 | "end_offset": 30 99 | }... 100 | ]... 101 | } 102 | } 103 | """) 104 | parser.add_argument('--out-file', '-o', metavar='eval.json', 105 | help='Write accuracy metrics to file (default is stdout).') 106 | parser.add_argument('--top_k', '-k', type=int, default=_DEFAULT_TOP_K, 107 | help='Eval script will compute F1 score using the top 1 prediction' 108 | ' as well as the top k predictions') 109 | parser.add_argument('--verbose', '-v', action="store_const", const=logging.DEBUG, 110 | default=logging.INFO) 111 | if len(sys.argv) == 1: 112 | parser.print_help() 113 | sys.exit(1) 114 | return parser.parse_args() 115 | 116 | 117 | def make_qid_to_has_ans(dataset): 118 | qid_to_has_ans = {} 119 | for qid, q in dataset.items(): 120 | if 'ANSWERABLE' in q and q['ANSWERABLE'] == 'Y': 121 | qid_to_has_ans[qid] = True 122 | else: 123 | qid_to_has_ans[qid] = False 124 | 125 | return qid_to_has_ans 126 | 127 | 128 | def compute_f1(gold_start_offset, gold_end_offset, prediction_start_offset, prediction_end_offset): 129 | num_gold_chars = gold_end_offset - gold_start_offset 130 | num_pred_chars = prediction_end_offset - prediction_start_offset 131 | num_same_chars = max(0, 132 | min(gold_end_offset, prediction_end_offset) - max(gold_start_offset, 133 | prediction_start_offset)) 134 | if num_gold_chars == 0 or num_pred_chars == 0: 135 | # If either is no-answer, then F1 is 1 if they agree, 0 otherwise 136 | return int(num_gold_chars == num_pred_chars) 137 | if num_same_chars == 0: 138 | return 0 139 | precision = 1.0 * num_same_chars / num_pred_chars 140 | recall = 1.0 * num_same_chars / num_gold_chars 141 | f1 = (2 * precision * recall) / (precision + recall) 142 | return f1 143 | 144 | 145 | def get_raw_scores( 146 | dataset: Dict[str, Dict], preds: Dict[str, List[Dict]], 147 | qid_to_has_ans: Dict[str, bool], top_k: int) -> Tuple[ 148 | TopKScoresById, TopKScoresById, TopKScoresById]: 149 | prediction_scores_by_qid = {} 150 | f1_scores_by_qid = {} 151 | retrieval_accuracies_by_qid = {} 152 | 153 | for qid, q in dataset.items(): 154 | 155 | prediction_scores = list() 156 | f1_scores = list() 157 | retrieval_accuracies = list() 158 | if qid not in preds or len(preds[qid]) < 1: 159 | logging.warning('Missing predictions for %s; going to receive 0 points for it' % qid) 160 | # Force this score to be incorrect 161 | prediction_scores.append(float('inf')) 162 | f1_scores.append(0) 163 | retrieval_accuracies.append(0) 164 | else: 165 | if qid_to_has_ans[qid]: 166 | gold_doc_id = q['DOCUMENT'] 167 | gold_start_offset = int(q['START_OFFSET']) 168 | gold_end_offset = int(q['END_OFFSET']) 169 | else: 170 | gold_start_offset = -1 171 | gold_end_offset = -1 172 | gold_doc_id = '' 173 | 174 | for prediction in preds[qid][:top_k]: 175 | if gold_doc_id.strip() != prediction['doc_id'].strip(): 176 | f1_scores.append(0) 177 | retrieval_accuracies.append(0) 178 | else: 179 | f1_scores.append(compute_f1(gold_start_offset=gold_start_offset, 180 | gold_end_offset=gold_end_offset, 181 | prediction_start_offset=prediction['start_offset'], 182 | prediction_end_offset=prediction['end_offset'])) 183 | retrieval_accuracies.append(1) 184 | prediction_scores.append(prediction['score']) 185 | 186 | f1_scores_by_qid[qid] = f1_scores 187 | prediction_scores_by_qid[qid] = prediction_scores 188 | retrieval_accuracies_by_qid[qid] = retrieval_accuracies 189 | return f1_scores_by_qid, retrieval_accuracies_by_qid, prediction_scores_by_qid 190 | 191 | 192 | def apply_no_ans_threshold( 193 | eval_scores: TopKScoresById, answer_probabilities: TopKScoresById, 194 | qid_to_has_ans: Dict[str, bool], answer_threshold: float) -> Tuple[ScoresById, ScoresById]: 195 | top1_eval_scores = {} 196 | max_eval_scores = {} 197 | 198 | for qid, s in eval_scores.items(): 199 | # Check the top 1 prediction 200 | pred_na = answer_probabilities[qid][0] < answer_threshold 201 | if pred_na: 202 | top1_eval_scores[qid] = float(not qid_to_has_ans[qid]) 203 | else: 204 | top1_eval_scores[qid] = s[0] 205 | 206 | # Check all predictions 207 | if not qid_to_has_ans[qid] and any( 208 | score < answer_threshold for score in answer_probabilities[qid]): 209 | max_eval_scores[qid] = 1 210 | else: 211 | max_eval_scores[qid] = max(s) 212 | 213 | return top1_eval_scores, max_eval_scores 214 | 215 | 216 | def make_eval_dict(f1_scores_by_qid: ScoresById, retrieval_scores_by_qid: ScoresById, 217 | qid_list: Optional[set] = None) -> collections.OrderedDict: 218 | f1_score_sum = 0 219 | retrieval_score_sum = 0 220 | 221 | if not qid_list: 222 | qid_list = list(f1_scores_by_qid.keys()) 223 | 224 | total = len(qid_list) 225 | for qid in qid_list: 226 | f1_score_sum += f1_scores_by_qid[qid] 227 | retrieval_score_sum += retrieval_scores_by_qid[qid] 228 | 229 | return collections.OrderedDict([ 230 | ('QA_F1', 100.0 * f1_score_sum / total), 231 | ('IR_Precision', 100.0 * retrieval_score_sum / total), 232 | ('Total_Questions', total), 233 | ]) 234 | 235 | 236 | def merge_eval(main_eval, new_eval, prefix): 237 | for k in new_eval: 238 | main_eval['%s_%s' % (prefix, k)] = new_eval[k] 239 | 240 | 241 | def find_best_thresh(preds_by_qid, eval_scores_by_qid, qid_to_has_ans): 242 | num_no_ans = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]) 243 | cur_score = num_no_ans 244 | best_score = cur_score 245 | best_thresh = float('inf') 246 | qid_list = sorted(preds_by_qid.keys(), key=lambda qid: preds_by_qid[qid], reverse=True) 247 | for i, qid in enumerate(qid_list): 248 | if qid not in eval_scores_by_qid: continue 249 | if qid_to_has_ans[qid]: 250 | diff = eval_scores_by_qid[qid] 251 | else: 252 | if preds_by_qid[qid]: 253 | diff = -1 254 | else: 255 | diff = 0 256 | cur_score += diff 257 | if cur_score > best_score: 258 | best_score = cur_score 259 | best_thresh = preds_by_qid[qid] 260 | return 100.0 * best_score / len(eval_scores_by_qid), best_thresh 261 | 262 | 263 | def find_all_best_thresh(main_eval, preds, f1_raw, qid_to_has_ans): 264 | best_f1, f1_thresh = find_best_thresh(preds, f1_raw, qid_to_has_ans) 265 | main_eval['Best_QA_F1'] = best_f1 266 | main_eval['Best_QA_F1_Threshold'] = f1_thresh 267 | 268 | 269 | def main(OPTS): 270 | logging.basicConfig(level=OPTS.verbose) 271 | 272 | with open(OPTS.data_file, encoding='utf-8') as f: 273 | dataset = {query['QUESTION_ID']: query for query in json.load(f)} 274 | with open(OPTS.pred_file, encoding='utf-8') as f: 275 | system_output = json.load(f) 276 | threshold = system_output['threshold'] 277 | preds = system_output['predictions'] 278 | 279 | out_eval = evaluate(preds=preds, dataset=dataset, threshold=threshold) 280 | 281 | if OPTS.out_file: 282 | with open(OPTS.out_file, 'w') as f: 283 | json.dump(out_eval, f) 284 | else: 285 | print(json.dumps(out_eval, indent=2)) 286 | return out_eval 287 | 288 | 289 | def evaluate(preds: Dict[str, List[Dict]], dataset: Dict[str, Dict], 290 | threshold: float = _NEGATIVE_INFINITY): 291 | qid_to_has_ans = make_qid_to_has_ans(dataset) # maps qid to True/False 292 | has_ans_qids = {k for k, v in qid_to_has_ans.items() if v} 293 | 294 | # Calculate metrics without thresholding 295 | f1_raw_by_qid, retrieval_acc_raw_by_qid, pred_score_by_qid = \ 296 | get_raw_scores(dataset, preds, qid_to_has_ans, OPTS.top_k) 297 | top1_raw_retrieval_acc_by_qid = {qid: scores[0] for qid, scores in 298 | retrieval_acc_raw_by_qid.items()} 299 | topk_raw_retrieval_acc_by_qid = {qid: max(scores) for qid, scores in 300 | retrieval_acc_raw_by_qid.items()} 301 | top1_f1_raw_by_qid = {qid: scores[0] for qid, scores in f1_raw_by_qid.items()} 302 | topk_f1_raw_by_qid = {qid: max(scores) for qid, scores in f1_raw_by_qid.items()} 303 | top1_pred_score_by_qid = {qid: scores[0] for qid, scores in pred_score_by_qid.items()} 304 | 305 | # Calculating f1 with threshold 306 | top1_f1_thresh_by_qid, topk_f1_thresh_by_qid = apply_no_ans_threshold(f1_raw_by_qid, 307 | pred_score_by_qid, 308 | qid_to_has_ans, threshold) 309 | 310 | # Calculating doc retrieval accuracy with threshold 311 | top1_retrieval_acc_by_qid, topk_retrieval_acc_by_qid = \ 312 | apply_no_ans_threshold(retrieval_acc_raw_by_qid, pred_score_by_qid, 313 | qid_to_has_ans, threshold) 314 | 315 | # Create evaluation summary 316 | out_eval = make_eval_dict(top1_f1_thresh_by_qid, top1_retrieval_acc_by_qid) 317 | if has_ans_qids: 318 | merge_eval(out_eval, make_eval_dict(top1_f1_raw_by_qid, top1_raw_retrieval_acc_by_qid, 319 | qid_list=has_ans_qids), 'HasAns') 320 | merge_eval(out_eval, make_eval_dict(topk_f1_raw_by_qid, topk_raw_retrieval_acc_by_qid, 321 | qid_list=has_ans_qids), 322 | 'HasAns_Top_%d' % OPTS.top_k) 323 | 324 | # Find best threshold for top 1 f1 metric 325 | find_all_best_thresh(out_eval, top1_pred_score_by_qid, top1_f1_raw_by_qid, qid_to_has_ans) 326 | 327 | return out_eval 328 | 329 | 330 | if __name__ == '__main__': 331 | OPTS = parse_args() 332 | main(OPTS) -------------------------------------------------------------------------------- /techqa_metrics.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | import json 3 | import logging 4 | import os 5 | from collections import defaultdict 6 | 7 | import functools 8 | import torch 9 | from torch import nn 10 | from torch.utils.data import DataLoader, SequentialSampler 11 | from tqdm import tqdm 12 | from typing import List, Dict, Optional, Callable, Iterable 13 | 14 | from techqa_evaluation import evaluate 15 | from techqa_processor import TechQaInputFeature 16 | 17 | from torch.utils.data import TensorDataset 18 | 19 | _NEGATIVE_INFINITY = float('-inf') 20 | 21 | @functools.total_ordering 22 | class TechQAPrediction: 23 | def __init__(self, doc_id, start_offset, end_offset, score): 24 | self.doc_id = doc_id 25 | self.start_offset = start_offset 26 | self.end_offset = end_offset 27 | self.score = score 28 | 29 | def __hash__(self): 30 | return hash((self.doc_id, self.start_offset, self.end_offset, self.score)) 31 | 32 | def __lt__(self, other): 33 | return self.score < other.score 34 | 35 | def __eq__(self, other): 36 | return self.score == other.score 37 | 38 | 39 | class BestSpanTracker(object): 40 | __slots__ = ['n_logits_to_search', 'max_spans_to_track', 'top_n_spans', 'max_answer_length', 'score_calculator'] 41 | 42 | def __init__(self, n_logits_to_search: int, max_spans_to_track: int, max_answer_length: int, 43 | score_calculator: Callable): 44 | self.n_logits_to_search = n_logits_to_search 45 | self.max_spans_to_track = max_spans_to_track 46 | self.max_answer_length = max_answer_length 47 | self.top_n_spans = list() 48 | self.score_calculator = score_calculator 49 | 50 | def collect_best_non_null_spans(self, start_logits: List[float], end_logits: List[float], 51 | feature: TechQaInputFeature): 52 | 53 | null_span_score = end_logits[0] + start_logits[0] 54 | 55 | for start_idx, end_idx in self._get_start_end_scores_for_possible_spans( 56 | get_best_indexes(start_logits, self.n_logits_to_search), 57 | get_best_indexes(end_logits, self.n_logits_to_search), feature): 58 | self._update_top_n_spans( 59 | TechQAPrediction( 60 | doc_id=feature.doc_id, 61 | start_offset=feature.token_to_original_start_offset[start_idx], 62 | end_offset=feature.token_to_original_end_offset[end_idx], 63 | score=self.score_calculator( 64 | span_score=end_logits[end_idx] + start_logits[start_idx], 65 | null_span_score=null_span_score))) 66 | 67 | def _update_top_n_spans(self, prediction: TechQAPrediction): 68 | if len(self.top_n_spans) < self.max_spans_to_track: 69 | # Collect up to nbest_size spans 70 | heapq.heappush(self.top_n_spans, prediction) 71 | elif prediction.score > self.top_n_spans[0].score: 72 | # This span has a better score than the ones we've seen, so swap it into the set 73 | heapq.heapreplace(self.top_n_spans, prediction) 74 | 75 | def get_nbest_spans(self, n: int) -> List[TechQAPrediction]: 76 | return heapq.nlargest(n=n, iterable=self.top_n_spans) 77 | 78 | def _get_start_end_scores_for_possible_spans(self, start_indeces, end_indeces, feature): 79 | for start_index in start_indeces: 80 | for end_index in end_indeces: 81 | # This should be an actual span from the passage tokens, make sure that's 82 | # actually the case. We could hypothetically create invalid predictions, 83 | # e.g., predict that the start of the span is in the question. We throw out all 84 | # invalid predictions. 85 | if start_index >= len(feature.tokens): 86 | continue 87 | if end_index >= len(feature.tokens): 88 | continue 89 | if start_index not in feature.token_to_original_start_offset: 90 | continue 91 | if end_index not in feature.token_to_original_end_offset: 92 | continue 93 | if end_index < start_index: 94 | continue 95 | # We may have shuffled sentences during feature prep, so account for that 96 | if feature.token_to_original_start_offset[start_index] > \ 97 | feature.token_to_original_end_offset[ 98 | end_index]: 99 | continue 100 | length = end_index - start_index + 1 101 | if length > self.max_answer_length: 102 | continue 103 | yield start_index, end_index 104 | 105 | def to_list(tensor): 106 | return tensor.detach().cpu().tolist() 107 | 108 | def _save_predictions_to_output_dir(threshold, predictions, output_dir, epoch=-1): 109 | if epoch < 0: 110 | output_prediction_file = os.path.join(output_dir, "predictions.json") 111 | else: 112 | output_prediction_file = os.path.join(output_dir, "predictions_{}.json".format(epoch)) 113 | 114 | with open(output_prediction_file, "w") as outF: 115 | logging.info('Saving %d predictions to %s' % (len(predictions), output_prediction_file)) 116 | json.dump({'threshold': threshold, 'predictions': predictions}, outF, indent=2) 117 | 118 | def get_best_indexes(logits, n_best_size): 119 | """Get the n-best logits from a list.""" 120 | index_and_score = sorted(enumerate(logits), key=lambda x: x[1], 121 | reverse=True) 122 | 123 | best_indexes = [] 124 | for i in range(len(index_and_score)): 125 | if i >= n_best_size: 126 | break 127 | best_indexes.append(index_and_score[i][0]) 128 | return best_indexes 129 | 130 | def compute_score_diff_between_span_and_cls( 131 | span_score: float, null_span_score: float, *args, **kwargs): 132 | return span_score - null_span_score 133 | 134 | def predict_output(device, eval_features: List[TechQaInputFeature], eval_dataset: TensorDataset, 135 | gold_dict: Dict, corpus: Dict, model: nn.Module, model_type: str, 136 | nbest_size: int, max_answer_length: int, 137 | output_dir: str, predict_batch_size: int, 138 | threshold: Optional[float] = None, 139 | n_to_predict: Optional[int] = 1, epoch: Optional[int] = -1): 140 | logging.info("**** Starting Predict ****") 141 | logging.info("\tNum examples = %d", len(gold_dict)) 142 | logging.info("\tn_best_size = %d" % nbest_size) 143 | logging.info("\tn_to_predict = %d" % n_to_predict) 144 | logging.info('\tpredict batch size = %d' % predict_batch_size) 145 | logging.info('\tdefault threshold = %s' % threshold) 146 | logging.info("\tmodel type = %s" % model_type) 147 | model.eval() 148 | 149 | nbest_spans_by_example_id = defaultdict( 150 | lambda: BestSpanTracker(max_answer_length=max_answer_length, 151 | n_logits_to_search=nbest_size, max_spans_to_track=n_to_predict, 152 | score_calculator=compute_score_diff_between_span_and_cls)) 153 | progress_bar = tqdm(total=len(gold_dict), desc="Collecting best spans per question id") 154 | eval_sampler = SequentialSampler(eval_dataset) 155 | eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=predict_batch_size) 156 | 157 | for batch in eval_dataloader: 158 | batch = tuple(t.to(device) for t in batch) 159 | num_examples_so_far = len(nbest_spans_by_example_id) 160 | 161 | with torch.no_grad(): 162 | inputs = {'input_ids': batch[0], 163 | 'attention_mask': batch[1], 164 | 'token_type_ids': batch[2] 165 | } 166 | 167 | outputs = model(**inputs) 168 | feature_vector_indeces = batch[5] 169 | for i, feature_index in enumerate(feature_vector_indeces): 170 | output = [to_list(output[i]) for output in outputs] 171 | start_logits, end_logits = output 172 | 173 | input_feature = eval_features[feature_index.item()] 174 | 175 | nbest_spans_by_example_id[input_feature.qid].collect_best_non_null_spans( 176 | start_logits=start_logits, 177 | end_logits=end_logits, 178 | feature=input_feature) 179 | 180 | progress_bar.update(n=len(nbest_spans_by_example_id) - num_examples_so_far) 181 | 182 | progress_bar.close() 183 | 184 | predictions = dict() 185 | for query_id, nbest_spans_tracker in tqdm(nbest_spans_by_example_id.items(), 186 | 'Formatting predictions into eval format'): 187 | predictions[query_id] = _generate_predictions(nbest_spans_tracker=nbest_spans_tracker, 188 | n_to_predict=n_to_predict, corpus=corpus) 189 | 190 | logging.info('Evaluating predictions') 191 | if threshold is None: 192 | evaluation_scores = evaluate(preds=predictions, dataset=gold_dict) 193 | threshold = evaluation_scores['Best_QA_F1_Threshold'] 194 | else: 195 | logging.info('Using pre-configured threshold: %s' % threshold) 196 | evaluation_scores = evaluate(preds=predictions, dataset=gold_dict, threshold=threshold) 197 | 198 | logging.info('Done evaluating:\n%s' % evaluation_scores) 199 | _save_predictions_to_output_dir(threshold=threshold, 200 | predictions=predictions, output_dir=output_dir, epoch=epoch) 201 | return evaluation_scores 202 | 203 | 204 | def _generate_predictions(nbest_spans_tracker: BestSpanTracker, corpus: Dict, 205 | n_to_predict: int) -> List[Dict]: 206 | top_spans = nbest_spans_tracker.get_nbest_spans(n=n_to_predict) 207 | 208 | if len(top_spans) < 1: 209 | return [{'doc_id': '', 'answer': '', 'score': 0}] 210 | 211 | return [{'doc_id': prediction.doc_id, 212 | 'answer': corpus[prediction.doc_id]['text'][ 213 | prediction.start_offset:prediction.end_offset], 214 | 'start_offset': prediction.start_offset, 215 | 'end_offset': prediction.end_offset, 216 | 'score': prediction.score} for prediction in top_spans] -------------------------------------------------------------------------------- /techqa_processor.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | from copy import deepcopy 4 | from os import path 5 | from random import random 6 | import re 7 | from datetime import datetime 8 | from tqdm import tqdm 9 | import torch 10 | from typing import Optional, Iterable, List, Tuple, Dict 11 | 12 | from transformers import PreTrainedTokenizer, RobertaTokenizer 13 | from torch.utils.data import TensorDataset 14 | 15 | TEXT_ENCODING = 'utf-8' 16 | 17 | class TechQaInputFeature(object): 18 | """A single input vector for the model.""" 19 | 20 | __slots__ = ['qid', 'doc_id', 'doc_span_index', 'tokens', 'token_to_original_start_offset', 21 | 'token_to_original_end_offset', 22 | 'input_ids', 'input_mask', 'segment_ids', 'start_position', 'end_position'] 23 | 24 | def __init__(self, qid: str, doc_id: str, doc_span_index: int, tokens: List[str], 25 | token_to_original_start_offset: Dict[int, int], input_mask: List[int], 26 | token_to_original_end_offset: Dict[int, int], input_ids: List[int], 27 | segment_ids: List[int], start_position: Optional[int] = None, 28 | end_position: Optional[int] = None): 29 | self.qid = qid 30 | self.doc_id = doc_id 31 | self.doc_span_index = doc_span_index 32 | self.tokens = tokens 33 | self.token_to_original_start_offset = token_to_original_start_offset 34 | self.token_to_original_end_offset = token_to_original_end_offset 35 | self.input_ids = input_ids 36 | self.input_mask = input_mask 37 | self.segment_ids = segment_ids 38 | self.start_position = start_position 39 | self.end_position = end_position 40 | 41 | def __repr__(self): 42 | return self.__str__() 43 | 44 | def __str__(self) -> str: 45 | return "%s(%s)" % ( 46 | self.__class__.__name__, 47 | ",".join('%s=%s' % 48 | (attribute, getattr(self, attribute)) for attribute in self.__slots__)) 49 | 50 | 51 | class Span(object): 52 | __slots__ = ['start', 'end'] 53 | 54 | def __init__(self, start: int, end: int): 55 | self.start = start 56 | self.end = end 57 | 58 | if self.start != -1 and self.start > self.end: 59 | raise ValueError('Inconsistent span start (%d) and end (%d)' % (start, end)) 60 | 61 | def is_null_span(self): 62 | return self.start == -1 or self.end == -1 63 | 64 | def __contains__(self, other): 65 | if self.is_null_span(): 66 | return False 67 | elif isinstance(other, Span): 68 | if other.start >= self.start and other.end < self.end: 69 | return True 70 | else: 71 | return False 72 | else: 73 | return self.end > other >= self.start 74 | 75 | def __repr__(self): 76 | return self.__str__() 77 | 78 | def __str__(self) -> str: 79 | return "Span[boundaries=[%s,%s)]" % (self.start, self.end) 80 | 81 | def __hash__(self): 82 | return hash((self.start, self.end)) 83 | 84 | 85 | _NULL_SPAN = Span(start=-1, end=-1) 86 | 87 | 88 | class WordTokenizerWithCharOffsetTracking(object): 89 | # Create a Tokenizer with the default settings for English 90 | # including punctuation rules and exceptions 91 | 92 | @classmethod 93 | def tokenize(cls, text: str) -> List[Tuple[str, Span]]: 94 | def inner(text): 95 | for match in re.finditer(r'\S+', text): 96 | span = Span(start=match.start(), end=match.end()) 97 | tok = match.group(0) 98 | yield (tok, span) 99 | 100 | return list(inner(text)) 101 | 102 | 103 | def _get_tokenized_text_and_mapping_to_original_offsets( 104 | text: str, tokenizer: PreTrainedTokenizer, 105 | max_number_of_tokens: Optional[int] = None) -> Tuple[List[str], List[Span]]: 106 | tokens = list() 107 | token_idx_to_char_boundaries = [] 108 | 109 | # We do a first pass white space / punctuation tokenization using the non-destructive 110 | # spacy tokenizer so that we can maintain a map back to the original character offsets 111 | # and then do a second pass with the tokenizer of choice to convert into model 112 | # specific word pieces 113 | for word, char_offset_boundaries_for_this_word in WordTokenizerWithCharOffsetTracking.tokenize( 114 | text): 115 | word_pieces = tokenizer.tokenize(word) 116 | 117 | if max_number_of_tokens is not None and len(tokens) + len(word_pieces) > \ 118 | max_number_of_tokens: 119 | logging.warning('Truncating text after %d word piece tokens' % len(tokens)) 120 | break 121 | 122 | for word_piece in tokenizer.tokenize(word): 123 | tokens.append(word_piece) 124 | token_idx_to_char_boundaries.append(char_offset_boundaries_for_this_word) 125 | 126 | return tokens, token_idx_to_char_boundaries 127 | 128 | 129 | def _map_answer_boundaries_to_doc_span_vector_offsets( 130 | original_answer_span: Span, size_of_question_segment: int, doc_span: Span) -> Span: 131 | # TODO: Think harder about the situation where the correct answer boundaries 132 | # partially overlap with the document span, currently we still mark those spans as not 133 | # having an answers...but perhaps that's sending bad signals to the training algorithm?? 134 | if original_answer_span in doc_span: 135 | answer_span_within_answer_segment = \ 136 | Span(start=original_answer_span.start - doc_span.start + size_of_question_segment, 137 | end=original_answer_span.end - doc_span.start + size_of_question_segment) 138 | else: 139 | # Point to the [CLS] token; Re-visit if we need to support xlnet which doesn't keep the 140 | # [CLS] token at position 0 141 | answer_span_within_answer_segment = Span(start=0, end=0) 142 | 143 | return answer_span_within_answer_segment 144 | 145 | 146 | def _split_into_spans(total_length: int, window_length: int, stride_length: int) -> List[Span]: 147 | spans = list() 148 | if total_length <= window_length: 149 | logging.debug('Window size (%d) for splitting is larger than the total document size: %d' % 150 | (window_length, total_length)) 151 | spans.append(Span(start=0, end=total_length)) 152 | else: 153 | start_offset = 0 154 | while start_offset < total_length: 155 | spans.append(Span(start_offset, 156 | end=min(start_offset + window_length, total_length))) 157 | start_offset += stride_length 158 | return spans 159 | 160 | 161 | def _map_answer_char_offsets_to_token_boundaries( 162 | answer_span_in_char_offsets: Span, token_idx_to_char_offset_boundaries: List): 163 | # NOTE: the character offsets may not align exactly with our token boundaries so we find the 164 | # nearest aligned token boundaries in order to specify the span 165 | 166 | start_token_idx = None 167 | end_token_idx = None 168 | for token_idx, token_char_boundaries in enumerate(token_idx_to_char_offset_boundaries): 169 | if start_token_idx is None: 170 | if answer_span_in_char_offsets.start in token_char_boundaries: 171 | # We found that there is a token that contains (inclusive) the specified start 172 | # char offset 173 | start_token_idx = token_idx 174 | elif answer_span_in_char_offsets.start < token_char_boundaries.start: 175 | # We use the first token that starts after the specified start char offset 176 | start_token_idx = token_idx 177 | 178 | if end_token_idx is None: 179 | # NOTE: annotations use exclusive end offset, but we want inclusive token end offset 180 | if token_char_boundaries.start >= answer_span_in_char_offsets.end: 181 | # We found the first token that starts _after_ the specified end char offset, so 182 | # use the previous token 183 | end_token_idx = max(0, token_idx - 1) 184 | elif (answer_span_in_char_offsets.end - 1) in token_char_boundaries: 185 | # We found that there is a token that contains (exclusive) the specified end 186 | # char offset 187 | end_token_idx = token_idx 188 | 189 | if start_token_idx is not None and end_token_idx is not None: 190 | break 191 | 192 | if start_token_idx is None: 193 | raise RuntimeError('Unable to map the answer character offsets %s to an appropriate' 194 | ' token offset boundary using %s' % ( 195 | answer_span_in_char_offsets, token_idx_to_char_offset_boundaries)) 196 | elif end_token_idx is None: 197 | # assume that the end character offset takes us beyond the last tokenized word (e.g. 198 | # if the document has trailing white space 199 | end_token_idx = len(token_idx_to_char_offset_boundaries) - 1 200 | 201 | return Span(start=start_token_idx, end=end_token_idx) 202 | 203 | def _prepare_query_segment(query: Dict[str, str], max_query_length: int, sep_tokens: List[str], 204 | tokenizer: PreTrainedTokenizer) -> List[str]: 205 | try: 206 | query_title, _ = _get_tokenized_text_and_mapping_to_original_offsets( 207 | text=query['QUESTION_TITLE'], 208 | tokenizer=tokenizer) 209 | 210 | query_body, _ = _get_tokenized_text_and_mapping_to_original_offsets( 211 | text=query['QUESTION_TEXT'], 212 | tokenizer=tokenizer) 213 | 214 | if len(query_title) + len(query_body) + len(sep_tokens) > max_query_length: 215 | query_title = query_title[: max_query_length // 2] 216 | query_tokens = query_title + sep_tokens 217 | query_tokens += query_body[:max_query_length - len(query_tokens)] 218 | except Exception as ex: 219 | raise ValueError('Unable to parse query tokens from query `%s`: %s' % (query, ex)) from ex 220 | 221 | return query_tokens 222 | 223 | def generate_features_for_example( 224 | qid: str, query: dict, doc: dict, doc_id: str, answer_span: Span, 225 | tokenizer: PreTrainedTokenizer, max_seq_length: int, doc_stride: int, 226 | max_query_length: int, negative_span_subsampling_probability: float, 227 | add_doc_title_to_passage: bool = False) -> \ 228 | List[TechQaInputFeature]: 229 | features = list() 230 | 231 | between_text_segment_separator = [tokenizer.sep_token] 232 | if isinstance(tokenizer, RobertaTokenizer): 233 | # Roberta uses 2 sep tokens to separate segments 234 | between_text_segment_separator.append(tokenizer.sep_token) 235 | 236 | query_segment = _prepare_query_segment(query=query, tokenizer=tokenizer, 237 | sep_tokens=between_text_segment_separator, 238 | max_query_length=max_query_length) 239 | if len(query_segment) < 1: 240 | logging.warning('No query tokens left after tokenization for qid %s' % qid) 241 | return features 242 | 243 | query_segment = [tokenizer.cls_token] + query_segment + between_text_segment_separator 244 | context_size = max_seq_length - len(query_segment) - 1 245 | if add_doc_title_to_passage: 246 | document_title_tokens, _ = _get_tokenized_text_and_mapping_to_original_offsets( 247 | text=doc['title'], 248 | tokenizer=tokenizer)[: context_size // 2] 249 | 250 | # better to add doc title to query segment rather than doc (i.e. segment id == [0]) 251 | query_segment += document_title_tokens + between_text_segment_separator 252 | context_size -= len(document_title_tokens) + len(between_text_segment_separator) 253 | 254 | document_tokens, token_idx_to_char_boundaries = \ 255 | _get_tokenized_text_and_mapping_to_original_offsets( 256 | text=doc['text'], 257 | tokenizer=tokenizer) 258 | 259 | if len(document_tokens) < 1: 260 | logging.warning('No document tokens left after tokenization for doc id %s' % doc['_id']) 261 | return features 262 | sliding_window_spans = _split_into_spans(total_length=len(document_tokens), 263 | window_length=context_size, 264 | stride_length=doc_stride) 265 | 266 | if not answer_span.is_null_span(): 267 | answer_span = _map_answer_char_offsets_to_token_boundaries(answer_span, 268 | token_idx_to_char_boundaries) 269 | 270 | features = [] 271 | 272 | # For each span, create a new feature vector 273 | for doc_span_index, doc_span in enumerate(sliding_window_spans): 274 | # Create a copy of the question segment for each doc span 275 | tokens = deepcopy(query_segment) 276 | segment_ids = [0] * len(tokens) 277 | 278 | size_of_question_segment = len(segment_ids) 279 | 280 | # Map the original token index offsets to the feature vector containing the current doc 281 | # span, the query, and the special tokens 282 | answer_span_within_context = _map_answer_boundaries_to_doc_span_vector_offsets( 283 | original_answer_span=answer_span, 284 | size_of_question_segment=size_of_question_segment, doc_span=doc_span) 285 | span_token_to_original_start_offset = { 286 | i - doc_span.start + size_of_question_segment: token_idx_to_char_boundaries[i].start for i 287 | in range(doc_span.start, doc_span.end)} 288 | span_token_to_original_end_offset = { 289 | i - doc_span.start + size_of_question_segment: token_idx_to_char_boundaries[i].end for i 290 | in range(doc_span.start, doc_span.end)} 291 | 292 | span_has_answer = answer_span_within_context.start >= size_of_question_segment 293 | 294 | if not span_has_answer and random() > negative_span_subsampling_probability: 295 | logging.debug('Dropping span since it\'s a negative instance') 296 | else: 297 | # Add document tokens 298 | for i in range(doc_span.start, doc_span.end): 299 | tokens.append(document_tokens[i]) 300 | segment_ids.append(1) 301 | 302 | # Add the final separator token to indicate end of passage 303 | tokens.append(tokenizer.sep_token) 304 | segment_ids.append(1) 305 | 306 | # Initialize the input ids & masks (for padding) 307 | input_ids = tokenizer.convert_tokens_to_ids(tokens) 308 | input_mask = [1] * len(input_ids) 309 | while len(input_ids) < max_seq_length: 310 | # Mask is 0 for padding tokens 311 | input_ids.append(0) 312 | input_mask.append(0) 313 | segment_ids.append(0) 314 | 315 | features.append(TechQaInputFeature( 316 | qid=qid, doc_id=doc_id, doc_span_index=doc_span_index, tokens=tokens, 317 | token_to_original_start_offset=span_token_to_original_start_offset, 318 | token_to_original_end_offset=span_token_to_original_end_offset, 319 | input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, 320 | start_position=answer_span_within_context.start, 321 | end_position=answer_span_within_context.end)) 322 | return features 323 | 324 | def create_features(input_query_file: str, input_corpus_file: str, max_seq_length: int, 325 | max_query_length: int, doc_stride: int, tokenizer: PreTrainedTokenizer, 326 | negative_subsampling_probability_when_has_answer: Optional[float] = None, 327 | negative_subsampling_probability_when_no_answer: Optional[float] = None, 328 | add_doc_title_to_passage: bool = False): 329 | with open(input_corpus_file, encoding=TEXT_ENCODING) as infile: 330 | logging.info('Loading corpus text from %s' % infile) 331 | document_by_id = json.load(infile) 332 | logging.info('Loaded %d documents from corpus' % len(document_by_id)) 333 | 334 | with open(input_query_file, encoding=TEXT_ENCODING) as infile: 335 | logging.info('Loading queries and annotations from %s' % infile) 336 | queries = json.load(infile) 337 | logging.info('Loaded %d queries from %s' % (len(queries), infile)) 338 | 339 | num_generated_features = 0 340 | if negative_subsampling_probability_when_has_answer is None: 341 | negative_subsampling_probability_when_has_answer = 1.0 342 | if negative_subsampling_probability_when_no_answer is None: 343 | negative_subsampling_probability_when_no_answer = 1.0 344 | 345 | features = [] 346 | 347 | for i, query in enumerate(tqdm(queries, desc='Featurizing queries')): 348 | qid = "The %d th query" % i 349 | try: 350 | qid = query['QUESTION_ID'] 351 | correct_doc_id = None 352 | if 'ANSWERABLE' in query and query['ANSWERABLE'] == 'Y': 353 | # Add positive examples and keep track of the doc id so that we don't featurize it again from the answer 354 | # pool 355 | correct_doc_id = query['DOCUMENT'] 356 | for input_feature in generate_features_for_example( 357 | qid=qid, doc_id=query['DOCUMENT'], 358 | query=query, doc=document_by_id[query['DOCUMENT']], 359 | answer_span=Span(start=int(query['START_OFFSET']), 360 | end=int(query['END_OFFSET'])), 361 | tokenizer=tokenizer, max_seq_length=max_seq_length, 362 | doc_stride=doc_stride, max_query_length=max_query_length, 363 | negative_span_subsampling_probability= 364 | negative_subsampling_probability_when_has_answer, 365 | add_doc_title_to_passage=add_doc_title_to_passage): 366 | num_generated_features += 1 367 | features.append(input_feature) 368 | 369 | # Add negative examples from the answer pool 370 | for doc_id in query['DOC_IDS']: 371 | doc_id = doc_id.strip() 372 | if doc_id != correct_doc_id: 373 | if doc_id not in document_by_id: 374 | logging.warning('Document %s is specified in the DOC_IDS for question %s' 375 | ' but does not exist in the corpus!!' % (qid, doc_id)) 376 | else: 377 | for input_feature in generate_features_for_example( 378 | qid=qid, doc_id=doc_id, query=query, doc=document_by_id[doc_id], 379 | answer_span=_NULL_SPAN, 380 | tokenizer=tokenizer, max_seq_length=max_seq_length, 381 | doc_stride=doc_stride, max_query_length=max_query_length, 382 | negative_span_subsampling_probability= 383 | negative_subsampling_probability_when_no_answer, 384 | add_doc_title_to_passage=add_doc_title_to_passage): 385 | num_generated_features += 1 386 | features.append(input_feature) 387 | 388 | except Exception as ex: 389 | logging.warning('Error featurizing query %s. We will skip this query: %s' % (qid, ex)) 390 | 391 | logging.info('Generated %d features from %d queries' % 392 | (num_generated_features, len(queries))) 393 | return features 394 | 395 | 396 | def _derive_feature_cache_name( 397 | input_query_file: str, input_corpus_file: str, max_seq_len: int, 398 | max_query_length: int, doc_stride: int, tokenizer: PreTrainedTokenizer, 399 | negative_subsampling_probability_when_has_answer: Optional[float] = None, 400 | negative_subsampling_probability_when_no_answer: Optional[float] = None, 401 | add_doc_title_to_passage: bool = False) -> str: 402 | cache_filename = '{0}_{1}_features_with_{2}_max_seq_len_{3}_stride_{4}_max_q_len_{5}_' \ 403 | 'has_answer_ssrate_{6}_no_answer_ssrate_{7}_doc_title_{8}'.format( 404 | path.splitext(input_query_file)[0], 405 | path.splitext(path.basename(input_corpus_file))[0], 406 | tokenizer.__class__.__name__, 407 | max_seq_len, 408 | doc_stride, 409 | max_query_length, 410 | negative_subsampling_probability_when_has_answer, 411 | negative_subsampling_probability_when_no_answer, 412 | 'Y' if add_doc_title_to_passage else 'N') 413 | 414 | if hasattr(tokenizer, 'basic_tokenizer') and hasattr(tokenizer.basic_tokenizer, 415 | 'do_lower_case'): 416 | cache_filename += '_lower_case_{0}'.format(tokenizer.basic_tokenizer.do_lower_case) 417 | 418 | return cache_filename 419 | 420 | def load_and_cache_examples(args, tokenizer, evaluate=False, output_examples=False): 421 | if evaluate: 422 | input_query_file = args.predict_file 423 | negative_subsampling_probability_when_has_answer = None 424 | negative_subsampling_probability_when_no_answer = None 425 | else: 426 | input_query_file = args.train_file 427 | negative_subsampling_probability_when_has_answer = args.negative_sampling_prob_when_has_answer 428 | negative_subsampling_probability_when_no_answer = args.negative_sampling_prob_when_no_answer 429 | 430 | return get_tech_qa_features( 431 | input_query_file=input_query_file, 432 | input_corpus_file=args.input_corpus_file, 433 | max_seq_len=args.max_seq_length, 434 | max_query_length=args.max_query_length, 435 | doc_stride=args.doc_stride, 436 | tokenizer=tokenizer, 437 | negative_subsampling_probability_when_no_answer=negative_subsampling_probability_when_no_answer, 438 | negative_subsampling_probability_when_has_answer=negative_subsampling_probability_when_has_answer, 439 | add_doc_title_to_passage=args.add_doc_title_to_passage, 440 | output_examples=output_examples 441 | ) 442 | 443 | def get_dataset_from_features(features): 444 | all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) 445 | all_input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long) 446 | all_segment_ids = torch.tensor([f.segment_ids for f in features], dtype=torch.long) 447 | all_start_positions = torch.tensor([f.start_position for f in features], dtype=torch.long) 448 | all_end_positions = torch.tensor([f.end_position for f in features], dtype=torch.long) 449 | all_feature_indices = torch.arange(all_input_ids.size(0), dtype=torch.long) 450 | 451 | dataset = TensorDataset( 452 | all_input_ids, all_input_mask, all_segment_ids, all_start_positions, all_end_positions, all_feature_indices) 453 | 454 | return dataset 455 | 456 | def get_tech_qa_features( 457 | input_query_file: str, input_corpus_file: str, max_seq_len: int, 458 | max_query_length: int, doc_stride: int, tokenizer: PreTrainedTokenizer, 459 | negative_subsampling_probability_when_has_answer: Optional[float] = None, 460 | negative_subsampling_probability_when_no_answer: Optional[float] = None, 461 | add_doc_title_to_passage: bool = False, 462 | output_examples: bool = False 463 | ) -> \ 464 | Iterable[TechQaInputFeature]: 465 | logging.info('**** Generating feature caches for examples from %s ****\n' % 466 | input_query_file) 467 | logging.info('Using corpus: %s' % input_corpus_file) 468 | logging.info('Using tokenizer: %s' % tokenizer.__class__.__name__) 469 | logging.info('Using max sequence length: %s' % max_seq_len) 470 | logging.info('Using document stride: %s' % doc_stride) 471 | logging.info('Using maximum query length: %s' % max_query_length) 472 | logging.info( 473 | 'When example has answer, using negative instance subsampling probability: %s' % 474 | negative_subsampling_probability_when_has_answer) 475 | logging.info( 476 | 'When example has NO answer, using negative instance subsampling probability: %s' % 477 | negative_subsampling_probability_when_no_answer) 478 | 479 | logging.info("add doc title to passage: %d" % (add_doc_title_to_passage)) 480 | 481 | cache_file = _derive_feature_cache_name( 482 | max_seq_len=max_seq_len, max_query_length=max_query_length, 483 | doc_stride=doc_stride, tokenizer=tokenizer, input_corpus_file=input_corpus_file, 484 | input_query_file=input_query_file, 485 | negative_subsampling_probability_when_no_answer= 486 | negative_subsampling_probability_when_no_answer, 487 | negative_subsampling_probability_when_has_answer= 488 | negative_subsampling_probability_when_has_answer, 489 | add_doc_title_to_passage=add_doc_title_to_passage) 490 | 491 | if not path.isfile(cache_file): 492 | logging.info('Did not find previously cached features (%s) for %s, generating them now' % 493 | (cache_file, input_query_file)) 494 | features = create_features( 495 | input_query_file=input_query_file, 496 | input_corpus_file=input_corpus_file, 497 | tokenizer=tokenizer, max_seq_length=max_seq_len, 498 | doc_stride=doc_stride, 499 | max_query_length=max_query_length, 500 | negative_subsampling_probability_when_has_answer= 501 | negative_subsampling_probability_when_has_answer, 502 | negative_subsampling_probability_when_no_answer= 503 | negative_subsampling_probability_when_no_answer, 504 | add_doc_title_to_passage=add_doc_title_to_passage 505 | ) 506 | 507 | dataset = get_dataset_from_features(features) 508 | 509 | with open(input_query_file, encoding=TEXT_ENCODING) as infile: 510 | gold_dict = {q['QUESTION_ID']: q for q in json.load(infile)} 511 | 512 | logging.info("Saving features into cached file %s", cache_file) 513 | torch.save({"features": features, "dataset": dataset, "examples": gold_dict}, cache_file) 514 | else: 515 | logging.info('Skipping featurization and loading features from cache: %s' % cache_file) 516 | features_and_dataset = torch.load(cache_file) 517 | dataset = features_and_dataset["dataset"] 518 | if output_examples: 519 | gold_dict = features_and_dataset["examples"] 520 | features = features_and_dataset["features"] 521 | 522 | if output_examples: 523 | return dataset, features, gold_dict 524 | return dataset --------------------------------------------------------------------------------