├── .flake8 ├── docs ├── cfgen.pdf └── _static │ └── pipeline.png ├── requirements.txt ├── cfgen ├── __init__.py ├── visualization.py ├── outadapter.py ├── metric.py ├── generator.py ├── config.py ├── command.py ├── laboratory.py ├── common.py ├── tokenizer.py ├── trainer.py ├── inadapter.py └── model.py ├── app.py ├── README.md ├── .gitignore └── LICENSE /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length = 160 3 | -------------------------------------------------------------------------------- /docs/cfgen.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xijiz/cfgen/HEAD/docs/cfgen.pdf -------------------------------------------------------------------------------- /docs/_static/pipeline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xijiz/cfgen/HEAD/docs/_static/pipeline.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | torch==1.6.0 2 | pandas==1.1.2 3 | fire==0.3.1 4 | scikit_learn==0.23.2 5 | seaborn==0.10.1 6 | matplotlib==3.2.1 7 | -------------------------------------------------------------------------------- /cfgen/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright (C) The Zhejiang University DMAC Lab Authors. team - All Rights Reserved 3 | # 4 | # Written by Xiangji Zeng , March 2020 5 | """Counterfactual Generator Package""" 6 | 7 | __all__ = ["command"] 8 | 9 | from .command import command 10 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright (C) The Zhejiang University DMAC Lab Authors. team - All Rights Reserved 3 | # 4 | # Written by Xiangji Zeng , March 2020 5 | """Application Start Point""" 6 | 7 | from cfgen import command 8 | 9 | 10 | if __name__ == "__main__": 11 | command() 12 | -------------------------------------------------------------------------------- /cfgen/visualization.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright (C) The Zhejiang University DMAC Lab Authors. team - All Rights Reserved 3 | # 4 | # Written by Xiangji Zeng , March 2020 5 | """Visualization""" 6 | 7 | import os 8 | 9 | 10 | def visualize_avearage_causal_effects(folder: str, file_name: str = "intervention.csv") -> None: 11 | """ 12 | Visualize Average Causal Effects. 13 | 14 | References: 15 | [1] https://seaborn.pydata.org/tutorial/color_palettes.html 16 | 17 | Args: 18 | folder (str): The folder name where the experimental file exists. 19 | file_name (str): The experimental file name. 20 | """ 21 | import matplotlib.pyplot as plt 22 | import pandas as pd 23 | import seaborn as sns 24 | 25 | file_name = os.path.join(folder, file_name) 26 | data = pd.read_csv(file_name, "\t") 27 | data = data[data["Level"] == "Token"] 28 | data.loc[data.Augmentation == 0, "Augmentation"] = "No" 29 | data.loc[data.Augmentation == 1, "Augmentation"] = "Yes" 30 | sns.catplot( 31 | x="N", y="RI", hue="Augmentation", kind="bar", col="Dataset", row="Model", 32 | palette="Paired", edgecolor="w", linewidth=0.3, aspect = 0.7, data=data 33 | ) 34 | plt.show() 35 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Implementation of the [EMNLP 2020](https://2020.emnlp.org/papers/main) paper "[Counterfactual Generator: A Weakly-Supervised Method for Named Entity Recognition](https://www.aclweb.org/anthology/2020.emnlp-main.590/)". 2 | 3 | # **C**ounter**F**actual **GEN**erator (`cfgen`) 4 | ## Introduction 5 | ![](./docs/_static/pipeline.png) 6 | 7 | We propose the Counterfactual Generator, which generates counterfactual examples by the interventions on the existing observational examples to enhance the original dataset by breaking the entangled correlations between the spurious features and the non-spurious fearures. Experiments across three datasets show that our method improves the generalization ability of models under limited observational examples. 8 | 9 | ## Getting Started 10 | ### Setup Environment 11 | - [`Python3`](https://www.python.org/) 12 | - [`Ubuntu 18.04`](https://ubuntu.com/download/desktop) 13 | 14 | ```bash 15 | sudo apt install python3-pip 16 | pip3 install virtualenv 17 | virtualenv -p /usr/bin/python3 env 18 | source env/bin/activate 19 | pip install -r requirements.txt 20 | ``` 21 | 22 | ### Quick Start 23 | It is important to know that we do not provide the link or data of the dataset `IDiag`, because it is a private dataset only for the *INTERNAL USE*. 24 | 25 | - Train a model on a given dataset 26 | 27 | ```bash 28 | python app.py train --gpu "[0]" --model "bilstm" --dataset "cluener" --seed 100 29 | ``` 30 | 31 | - Training with all settings 32 | 33 | ```bash 34 | python app.py trainall --gpu "[0]" --models "['bilstm', 'bert']" --datasets "['cluener', 'cner']" 35 | ``` 36 | 37 | ## Citation 38 | ```plain 39 | @inproceedings{zeng-etal-2020-counterfactual, 40 | title = "Counterfactual Generator: A Weakly-Supervised Method for Named Entity Recognition", 41 | author = "Zeng, Xiangji and 42 | Li, Yunliang and 43 | Zhai, Yuchen and 44 | Zhang, Yin", 45 | booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)", 46 | month = nov, 47 | year = "2020", 48 | address = "Online", 49 | publisher = "Association for Computational Linguistics", 50 | url = "https://www.aclweb.org/anthology/2020.emnlp-main.590", 51 | pages = "7270--7280", 52 | } 53 | ``` 54 | 55 | ## License 56 | CFGen is CC-BY-NC 4.0. 57 | 58 | ## Contact 59 | If you have any questions, please contact me or create a Github issue. 60 | -------------------------------------------------------------------------------- /cfgen/outadapter.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright (C) The Zhejiang University DMAC Lab Authors. team - All Rights Reserved 3 | # 4 | # Written by Xiangji Zeng , March 2020 5 | """Output Adapter""" 6 | 7 | import os 8 | from typing import Union 9 | import shutil 10 | 11 | 12 | class OutAdapter: 13 | """ 14 | OutAdapter provides functions to postprocess the data from the neural nets. 15 | 16 | Args: 17 | folder (str): The data folder where the mapping data exists. 18 | """ 19 | 20 | def __init__(self, folder: str): 21 | super(OutAdapter, self).__init__() 22 | self._folder = folder 23 | self._to_index = {} 24 | self._to_label = [] 25 | self._load() 26 | 27 | @property 28 | def pad_id(self) -> int: 29 | """Return PAD ID.""" 30 | return self[self.pad_label] 31 | 32 | @property 33 | def pad_label(self) -> str: 34 | """Return PAD label.""" 35 | return "O" 36 | 37 | def _load(self) -> None: 38 | """Load all mapping labels.""" 39 | with open(os.path.join(self._folder, "labels.txt"), "r", encoding="utf-8") as f_in: 40 | data = [line.replace("\n", "") for line in f_in.readlines()] 41 | for item in data: 42 | self._to_index[item] = len(self._to_label) 43 | self._to_label.append(item) 44 | 45 | def __len__(self) -> int: 46 | """Return the total number of mapping labels.""" 47 | return len(self._to_label) 48 | 49 | def __getitem__(self, item: Union[int, str]) -> Union[str, int]: 50 | """ 51 | Convert label into ID or ID into label. 52 | 53 | Args: 54 | item (Union[int, str]): ID or label. 55 | """ 56 | if isinstance(item, str) and item in self._to_index: 57 | return self._to_index[item] 58 | elif isinstance(item, int) and 0 <= item < len(self._to_label): 59 | return self._to_label[item] 60 | raise ValueError("No corresponding value found: {0} with type {1}".format(item, type(item))) 61 | 62 | def save(self, folder: str): 63 | """ 64 | Save labels into a given folder. 65 | 66 | Args: 67 | folder (str): A given folder to be used for saving labels. 68 | """ 69 | label_name = "labels.txt" 70 | shutil.copy(os.path.join(self._folder, label_name), os.path.join(folder, label_name)) 71 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # celery beat schedule file 95 | celerybeat-schedule 96 | 97 | # SageMath parsed files 98 | *.sage.py 99 | 100 | # Environments 101 | .env 102 | .venv 103 | env/ 104 | venv/ 105 | ENV/ 106 | env.bak/ 107 | venv.bak/ 108 | 109 | # Spyder project settings 110 | .spyderproject 111 | .spyproject 112 | 113 | # Rope project settings 114 | .ropeproject 115 | 116 | # mkdocs documentation 117 | /site 118 | 119 | # mypy 120 | .mypy_cache/ 121 | .dmypy.json 122 | dmypy.json 123 | 124 | # Pyre type checker 125 | .pyre/ 126 | 127 | # vscode 128 | .vscode/ 129 | .ipynb_checkpoints/ 130 | 131 | # middle files: log, weights, datasets 132 | tmp/ -------------------------------------------------------------------------------- /cfgen/metric.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright (C) The Zhejiang University DMAC Lab Authors. team - All Rights Reserved 3 | # 4 | # Written by Xiangji Zeng , March 2020 5 | """Evaluation Metrics""" 6 | 7 | from typing import List, Dict, Any 8 | from sklearn.metrics import precision_recall_fscore_support 9 | from .common import to_entities 10 | 11 | 12 | def evalner(batch_gold_labels: List[List[str]], batch_pred_labels: List[List[str]]) -> Dict[str, Any]: 13 | """ 14 | Calculate NER metrics: F1, Precision, Recall. 15 | 16 | Args: 17 | batch_gold_labels (List[List[str]]): Batch gold labels with shape (batch_size, seq_len). 18 | batch_pred_labels (List[List[str]]): Batch predicted labels with shape (batch_size, seq_len). 19 | """ 20 | # nsp: not successfully predicted 21 | scores = {"nsp": []} 22 | # entity level 23 | all_gold_entities, all_pred_entities, all_correct_entities = [], [], [] 24 | for i, _ in enumerate(batch_gold_labels): 25 | gold_entities = [ 26 | "[{0}]({1},{2})".format(span["label"], span["start"], span["end"]) 27 | for span in to_entities("O"*len(batch_gold_labels[i]), batch_gold_labels[i]) 28 | ] 29 | pred_entities = [ 30 | "[{0}]({1},{2})".format(span["label"], span["start"], span["end"]) 31 | for span in to_entities("O"*len(batch_pred_labels[i]), batch_pred_labels[i]) 32 | ] 33 | correct_set = set(gold_entities).intersection(set(pred_entities)) 34 | scores["nsp"].append(list(set(gold_entities) - correct_set)) 35 | all_correct_entities.extend(list(correct_set)) 36 | all_gold_entities.extend(gold_entities) 37 | all_pred_entities.extend(pred_entities) 38 | scores["entity"] = { 39 | "p": len(all_correct_entities) / len(all_pred_entities) if len(all_pred_entities) > 0 else 0, 40 | "r": len(all_correct_entities) / len(all_gold_entities) if len(all_gold_entities) > 0 else 0 41 | } 42 | deno = scores["entity"]["p"] + scores["entity"]["r"] 43 | scores["entity"]["f1"] = 2*scores["entity"]["p"]*scores["entity"]["r"] / deno if deno > 0 else 0 44 | 45 | # token level 46 | gold_labels, pred_labels = [], [] 47 | for i, _ in enumerate(batch_gold_labels): 48 | gold_labels.extend(batch_gold_labels[i]) 49 | pred_labels.extend(batch_pred_labels[i]) 50 | p, r, f1, _ = precision_recall_fscore_support(gold_labels, pred_labels, average='micro', warn_for=tuple()) 51 | scores["token"] = { 52 | "p": p, 53 | "r": r, 54 | "f1": f1 55 | } 56 | 57 | return scores 58 | -------------------------------------------------------------------------------- /cfgen/generator.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright (C) The Zhejiang University DMAC Lab Authors. team - All Rights Reserved 3 | # 4 | # Written by Xiangji Zeng , March 2020 5 | """Counterfactual Generator""" 6 | 7 | import copy 8 | import random 9 | from typing import List 10 | from collections import defaultdict 11 | 12 | 13 | def create_counterfactual_examples(trainset: List[dict]) -> List[dict]: 14 | """ 15 | Given a part of observational seed examples, creating counterfactual examples. 16 | 17 | Args: 18 | trainset (List[dict]): A list of observational seed examples. 19 | """ 20 | deduplicated_examples = set() 21 | counterfactual_examples = [] 22 | local_entity_sets = defaultdict(set) 23 | for example in trainset: 24 | deduplicated_examples.add(copy.deepcopy(example["text"])) 25 | example["spans"] = sorted(example["spans"], key=lambda s: s["start"], reverse=False) 26 | for span_id, span in enumerate(example["spans"]): 27 | local_entity_sets[span["label"]].add(span["text"]) 28 | 29 | for i, example in enumerate(trainset): 30 | if not example["spans"]: 31 | continue 32 | index = random.choice(list(range(len(example["spans"])))) 33 | for local_candidate in local_entity_sets[example["spans"][index]["label"]]: 34 | cfexample = copy.deepcopy(example) 35 | cfexample["obersavational_text"] = example["text"] 36 | cfexample["text"] = "{0}{1}{2}".format( 37 | cfexample["text"][: cfexample["spans"][index]["start"]], 38 | local_candidate, 39 | cfexample["text"][cfexample["spans"][index]["end"] + 1:] 40 | ) 41 | if cfexample["text"] == example["text"] or cfexample["text"] in deduplicated_examples: 42 | continue 43 | deduplicated_examples.add(copy.deepcopy(cfexample["text"])) 44 | dist = len(local_candidate) - len(cfexample["spans"][index]["text"]) 45 | cfexample["spans"][index]["end"] = cfexample["spans"][index]["start"] - 1 + len(local_candidate) 46 | cfexample["spans"][index]["text"] = local_candidate 47 | cfexample["replaced"] = [ 48 | "[{0}]({1}, {2})".format( 49 | cfexample["spans"][index]["label"], cfexample["spans"][index]["start"], cfexample["spans"][index]["end"] 50 | ) 51 | ] 52 | for i in range(index + 1, len(cfexample["spans"])): 53 | cfexample["spans"][i]["start"] += dist 54 | cfexample["spans"][i]["end"] += dist 55 | counterfactual_examples.append(cfexample) 56 | 57 | return counterfactual_examples 58 | -------------------------------------------------------------------------------- /cfgen/config.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright (C) The Zhejiang University DMAC Lab Authors. team - All Rights Reserved 3 | # 4 | # Written by Xiangji Zeng , March 2020 5 | """Configurations""" 6 | 7 | import os 8 | from typing import List, Dict, Any 9 | from datetime import datetime 10 | import torch 11 | 12 | 13 | class TrainerConfig: 14 | """ 15 | Trainer Configuarion. 16 | 17 | Args: 18 | model (str): Model name to be trained. 19 | dataset (str): Dataset name to be trained. 20 | tokenizer (str): Tokenizer name. 21 | data_folder (str): The root folder of data. 22 | gpu (List[int]): The given GPU devices. 23 | hyperparameters (Dict[str, Any]): All model hyperparameters. 24 | learning_rate (float): Learning rate. 25 | batch_size (int): Batch size. 26 | epoch (int): Training epoch. 27 | stop_if_no_improvement (int): This parameter is used to decease the training epoch if the metric does not 28 | increase with a given number of epoch round. 29 | early_stop_loss (float): Early stop loss for overcoming overfitting. 30 | identity (str): The sub-folder name of an experiment. 31 | """ 32 | 33 | def __init__( 34 | self, 35 | model: str, 36 | dataset: str, 37 | tokenizer: str, 38 | data_folder: str, 39 | gpu: List[int], 40 | hyperparameters: Dict[str, Any], 41 | learning_rate: float, 42 | batch_size: int, 43 | epoch: int, 44 | stop_if_no_improvement: int = 15, 45 | early_stop_loss: float = 0.01, 46 | identity: str = None 47 | ): 48 | super(TrainerConfig, self).__init__() 49 | self.model = model 50 | self.dataset = dataset 51 | self.tokenizer = tokenizer 52 | log_folder = os.path.join(data_folder, "logs") 53 | if identity is not None and os.path.isdir(log_folder) and identity in os.listdir(log_folder): 54 | self.identity = identity 55 | else: 56 | self.identity = "{0}-{1}-{2}".format(dataset, model, datetime.now().strftime("%Y%m%d%H%M%S")) 57 | self.data_folder = data_folder 58 | self.output_folder = os.path.join(self.data_folder, "logs", self.identity) 59 | self.dataset_folder = os.path.join(self.data_folder, "datasets", self.dataset) 60 | self.tokenizer_folder = os.path.join(self.data_folder, "tokenizers", self.tokenizer) 61 | self.device, self.gpu = self._devices(gpu) 62 | self.hyperparameters = hyperparameters 63 | self.max_seq_len = hyperparameters.get("max_seq_len", 512) 64 | self.learning_rate = learning_rate 65 | self.batch_size = batch_size 66 | self.epoch = epoch 67 | self.stop_if_no_improvement = stop_if_no_improvement 68 | self.early_stop_loss = early_stop_loss 69 | 70 | def _devices(self, gpu: List[int]): 71 | """ 72 | Load available computing devices. 73 | 74 | Args: 75 | gpu (List[int]): All GPU devices that user gives. 76 | """ 77 | device, avaiable_gpu = "cpu", [] 78 | if torch.cuda.is_available() and len(gpu) > 0: 79 | if torch.cuda.device_count() < len(gpu): 80 | avaiable_gpu = list(range(torch.cuda.device_count())) 81 | else: 82 | avaiable_gpu = gpu 83 | device = "cuda:{0}".format(avaiable_gpu[0]) 84 | 85 | return (device, avaiable_gpu) 86 | -------------------------------------------------------------------------------- /cfgen/command.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright (C) The Zhejiang University DMAC Lab Authors. team - All Rights Reserved 3 | # 4 | # Written by Xiangji Zeng , March 2020 5 | """Command Line Tools""" 6 | 7 | from typing import List 8 | import fire 9 | import torch 10 | from .laboratory import train, trainall 11 | from .visualization import visualize_avearage_causal_effects 12 | 13 | 14 | torch.manual_seed(999) 15 | 16 | 17 | def check(model_names: List[str], dataset_names: List[str], n_seeds: List[int]) -> None: 18 | """ 19 | Check whether the input is legal. 20 | 21 | Args: 22 | model_names (List[str]): The inputted model names by user. 23 | dataset_names (List[str]): The inputted dataset names by user. 24 | n_seeds (List[int]): The inputted training seeds by user. 25 | """ 26 | all_model_names, all_dataset_names = ["bilstm", "bert"], ["cluener", "cner"] 27 | if not all([model_name in all_model_names for model_name in model_names]): 28 | print("Available models {0}, but with provided models {1}".format(all_model_names, model_names)) 29 | exit(0) 30 | if not all([dataset_name in all_dataset_names for dataset_name in dataset_names]): 31 | print("Available datasets {0}, but with provided datasets {1}".format(all_dataset_names, dataset_names)) 32 | exit(0) 33 | if not all([seed <= 500 or seed == -1 for seed in n_seeds]): 34 | print("All seeds must be less equal to 500 or -1.") 35 | exit(0) 36 | 37 | 38 | class CommandLineTool: 39 | """ 40 | CommandLineTool provides interfaces to do experiments with various settings. 41 | """ 42 | 43 | @staticmethod 44 | def trainall( 45 | models: List[str] = ["bilstm", "bert"], 46 | datasets: List[str] = ["cluener", "cner"], 47 | seeds: List[int] = [100, 200, 300, 400, 500, -1], 48 | gpu: List[int] = [], 49 | batch_size: int = 8, 50 | epoch: int = 128, 51 | data_folder: str = "./tmp/" 52 | ): 53 | """ 54 | Train all models on all datasets with all settings. 55 | 56 | Args: 57 | models (List[str]): The inputted model names by user. 58 | datasets (List[str]): The inputted dataset names by user. 59 | seeds (List[int]): The inputted training seeds by user. 60 | gpu (List[int]): A list of GPU devices. 61 | batch_size (int): Training batch size. 62 | epoch (int): The total training epoch. 63 | data_folder (str): The root folder where data exists. 64 | """ 65 | check(models, datasets, seeds) 66 | trainall(models, datasets, seeds, gpu, batch_size, epoch, data_folder) 67 | 68 | @staticmethod 69 | def train(model: str, dataset: str, seed: int, gpu: List[int], batch_size: int = 8, epoch: int = 128, data_folder: str = "./tmp/"): 70 | """ 71 | Train a model on a dataset with a given seed. 72 | 73 | Args: 74 | model (str): The inputted model name by user. 75 | dataset (str): The inputted dataset name by user. 76 | seed (int): The inputted training seed by user. 77 | gpu (List[int]): A list of GPU devices. 78 | batch_size (int): Training batch size. 79 | epoch (int): The total training epoch. 80 | data_folder (str): The root folder where data exists. 81 | """ 82 | check([model], [dataset], [seed]) 83 | results = train(model, dataset, seed, gpu, batch_size, epoch, data_folder) 84 | print(results) 85 | 86 | @staticmethod 87 | def visualize(logfolder: str = "./tmp/"): 88 | """ 89 | Visualize ACE under with the augmented data and the non-augmented data. 90 | 91 | Args: 92 | logfolder (str): The folder where the log file exists. 93 | """ 94 | visualize_avearage_causal_effects(logfolder) 95 | 96 | 97 | def command(): 98 | """Start a CLI.""" 99 | fire.Fire(CommandLineTool) 100 | -------------------------------------------------------------------------------- /cfgen/laboratory.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright (C) The Zhejiang University DMAC Lab Authors. team - All Rights Reserved 3 | # 4 | # Written by Xiangji Zeng , March 2020 5 | """Laboratory""" 6 | 7 | import os 8 | from typing import List, Any 9 | import pandas as pd 10 | from .config import TrainerConfig 11 | from .trainer import NERTrainer, __DATASET_MAP__ 12 | from .common import save_jsonl 13 | 14 | 15 | __HPS_MAP__ = {"bilstm": {"hidden_dim": 512, "n_layers": 2, "dropout": 0.1}, "bert": {}} 16 | __LR_MAP__ = {"bilstm": 0.001, "bert": 0.00002} 17 | __TOKENIZER_NAME_MAP__ = {"bilstm": "tce", "bert": "bert"} 18 | 19 | 20 | def trainall(model_names: List[str], dataset_names: List[str], n_seeds: List[int], gpu: List[int], batch_size: int, epoch: int, data_folder: str) -> None: 21 | """ 22 | Train all models on all datasets with all settings. 23 | 24 | Args: 25 | model_names (List[str]): The inputted model names by user. 26 | dataset_names (List[str]): The inputted dataset names by user. 27 | n_seeds (List[int]): The inputted training seeds by user. 28 | gpu (List[int]): A list of GPU devices. 29 | batch_size (int): Training batch size. 30 | epoch (int): The total training epoch. 31 | data_folder (str): The root folder where data exists. 32 | """ 33 | records_file_path = os.path.join(data_folder, "experiments.csv") 34 | if not os.path.isfile(records_file_path): 35 | records = pd.DataFrame(columns=["dataset", "model", "n_seed", "f1", "p", "r", "f1-aug", "p-aug", "r-aug", "diff-f1"]) 36 | else: 37 | records = pd.read_csv(records_file_path) 38 | for dataset_name in dataset_names: 39 | for model_name in model_names: 40 | for seed in n_seeds: 41 | if len(records.query("dataset == '{0}' & model == '{1}' & n_seed == '{2}'".format(dataset_name, model_name, seed))) > 0: 42 | continue 43 | results = train(model_name, dataset_name, seed, gpu, batch_size, epoch, data_folder) 44 | records.loc[len(records)] = results 45 | records.to_csv(records_file_path, index=False) 46 | print("Experimental data has been saved into {records_file_path}".format(records_file_path=records_file_path)) 47 | 48 | 49 | def train(model_name: str, dataset_name: str, seed: int, gpu: List[int], batch_size: int, epoch: int, data_folder: str) -> List[Any]: 50 | """ 51 | Train a model on a dataset with a given seed. 52 | 53 | Args: 54 | model_name (str): The inputted model name by user. 55 | dataset_name (str): The inputted dataset name by user. 56 | seed (int): The inputted training seed by user. 57 | gpu (List[int]): A list of GPU devices. 58 | batch_size (int): Training batch size. 59 | epoch (int): The total training epoch. 60 | data_folder (str): The root folder where data exists. 61 | """ 62 | # train with observational examples 63 | config = TrainerConfig( 64 | model_name, dataset_name, __TOKENIZER_NAME_MAP__[model_name], data_folder, 65 | gpu, __HPS_MAP__[model_name], __LR_MAP__[model_name], batch_size, epoch 66 | ) 67 | datasets = list(__DATASET_MAP__[dataset_name].split_datasets(config.dataset_folder, config.max_seq_len)) 68 | n_trains = len(datasets[0]) 69 | if seed == -1: 70 | seed = n_trains 71 | datasets[0] = datasets[0][:seed] # extract partial obervational examples 72 | trainer = NERTrainer(config, datasets) 73 | results1 = trainer.train() 74 | # train with counterfactual examples 75 | if seed != n_trains: 76 | reasonable_cfexamples, unreasonable_cfexamples = trainer.create_discriminated_examples(datasets[0][:seed]) 77 | datasets[0] += reasonable_cfexamples 78 | del trainer 79 | trainer = NERTrainer(config, datasets) 80 | results2 = trainer.train() 81 | del trainer 82 | testset = datasets[2] 83 | for i, _ in enumerate(testset): 84 | testset[i]["nsp"] = {"noaug": results1["nsp"][i], "aug": results2["nsp"][i]} 85 | save_jsonl(reasonable_cfexamples, config.output_folder, "train-{0}-reasonable-{1}.jsonl".format(model_name, seed)) 86 | save_jsonl(unreasonable_cfexamples, config.output_folder, "train-{0}-unreasonable-{1}.jsonl".format(model_name, seed)) 87 | save_jsonl(testset, config.output_folder, "test-{0}-{1}.jsonl".format(model_name, seed)) 88 | else: 89 | results2 = results1 90 | merged_results = [ 91 | dataset_name, model_name, seed, 92 | results1["entity"]["f1"], results1["entity"]["p"], results1["entity"]["r"], 93 | results2["entity"]["f1"], results2["entity"]["p"], results2["entity"]["r"], 94 | results2["entity"]["f1"] - results1["entity"]["f1"] 95 | ] 96 | 97 | return merged_results 98 | -------------------------------------------------------------------------------- /cfgen/common.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright (C) The Zhejiang University DMAC Lab Authors. team - All Rights Reserved 3 | # 4 | # Written by Xiangji Zeng , March 2020 5 | """Common Utils""" 6 | 7 | import json 8 | import os 9 | from typing import Union, Tuple, List, Callable 10 | import torch 11 | 12 | 13 | def save_text(text: Union[str, dict], *paths: Tuple) -> None: 14 | """ 15 | Save text into local disk. 16 | 17 | Args: 18 | text (Union[str, dict]): The text to be saved. 19 | paths (Tuple): All sub-paths which will be concatenated a complete path. 20 | """ 21 | if isinstance(text, dict): 22 | text = json.dumps(text, ensure_ascii="utf-8") 23 | if not isinstance(text, str): 24 | raise ValueError("can not convert text into a string") 25 | file_path = os.path.join(*paths) 26 | 27 | with open(file_path, "w", encoding="utf-8") as f_o: 28 | f_o.write(text) 29 | 30 | 31 | def load_jsonl(*file_path: Tuple[str], encoding: str = "utf-8") -> list: 32 | """ 33 | Load a list of JSON from local disk. 34 | 35 | Args: 36 | file_path (Tuple): All sub-paths which will be concatenated a complete path. 37 | encoding (str): Text encoding. 38 | """ 39 | data = [] 40 | file_path = os.path.join(*file_path) 41 | with open(file_path, "r", encoding=encoding) as f_in: 42 | for line in f_in.readlines(): 43 | data.append(json.loads(line)) 44 | 45 | return data 46 | 47 | 48 | def save_jsonl(data: List[dict], *file_path: Tuple[str]) -> None: 49 | """ 50 | Save a list of JSON into local disk. 51 | 52 | Args: 53 | data (List[dict]): A list of JSON object. 54 | file_path (Tuple): All sub-paths which will be concatenated a complete path. 55 | """ 56 | file_path = os.path.join(*file_path) 57 | data = [json.dumps(sample, ensure_ascii=False) for sample in data] 58 | with open(file_path, "w", encoding="utf-8") as f_out: 59 | f_out.write("\n".join(data)) 60 | 61 | 62 | def load_json(*file_path: Tuple[str], encoding: str = "utf-8") -> dict: 63 | """ 64 | Load a JSON from local disk. 65 | 66 | Args: 67 | file_path (Tuple): All sub-paths which will be concatenated a complete path. 68 | encoding (str): Text encoding. 69 | """ 70 | file_path = os.path.join(*file_path) 71 | with open(file_path, "r", encoding=encoding) as f_in: 72 | return json.loads(f_in.read()) 73 | 74 | 75 | def to_entities(text: str, labels: List[str]) -> List[dict]: 76 | """ 77 | Convert a list of token labels into entities. 78 | 79 | Args: 80 | text (str): Sentences. 81 | labels (List[str]): A list of labels. 82 | """ 83 | spans = [] 84 | i, seq_len = 0, len(labels) 85 | while i < seq_len: 86 | if labels[i].startswith("B"): 87 | label_infos = labels[i].split("-") 88 | span = { 89 | "start": i, 90 | "end": i, 91 | "label": label_infos[1] 92 | } 93 | pointer = i + 1 94 | if pointer == seq_len: 95 | span["end"] = pointer - 1 96 | i = pointer 97 | while pointer < seq_len: 98 | if labels[pointer].startswith("O") or labels[pointer].startswith("B"): 99 | span["end"] = pointer - 1 100 | i = pointer 101 | break 102 | elif pointer == seq_len - 1: 103 | span["end"] = pointer 104 | i = pointer + 1 105 | break 106 | else: 107 | pointer += 1 108 | span["text"] = text[span["start"]: span["end"] + 1] 109 | spans.append(span) 110 | else: 111 | i += 1 112 | 113 | return spans 114 | 115 | 116 | def to_tags(seq_len: int, spans: List[dict]) -> list: 117 | """ 118 | Convert spans to a list of tag for sequence labeling. 119 | Tag scheme: BIO. 120 | 121 | Args: 122 | seq_len (int): The length of sequence. 123 | spans (List[dict]): All spans on this sequence. 124 | """ 125 | tags = ["O"] * seq_len 126 | for span in spans: 127 | pos = span["start"] 128 | if pos < seq_len: 129 | tags[pos] = "B-{0}".format(span["label"]) 130 | pos += 1 131 | while pos < min(span["end"] + 1, seq_len): 132 | tags[pos] = "I-{0}".format(span["label"]) 133 | pos += 1 134 | 135 | return tags 136 | 137 | 138 | def split_document(document: str, spans: List[dict], max_seq_len: int = 512, segsym: str = "。") -> Tuple[List[dict], List[dict]]: 139 | """ 140 | Split long document into sentences with parameter `max_seq_len` as sliding window. 141 | 142 | Args: 143 | document (str): The raw document. 144 | spans (List[dict]): Spans on this document. We do not split document inside a span. 145 | max_seq_len (str): The maximum sequence length of splited sentences. 146 | segsym (str): The segmentation symbols. 147 | """ 148 | if document == "": 149 | return ([], []) 150 | # this step should be the first, because the following step would change the document length. 151 | tags = to_tags(len(document), spans) 152 | if document.endswith(segsym): 153 | document = document[:len(document)-1] 154 | sentences = [sentence + segsym for sentence in document.split(segsym)] 155 | else: 156 | sentences = [sentence + segsym for sentence in document.split(segsym)] 157 | sentences[-1] = sentences[-1][:len(sentences[-1])-1] # remove last segsym 158 | data, ignored = [], [] 159 | start = 0 160 | short_document = "" 161 | for sentence in sentences: 162 | if len(short_document) + len(sentence) <= max_seq_len: 163 | short_document += sentence 164 | else: 165 | if len(short_document) > 0: 166 | data.append({ 167 | "text": short_document, 168 | "spans": to_entities(short_document, tags[start: start + len(short_document)]) 169 | }) 170 | start += len(short_document) 171 | short_document = "" 172 | if len(sentence) <= max_seq_len: 173 | short_document = sentence 174 | else: 175 | # ignored long fragment 176 | ignored.append({ 177 | "text": sentence, 178 | "spans": to_entities(sentence, tags[start: start + len(sentence)]) 179 | }) 180 | start += len(sentence) 181 | if short_document != "": 182 | if len(short_document) <= max_seq_len: 183 | data.append({ 184 | "text": short_document, 185 | "spans": to_entities(short_document, tags[start: start + len(short_document)]) 186 | }) 187 | else: 188 | ignored.append({ 189 | "text": sentence, 190 | "spans": to_entities(sentence, tags[start: start + len(sentence)]) 191 | }) 192 | 193 | return (data, ignored) 194 | 195 | 196 | def collate_fn(input_pad_id: int, output_pad_id: int, device: str) -> Callable: 197 | """ 198 | Collate function for padding batch sentences. 199 | 200 | Args: 201 | input_pad_id (int): The ID of input pad. 202 | output_pad_id (int): The ID of output pad. 203 | device (str): Computing device. 204 | """ 205 | def collate_fn_wrapper(batch): 206 | max_seq_len = 0 207 | for i, _ in enumerate(batch): 208 | max_seq_len = max(max_seq_len, len(batch[i]["input_ids"])) 209 | for i, _ in enumerate(batch): 210 | batch[i]["input_ids"] += [input_pad_id] * (max_seq_len - len(batch[i]["input_ids"])) 211 | batch[i]["output_ids"] += [output_pad_id] * (max_seq_len - len(batch[i]["output_ids"])) 212 | batch[i]["masks"] = [1] * batch[i]["length"] + [0] * (max_seq_len - batch[i]["length"]) 213 | input_ids = torch.tensor([sample["input_ids"] for sample in batch], device=device) 214 | output_ids = torch.tensor([sample["output_ids"] for sample in batch], device=device) 215 | masks = torch.tensor([sample["masks"] for sample in batch], device=device) 216 | 217 | return (input_ids, output_ids, masks) 218 | 219 | return collate_fn_wrapper 220 | -------------------------------------------------------------------------------- /cfgen/tokenizer.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright (C) The Zhejiang University DMAC Lab Authors. team - All Rights Reserved 3 | # 4 | # Written by Xiangji Zeng , March 2020 5 | """Tokenizer""" 6 | 7 | import os 8 | from typing import Dict, Any, List, Union 9 | from collections import OrderedDict 10 | import json 11 | import random 12 | import torch 13 | import shutil 14 | from .common import save_text 15 | 16 | 17 | class BaseTokenizer: 18 | """ 19 | BaseTokenizer defines basic interfaces and implements common functions of a Tokenizer. 20 | 21 | Args: 22 | folder (str): The folder where all token files exist. 23 | urls (List[str]): A list of pretrained token file links. 24 | """ 25 | 26 | def __init__(self, folder: str, urls: List[str]): 27 | super(BaseTokenizer, self).__init__() 28 | self._folder = folder 29 | self._urls = urls 30 | self._to_ids = {} 31 | self._to_tokens = [] 32 | self._load() 33 | assert all([sptoken in self._to_ids.keys() for sptoken in ["[UNK]", "[PAD]", "[EMPTY]"]]) 34 | 35 | def save(self, folder: str) -> None: 36 | """ 37 | Save tokens and configuations into a given folder. 38 | 39 | Args: 40 | folder (str): Saving destination. 41 | """ 42 | shutil.copyfile(os.path.join(self._folder, "tokens.txt"), os.path.join(folder, "tokens.txt")) 43 | # shutil.copyfile(os.path.join(self._folder, "embeddings.checkpoints"), os.path.join(folder, "embeddings.checkpoints")) 44 | shutil.copyfile(os.path.join(self._folder, "configs.json"), os.path.join(folder, "configs.json")) 45 | 46 | def _load(self) -> None: 47 | """ 48 | Load all token mapping. 49 | """ 50 | file_names = ["tokens.txt", "embeddings.checkpoints", "configs.json"] 51 | raw_folder = os.path.join(self._folder, "raw") 52 | if not os.path.isdir(self._folder) or not os.path.isdir(raw_folder) or len(os.listdir(raw_folder)) == 0: 53 | if not os.path.isdir(raw_folder): 54 | os.makedirs(raw_folder) 55 | print("Tokenization data is not found, please download data into {0}.".format(raw_folder)) 56 | for url in self._urls: 57 | print(url) 58 | exit(0) 59 | if len(set(os.listdir(self._folder)).intersection(set(file_names))) != len(file_names): 60 | results = self._preprocess() 61 | assert all([key in file_names for key in results.keys()]) and len(results.keys()) == 3 62 | for key, value in results.items(): 63 | if key == "tokens.txt" and isinstance(value, list): 64 | save_text("\n".join(value), self._folder, "tokens.txt") 65 | elif key == "configs.json" and isinstance(value, dict): 66 | save_text(json.dumps(value, ensure_ascii=False), self._folder, "configs.json") 67 | elif key == "embeddings.checkpoints" and (isinstance(value, torch.FloatTensor) or isinstance(value, OrderedDict)): 68 | torch.save(value, os.path.join(self._folder, "embeddings.checkpoints")) 69 | else: 70 | raise ValueError("incorrect object {0} with type {1}".format(key, type(value))) 71 | with open(os.path.join(self._folder, "tokens.txt"), "r", encoding="utf-8") as f_in: 72 | for line in f_in.readlines(): 73 | token = line.replace("\n", "") 74 | if token != "": 75 | self._to_ids[token] = len(self) 76 | self._to_tokens.append(token) 77 | 78 | def __len__(self) -> int: 79 | """Return the total number of tokens.""" 80 | return len(self._to_tokens) 81 | 82 | def __getitem__(self, idx: Union[int, str]) -> Union[str, int]: 83 | """ 84 | Convert token into ID or ID into token. 85 | 86 | Args: 87 | idx (Union[int, str]): ID or label. 88 | """ 89 | if isinstance(idx, int) and 0 <= idx < len(self): 90 | return self._to_tokens[idx] 91 | if isinstance(idx, str) and idx in self._to_ids.keys(): 92 | return self._to_ids[idx] 93 | 94 | return self._to_ids[self.unk_token] 95 | 96 | @property 97 | def pad_token(self) -> str: 98 | """Return PAD token.""" 99 | return "[PAD]" 100 | 101 | @property 102 | def pad_id(self) -> int: 103 | """Return PAD ID.""" 104 | return self[self.pad_token] 105 | 106 | @property 107 | def unk_token(self) -> str: 108 | """Return UNK token.""" 109 | return "[UNK]" 110 | 111 | @property 112 | def unk_id(self) -> int: 113 | """Return UNK ID.""" 114 | return self[self.unk_token] 115 | 116 | @property 117 | def empty_token(self) -> str: 118 | """Return EMPTY token.""" 119 | return "[EMPTY]" 120 | 121 | @property 122 | def empty_id(self) -> int: 123 | """Return EMPTY ID.""" 124 | return self[self.empty_token] 125 | 126 | def convert_tokens_to_ids(self, tokens: List[str]) -> List[int]: 127 | """ 128 | Convert a list of tokens into IDs. 129 | 130 | Args: 131 | tokens (List[str]): A list of tokens. 132 | """ 133 | return [self[token] for token in tokens] 134 | 135 | def tokenize(self, text: str) -> List[str]: 136 | """ 137 | Tokenize a text into a list of tokens. 138 | 139 | Args: 140 | text (str): The text to be tokenized. 141 | """ 142 | return list(text) 143 | 144 | def token_embeddings(self) -> torch.FloatTensor: 145 | """Return token embeddings.""" 146 | return torch.load(os.path.join(self._folder, "embeddings.checkpoints")) 147 | 148 | def configs(self) -> Dict[str, Any]: 149 | """Return token configurations.""" 150 | with open(os.path.join(self._folder, "configs.json"), "r", encoding="utf-8") as f_in: 151 | content = json.loads(f_in.read()) 152 | return content 153 | 154 | def _preprocess(self) -> Dict[str, Any]: 155 | """Preprocess tokens, embeddings, and configurations.""" 156 | raise NotImplementedError 157 | 158 | 159 | class TCETokenizer(BaseTokenizer): 160 | """ 161 | Tokenizer for Tencent AILab Chinese Embedding. 162 | """ 163 | 164 | def __init__(self, folder: str): 165 | super(TCETokenizer, self).__init__( 166 | folder, 167 | [ 168 | "https://ai.tencent.com/ailab/nlp/en/embedding.html", 169 | "https://ai.tencent.com/ailab/nlp/en/data/Tencent_AILab_ChineseEmbedding.tar.gz" 170 | ] 171 | ) 172 | 173 | def _preprocess(self): 174 | """Preprocess tokens, embeddings, and configurations.""" 175 | raw_folder = os.path.join(self._folder, "raw") 176 | shutil.unpack_archive(os.path.join(raw_folder, "Tencent_AILab_ChineseEmbedding.tar.gz"), raw_folder) 177 | raw_file_name = os.path.join(raw_folder, "Tencent_AILab_ChineseEmbedding.txt") 178 | tokens, embeddings, token_dim = [], [], 0 179 | 180 | with open(raw_file_name, "r", encoding="utf-8") as f_in: 181 | line = f_in.readline() 182 | token_dim = int(line.split(" ")[1]) 183 | line = f_in.readline() 184 | while line: 185 | elems = line.split(" ") 186 | token, embedding = elems[0], [float(tok) for tok in elems[1:]] 187 | if len(token) == 1 and len(embedding) == token_dim: 188 | tokens.append(token) 189 | embeddings.append(embedding) 190 | line = f_in.readline() 191 | tokens.extend(["[UNK]", "[EMPTY]", "[PAD]"]) 192 | embeddings.extend([[random.uniform(0.0, 1.0) for _ in range(token_dim)], [0.0]*token_dim, [0.0]*token_dim]) 193 | embeddings = torch.tensor(embeddings) 194 | configs = {"n_tokens": len(tokens), "token_dim": token_dim} 195 | 196 | return {"tokens.txt": tokens, "configs.json": configs, "embeddings.checkpoints": embeddings} 197 | 198 | 199 | class BERTTokenizer(BaseTokenizer): 200 | """ 201 | Tokenizer for BERT base Chinese. 202 | """ 203 | 204 | def __init__(self, folder: str): 205 | super(BERTTokenizer, self).__init__( 206 | folder, 207 | [ 208 | "https://huggingface.co/bert-base-chinese#", 209 | "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-config.json", 210 | "https://cdn.huggingface.co/bert-base-chinese-pytorch_model.bin", 211 | "https://cdn.huggingface.co/bert-base-chinese-vocab.txt" 212 | ] 213 | ) 214 | 215 | def _preprocess(self): 216 | """Preprocess tokens, embeddings, and configurations.""" 217 | # we only take six layers of BERT model. 218 | n_layers = 6 219 | raw_folder = os.path.join(self._folder, "raw") 220 | # pretrained weights 221 | layer_names = tuple(["encoder.layer.{0}.".format(i) for i in range(n_layers)]) 222 | original_embeddings, embeddings = torch.load(os.path.join(raw_folder, "bert-base-chinese-pytorch_model.bin")), OrderedDict() 223 | for key, value in original_embeddings.items(): 224 | if not key.startswith("cls"): 225 | key = key.replace("bert.", "") 226 | if key.startswith("encoder.layer.") and not key.startswith(layer_names): 227 | continue 228 | key = key.replace("embeddings.word_embeddings", "embeddings.token_embeddings") 229 | key = key.replace("LayerNorm", "layer_norm") 230 | key = key.replace("gamma", "weight") 231 | key = key.replace("beta", "bias") 232 | embeddings[key] = value 233 | # tokens 234 | with open(os.path.join(raw_folder, "bert-base-chinese-vocab.txt"), "r", encoding="utf-8") as f_in: 235 | tokens = [line.replace("\n", "") for line in f_in.readlines()] 236 | tokens[99] = "[EMPTY]" 237 | # configs 238 | with open(os.path.join(raw_folder, "bert-base-chinese-config.json"), "r", encoding="utf-8") as f_in: 239 | original_configs = json.loads(f_in.read()) 240 | 241 | configs = { 242 | "attention_dropout": original_configs["attention_probs_dropout_prob"], 243 | "hidden_dropout": original_configs["hidden_dropout_prob"], 244 | "hidden_dim": original_configs["hidden_size"], 245 | "intermediate_size": original_configs["intermediate_size"], 246 | "layer_norm_eps": original_configs["layer_norm_eps"], 247 | "max_seq_len": original_configs["max_position_embeddings"], 248 | "n_heads": original_configs["num_attention_heads"], 249 | "n_layers": n_layers, 250 | "n_token_types": original_configs["type_vocab_size"], 251 | "n_tokens": original_configs["vocab_size"], 252 | "padding_id": tokens.index("[PAD]") 253 | } 254 | 255 | return {"tokens.txt": tokens, "configs.json": configs, "embeddings.checkpoints": embeddings} 256 | -------------------------------------------------------------------------------- /cfgen/trainer.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright (C) The Zhejiang University DMAC Lab Authors. team - All Rights Reserved 3 | # 4 | # Written by Xiangji Zeng , March 2020 5 | """Trainer""" 6 | 7 | import logging 8 | import sys 9 | import os 10 | import math 11 | from typing import List, Tuple, Dict, Any 12 | 13 | import torch 14 | import torch.nn as nn 15 | import torch.optim as optim 16 | from torch.nn import DataParallel 17 | from torch.utils.data import DataLoader 18 | from torch.utils.tensorboard import SummaryWriter 19 | 20 | from .tokenizer import TCETokenizer, BERTTokenizer 21 | from .inadapter import InCNER, InCLUNER 22 | from .outadapter import OutAdapter 23 | from .model import LSTMTagger, BERTTagger 24 | from .config import TrainerConfig 25 | from .metric import evalner 26 | from .generator import create_counterfactual_examples 27 | from .common import collate_fn, to_entities 28 | 29 | 30 | __TOKENIZER_MAP__ = {"tce": TCETokenizer, "bert": BERTTokenizer} 31 | __MODEL_MAP__ = {"bilstm": LSTMTagger, "bert": BERTTagger} 32 | __DATASET_MAP__ = {"cner": InCNER, "cluener": InCLUNER} 33 | 34 | 35 | class NERTrainer: 36 | """ 37 | NERTrainer manages to train and test NER models on different datasets. 38 | 39 | Args: 40 | config (TrainerConfig): Trainer configuration. 41 | datasets (Tuple[list, list, list]): Train/Dev/Test set. 42 | """ 43 | 44 | def __init__(self, config: TrainerConfig, datasets: Tuple[list, list, list]): 45 | super(NERTrainer, self).__init__() 46 | writer_folder = os.path.join(config.output_folder, "summary") 47 | if not os.path.isdir(writer_folder): 48 | os.makedirs(writer_folder) 49 | self._config = config 50 | self._tokenizer = __TOKENIZER_MAP__[config.tokenizer](config.tokenizer_folder) 51 | self._tokenizer.save(config.output_folder) 52 | self._outadapter = OutAdapter(config.dataset_folder) 53 | self._outadapter.save(config.output_folder) 54 | self._trainset = __DATASET_MAP__[config.dataset](datasets[0], config.max_seq_len, self._outadapter, self._tokenizer) 55 | self._devset = __DATASET_MAP__[config.dataset](datasets[1], config.max_seq_len, self._outadapter, self._tokenizer) 56 | self._testset = __DATASET_MAP__[config.dataset](datasets[2], config.max_seq_len, self._outadapter, self._tokenizer) 57 | self._collate_fn = collate_fn(self._tokenizer.pad_id, self._outadapter.pad_id, config.device) 58 | self._trainloader = DataLoader(self._trainset, config.batch_size, collate_fn=self._collate_fn) 59 | self._devloader = DataLoader(self._devset, config.batch_size, collate_fn=self._collate_fn) 60 | self._testloader = DataLoader(self._testset, config.batch_size, collate_fn=self._collate_fn) 61 | config.hyperparameters["n_tags"] = len(self._outadapter) 62 | config.hyperparameters["empty_id"] = self._tokenizer.empty_id 63 | config.hyperparameters.update(self._tokenizer.configs()) 64 | self._model = __MODEL_MAP__[config.model]( 65 | **config.hyperparameters, token_embeddings=self._tokenizer.token_embeddings() 66 | ).to(config.device) 67 | if len(config.gpu) > 1: 68 | self._model = DataParallel(self._model, device_ids=config.gpu) 69 | self._loss_fn = nn.CrossEntropyLoss() 70 | self._optimizer = optim.Adam(self._model.parameters(), lr=config.learning_rate) 71 | self._writer = SummaryWriter(writer_folder) 72 | formatter = logging.Formatter("%(asctime)s %(message)s", "%Y-%m-%d %H:%M:%S") 73 | self._logger = logging.getLogger(__name__) 74 | self._logger.handlers.clear() 75 | fh = logging.FileHandler(os.path.join(config.output_folder, "log.txt")) 76 | fh.setFormatter(formatter) 77 | sh = logging.StreamHandler(sys.stdout) 78 | sh.setFormatter(formatter) 79 | self._logger.addHandler(fh) 80 | self._logger.addHandler(sh) 81 | self._logger.setLevel(logging.DEBUG) 82 | 83 | def load_checkpoints(self) -> None: 84 | """Load trained checkpoints from local disk.""" 85 | checkpoints_path = os.path.join(self._config.output_folder, "model.checkpoints") 86 | if os.path.isfile(checkpoints_path): 87 | checkpoints = torch.load(checkpoints_path, map_location=torch.device("cpu")) 88 | if isinstance(self._model, DataParallel): 89 | self._model.module.load_state_dict(checkpoints) 90 | elif isinstance(self._model, nn.Module): 91 | self._model.load_state_dict(checkpoints) 92 | 93 | def save_checkpoints(self) -> None: 94 | """Save trained checkpoints into local disk.""" 95 | checkpoints_path = os.path.join(self._config.output_folder, "model.checkpoints") 96 | if isinstance(self._model, DataParallel): 97 | checkpoints = self._model.module.state_dict() 98 | else: 99 | checkpoints = self._model.state_dict() 100 | torch.save(checkpoints, checkpoints_path) 101 | 102 | def log(self, content: str, y_value: float = None, x_value: float = None) -> None: 103 | """ 104 | Record status by logging, tensorboard. If x_value or y_value is None, we regard content 105 | as text and record it. Otherwise, we regard content as a record classification for merge 106 | the same values (x, y). The commonly used record classifications are F1 score, precision 107 | score, etc. 108 | 109 | Args: 110 | content (str): Logging content. 111 | y_value (float): Y input. 112 | x_value (float): X input. 113 | """ 114 | if y_value is not None and x_value is not None: 115 | self._writer.add_scalar("{0}/{1}".format(self._config.identity, content), y_value, x_value) 116 | else: 117 | self._writer.add_text("{0}/log".format(self._config.identity), content) 118 | content = "[{0}-{1}] ".format(self._config.model, self._config.dataset) + content 119 | self._logger.debug(content) 120 | 121 | def test(self, loader: DataLoader = None) -> Dict[str, Any]: 122 | """ 123 | Return model's performance. 124 | 125 | Args: 126 | loader (DataLoader): Dataloader to be tested. 127 | """ 128 | if loader is None: 129 | loader = self._testloader 130 | self._model.eval() 131 | batch_gold_labels, batch_pred_labels = [], [] 132 | for _, batch in enumerate(loader): 133 | input_ids, output_ids, masks = batch 134 | preds_ = self._model(input_ids, masks) 135 | pred_labels = [[self._outadapter[label_id] for label_id in label_ids] for label_ids in preds_.argmax(dim=-1).tolist()] 136 | batch_pred_labels.extend(pred_labels) 137 | gold_labels = [[self._outadapter[label_id] for label_id in label_ids] for label_ids in output_ids.tolist()] 138 | batch_gold_labels.extend(gold_labels) 139 | del batch, input_ids, preds_ 140 | 141 | return evalner(batch_gold_labels, batch_pred_labels) 142 | 143 | def train(self) -> Dict[str, Any]: 144 | """Start to train model on a given dataset.""" 145 | no_improvemnet, max_f1_score = 0, -math.inf 146 | for epoch in range(self._config.epoch): 147 | self._model.train() 148 | total_loss = 0. 149 | for _, batch in enumerate(self._trainloader): 150 | input_ids, output_ids, masks = batch 151 | self._model.zero_grad() 152 | preds_ = self._model(input_ids, masks) 153 | loss = self._loss_fn(preds_.view(-1, len(self._outadapter)), output_ids.view(-1)) 154 | loss.backward() 155 | self._optimizer.step() 156 | total_loss += loss.item() 157 | del batch, loss, input_ids, output_ids 158 | train_loss = total_loss / len(self._trainloader) 159 | evaluations = self.test(self._devloader) 160 | self.log("f1", evaluations["entity"]["f1"], epoch) 161 | self.log("p", evaluations["entity"]["p"], epoch) 162 | self.log("r", evaluations["entity"]["r"], epoch) 163 | self.log("train_loss", train_loss, epoch) 164 | self.log("epoch {0} dev-f1: {1}, dev-p: {2}, dev-r: {3}, train-loss: {4}".format( 165 | epoch, evaluations["entity"]["f1"], evaluations["entity"]["p"], evaluations["entity"]["r"], train_loss 166 | )) 167 | if evaluations["entity"]["f1"] > max_f1_score: 168 | max_f1_score = evaluations["entity"]["f1"] 169 | no_improvemnet = 0 170 | self.save_checkpoints() 171 | else: 172 | no_improvemnet += 1 173 | if train_loss < self._config.early_stop_loss or no_improvemnet > self._config.stop_if_no_improvement: 174 | break 175 | self.load_checkpoints() 176 | evaluations = self.test(self._testloader) 177 | self.log("test-f1: {0}, test-p: {1}, test-r: {2}".format(evaluations["entity"]["f1"], evaluations["entity"]["p"], evaluations["entity"]["r"])) 178 | 179 | return evaluations 180 | 181 | def create_discriminated_examples(self, trainset: List[dict]) -> List[dict]: 182 | """ 183 | Create new counterfactual examples with a discriminator from a observational seed examples. 184 | 185 | Args: 186 | trainset (List[dict]): A list of observational seed examples. 187 | """ 188 | self.load_checkpoints() 189 | self._model.eval() 190 | all_cfexamples = create_counterfactual_examples(trainset) 191 | reasonable_cfexamples, unreasonable_cfexamples = [], [] 192 | dataset = __DATASET_MAP__[self._config.dataset](all_cfexamples, self._config.max_seq_len, self._outadapter, self._tokenizer) 193 | dataloader = DataLoader(dataset, self._config.batch_size, collate_fn=self._collate_fn) 194 | for i, batch in enumerate(dataloader): 195 | input_ids, output_ids, masks = batch 196 | preds_ = self._model(input_ids, masks) 197 | pred_labels = [[self._outadapter[label_id] for label_id in label_ids] for label_ids in preds_.argmax(dim=-1).tolist()] 198 | for j, labels in enumerate(pred_labels): 199 | text = all_cfexamples[i*self._config.batch_size + j]["text"] 200 | replaced_spans = all_cfexamples[i*self._config.batch_size + j]["replaced"] 201 | predicted_spans = ["[{0}]({1}, {2})".format(span["label"], span["start"], span["end"]) for span in to_entities(text, labels)] 202 | if len(set(replaced_spans).intersection(set(predicted_spans))) == len(replaced_spans): 203 | reasonable_cfexamples.append(all_cfexamples[i*self._config.batch_size + j]) 204 | else: 205 | unreasonable_cfexamples.append(all_cfexamples[i*self._config.batch_size + j]) 206 | 207 | return (reasonable_cfexamples, unreasonable_cfexamples) 208 | -------------------------------------------------------------------------------- /cfgen/inadapter.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright (C) The Zhejiang University DMAC Lab Authors. team - All Rights Reserved 3 | # 4 | # Written by Xiangji Zeng , March 2020 5 | """Input Adapters""" 6 | 7 | import os 8 | import random 9 | import json 10 | import shutil 11 | from typing import Dict, Any, List, Tuple 12 | 13 | from torch.utils.data import Dataset 14 | from .common import save_text, load_jsonl, split_document 15 | from .tokenizer import BaseTokenizer 16 | from .outadapter import OutAdapter 17 | 18 | 19 | class BaseInAdapter(Dataset): 20 | """ 21 | BaseInAdapter provides functions to process various datasets and collate them into a uniform format for feeding 22 | the neural nets. 23 | 24 | Args: 25 | data (List[dict]): A list of preprocessed datapoints. 26 | max_seq_len (int): The maximum length of a sentence. 27 | outadapter (OutAdapter): Output adapter. 28 | tokenizer (BaseTokenizer): Tokenizer. 29 | """ 30 | 31 | urls = [] 32 | 33 | def __init__(self, data: List[dict], max_seq_len: int, outadapter: OutAdapter, tokenizer: BaseTokenizer): 34 | super(BaseInAdapter, self).__init__() 35 | self._dataset = [self.transform_example(example, max_seq_len, outadapter, tokenizer) for example in data] 36 | 37 | @classmethod 38 | def split_datasets(cls, data_folder: str, max_seq_len: int, is_random: bool = True, testpp: float = 0.1) -> Tuple[list, list, list]: 39 | """ 40 | Split datasets into three parts: train/dev/test. 41 | 42 | Args: 43 | data_folder (str): The dataset folder. 44 | max_seq_len (int): The maximum length of a text. 45 | is_random (bool): When preprocessing the dataset, whether to ramdom all datapoints. 46 | testpp (float): The proportion of test set. 47 | """ 48 | files = set(["data.jsonl", "labels.txt", "unqualified_data.txt", "train.jsonl", "dev.jsonl", "test.jsonl"]) 49 | raw_folder = os.path.join(data_folder, "raw") 50 | if not os.path.isdir(data_folder) or not os.path.isdir(raw_folder) or len(os.listdir(raw_folder)) == 0: 51 | if not os.path.isdir(raw_folder): 52 | os.makedirs(raw_folder) 53 | print("Data is not found, please download data into {0}.".format(raw_folder)) 54 | for url in cls.urls: 55 | print(url) 56 | exit(0) 57 | if len(set(os.listdir(data_folder)).intersection(files)) != len(files): 58 | data, labels, unqualified_data = cls._preprocess(data_folder, max_seq_len, is_random) 59 | n_trains, n_tests = len(data) - int(testpp*2*len(data)), int(testpp*len(data)) 60 | trainset, devset, testset = data[:n_trains], data[n_trains: n_trains + n_tests], data[n_trains + n_tests:] 61 | save_text("\n".join([json.dumps(sample, ensure_ascii=False) for sample in data]), data_folder, "data.jsonl") 62 | save_text("\n".join([json.dumps(sample, ensure_ascii=False) for sample in trainset]), data_folder, "train.jsonl") 63 | save_text("\n".join([json.dumps(sample, ensure_ascii=False) for sample in devset]), data_folder, "dev.jsonl") 64 | save_text("\n".join([json.dumps(sample, ensure_ascii=False) for sample in testset]), data_folder, "test.jsonl") 65 | save_text("\n".join(labels), data_folder, "labels.txt") 66 | save_text("\n".join(unqualified_data), data_folder, "unqualified_data.txt") 67 | print( 68 | "{0} data ({1} trains, {2} devs, {3} tests), {4} labels, {5} unqualified_data in {6}" 69 | .format(len(data), len(trainset), len(devset), len(testset), len(labels), len(unqualified_data), data_folder) 70 | ) 71 | trainset = load_jsonl(data_folder, "train.jsonl") 72 | devset = load_jsonl(data_folder, "dev.jsonl") 73 | testset = load_jsonl(data_folder, "test.jsonl") 74 | 75 | return (trainset, devset, testset) 76 | 77 | @staticmethod 78 | def _preprocess(data_folder: str, max_seq_len: int, is_random: bool) -> (List[dict], List[str], List[str]): 79 | """ 80 | Preprocess datasets. 81 | 82 | Args: 83 | data_folder (str): The dataset folder. 84 | max_seq_len (int): The maximum length of a text. 85 | is_random (bool): When preprocessing the dataset, whether to ramdom all datapoints. 86 | """ 87 | raise NotImplementedError 88 | 89 | def transform_example(self, example: Dict[str, Any], max_seq_len: int, outadapter: OutAdapter, tokenizer: BaseTokenizer) -> Dict[str, Any]: 90 | """ 91 | Transform the raw datapoint into numbers. 92 | 93 | Args: 94 | example (Dict[str, Any]): The raw datapoint. 95 | max_seq_len (int): The maximum length of a sentence. 96 | outadapter (OutAdapter): The output adapter. 97 | tokenizer (BaseTokenizer): Tokenizer. 98 | """ 99 | input_tokens = tokenizer.tokenize(example["text"])[:max_seq_len] 100 | output_labels = [outadapter.pad_label] * len(input_tokens) 101 | for span in example["spans"]: 102 | label = span["label"] 103 | if span["start"] < len(input_tokens): 104 | output_labels[span["start"]] = "B-{0}".format(label) 105 | pointer = span["start"] + 1 106 | while pointer <= span["end"] and pointer < len(input_tokens): 107 | output_labels[pointer] = "I-{0}".format(label) 108 | pointer += 1 109 | input_ids = tokenizer.convert_tokens_to_ids(input_tokens) 110 | output_ids = [outadapter[label] for label in output_labels] 111 | 112 | return {"input_ids": input_ids, "output_ids": output_ids, "length": len(input_ids)} 113 | 114 | def __len__(self) -> int: 115 | """Return the total number of datapoints.""" 116 | return len(self._dataset) 117 | 118 | def __getitem__(self, idx: int) -> Dict[str, Any]: 119 | """ 120 | Return the converted datapoint. 121 | 122 | Args: 123 | idx (int): The index of the datapoint. 124 | """ 125 | return self._dataset[idx] 126 | 127 | 128 | class InCNER(BaseInAdapter): 129 | """ 130 | Input Adapter for the dataset CNER. 131 | """ 132 | 133 | urls = ["http://www.ccks2019.cn/?page_id=62"] 134 | 135 | @staticmethod 136 | def _preprocess(data_folder: str, max_seq_len: int, is_random: bool) -> (List[dict], List[str], List[str]): 137 | """ 138 | Preprocess datasets. 139 | 140 | Args: 141 | data_folder (str): The dataset folder. 142 | max_seq_len (int): The maximum length of a text. 143 | is_random (bool): When preprocessing the dataset, whether to ramdom all datapoints. 144 | """ 145 | extracted_types = ["疾病和诊断"] 146 | raw_file_names = ["subtask1_training_part1.txt", "subtask1_training_part2.txt", "subtask1_test_set_with_answer.json"] 147 | raw_samples = [] 148 | for file_name in raw_file_names: 149 | file_name = os.path.join(data_folder, "raw", file_name) 150 | if not os.path.isfile(file_name): 151 | continue 152 | with open(file_name, "r", encoding="utf-8-sig") as f_in: 153 | for line in f_in.readlines(): 154 | sample = json.loads(line) 155 | raw_samples.append((file_name, sample)) 156 | data, unqualified_data = [], [] 157 | labels = ["O"] + ["{}-{}".format(prefix, label) for prefix in ["B", "I"] for label in extracted_types] 158 | 159 | for _, (file_name, sample) in enumerate(raw_samples): 160 | text, spans, is_normalized = sample["originalText"], [], True 161 | for span in sample["entities"]: 162 | if span["label_type"] not in extracted_types: 163 | continue 164 | if "overlap" in span and span["overlap"] > 0: 165 | is_normalized = False 166 | unqualified_data.append("{0}\t{1}".format(file_name, "overlap in {0}".format(text))) 167 | break 168 | start, end = span["start_pos"], span["end_pos"] 169 | spans.append({ 170 | "text": text[start: end], 171 | "label": span["label_type"], 172 | "start": start, 173 | "end": end - 1 174 | }) 175 | 176 | if is_normalized: 177 | spans.sort(key=lambda ann: ann["start"]) 178 | if len(text) > max_seq_len: 179 | samples, ignored = split_document(text, spans, max_seq_len) 180 | for sample in ignored: 181 | unqualified_data.append("{0}\t{1}".format(file_name, "document too long in {0}".format(sample["text"]))) 182 | else: 183 | samples = [{"text": text, "spans": spans}] 184 | data.extend(samples) 185 | 186 | if is_random: 187 | random.shuffle(data) 188 | 189 | return (data, labels, unqualified_data) 190 | 191 | 192 | class InCLUNER(BaseInAdapter): 193 | """ 194 | Input Adapter for the dataset CLUENER. 195 | """ 196 | 197 | urls = ["https://github.com/chineseGLUE/chineseGLUE"] 198 | 199 | @staticmethod 200 | def _preprocess(data_folder: str, max_seq_len: int, is_random: bool) -> (List[dict], List[str], List[str]): 201 | """ 202 | Preprocess datasets. 203 | 204 | Args: 205 | data_folder (str): The dataset folder. 206 | max_seq_len (int): The maximum length of a text. 207 | is_random (bool): When preprocessing the dataset, whether to ramdom all datapoints. 208 | """ 209 | raw_folder = os.path.join(data_folder, "raw") 210 | shutil.unpack_archive(os.path.join(raw_folder, "cluener_public.zip"), raw_folder) 211 | extracted_types = ["address", "book", "company", "game", "government", "movie", "name", "organization", "position", "scene"] 212 | raw_file_names = ["train.json", "dev.json"] 213 | data, unqualified_data = [], [] 214 | labels = ["O"] + ["{}-{}".format(prefix, label) for prefix in ["B", "I"] for label in extracted_types] 215 | 216 | for file_name in raw_file_names: 217 | file_name = os.path.join(data_folder, "raw", file_name) 218 | with open(file_name, "r", encoding="utf-8") as f_in: 219 | for line in f_in.readlines(): 220 | sample = json.loads(line) 221 | if len(sample["text"]) > max_seq_len: 222 | unqualified_data.append("{0}\texceed maximum length: {1}".format(file_name, sample["text"])) 223 | continue 224 | spans = [] 225 | for label, span in sample["label"].items(): 226 | if label not in extracted_types: 227 | unqualified_data.append("{0}\tcan not extract {1} from {2}".format(file_name, label, sample["text"])) 228 | continue 229 | for text, text_range in span.items(): 230 | spans.append({ 231 | "text": text, 232 | "label": label, 233 | "start": text_range[0][0], 234 | "end": text_range[0][1], 235 | }) 236 | data.append({ 237 | "text": sample["text"], 238 | "spans": spans 239 | }) 240 | 241 | if is_random: 242 | random.shuffle(data) 243 | 244 | return (data, labels, unqualified_data) 245 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NonCommercial 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More_considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-NonCommercial 4.0 International Public 58 | License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-NonCommercial 4.0 International Public License ("Public 63 | License"). To the extent this Public License may be interpreted as a 64 | contract, You are granted the Licensed Rights in consideration of Your 65 | acceptance of these terms and conditions, and the Licensor grants You 66 | such rights in consideration of benefits the Licensor receives from 67 | making the Licensed Material available under these terms and 68 | conditions. 69 | 70 | Section 1 -- Definitions. 71 | 72 | a. Adapted Material means material subject to Copyright and Similar 73 | Rights that is derived from or based upon the Licensed Material 74 | and in which the Licensed Material is translated, altered, 75 | arranged, transformed, or otherwise modified in a manner requiring 76 | permission under the Copyright and Similar Rights held by the 77 | Licensor. For purposes of this Public License, where the Licensed 78 | Material is a musical work, performance, or sound recording, 79 | Adapted Material is always produced where the Licensed Material is 80 | synched in timed relation with a moving image. 81 | 82 | b. Adapter's License means the license You apply to Your Copyright 83 | and Similar Rights in Your contributions to Adapted Material in 84 | accordance with the terms and conditions of this Public License. 85 | 86 | c. Copyright and Similar Rights means copyright and/or similar rights 87 | closely related to copyright including, without limitation, 88 | performance, broadcast, sound recording, and Sui Generis Database 89 | Rights, without regard to how the rights are labeled or 90 | categorized. For purposes of this Public License, the rights 91 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 92 | Rights. 93 | d. Effective Technological Measures means those measures that, in the 94 | absence of proper authority, may not be circumvented under laws 95 | fulfilling obligations under Article 11 of the WIPO Copyright 96 | Treaty adopted on December 20, 1996, and/or similar international 97 | agreements. 98 | 99 | e. Exceptions and Limitations means fair use, fair dealing, and/or 100 | any other exception or limitation to Copyright and Similar Rights 101 | that applies to Your use of the Licensed Material. 102 | 103 | f. Licensed Material means the artistic or literary work, database, 104 | or other material to which the Licensor applied this Public 105 | License. 106 | 107 | g. Licensed Rights means the rights granted to You subject to the 108 | terms and conditions of this Public License, which are limited to 109 | all Copyright and Similar Rights that apply to Your use of the 110 | Licensed Material and that the Licensor has authority to license. 111 | 112 | h. Licensor means the individual(s) or entity(ies) granting rights 113 | under this Public License. 114 | 115 | i. NonCommercial means not primarily intended for or directed towards 116 | commercial advantage or monetary compensation. For purposes of 117 | this Public License, the exchange of the Licensed Material for 118 | other material subject to Copyright and Similar Rights by digital 119 | file-sharing or similar means is NonCommercial provided there is 120 | no payment of monetary compensation in connection with the 121 | exchange. 122 | 123 | j. Share means to provide material to the public by any means or 124 | process that requires permission under the Licensed Rights, such 125 | as reproduction, public display, public performance, distribution, 126 | dissemination, communication, or importation, and to make material 127 | available to the public including in ways that members of the 128 | public may access the material from a place and at a time 129 | individually chosen by them. 130 | 131 | k. Sui Generis Database Rights means rights other than copyright 132 | resulting from Directive 96/9/EC of the European Parliament and of 133 | the Council of 11 March 1996 on the legal protection of databases, 134 | as amended and/or succeeded, as well as other essentially 135 | equivalent rights anywhere in the world. 136 | 137 | l. You means the individual or entity exercising the Licensed Rights 138 | under this Public License. Your has a corresponding meaning. 139 | 140 | Section 2 -- Scope. 141 | 142 | a. License grant. 143 | 144 | 1. Subject to the terms and conditions of this Public License, 145 | the Licensor hereby grants You a worldwide, royalty-free, 146 | non-sublicensable, non-exclusive, irrevocable license to 147 | exercise the Licensed Rights in the Licensed Material to: 148 | 149 | a. reproduce and Share the Licensed Material, in whole or 150 | in part, for NonCommercial purposes only; and 151 | 152 | b. produce, reproduce, and Share Adapted Material for 153 | NonCommercial purposes only. 154 | 155 | 2. Exceptions and Limitations. For the avoidance of doubt, where 156 | Exceptions and Limitations apply to Your use, this Public 157 | License does not apply, and You do not need to comply with 158 | its terms and conditions. 159 | 160 | 3. Term. The term of this Public License is specified in Section 161 | 6(a). 162 | 163 | 4. Media and formats; technical modifications allowed. The 164 | Licensor authorizes You to exercise the Licensed Rights in 165 | all media and formats whether now known or hereafter created, 166 | and to make technical modifications necessary to do so. The 167 | Licensor waives and/or agrees not to assert any right or 168 | authority to forbid You from making technical modifications 169 | necessary to exercise the Licensed Rights, including 170 | technical modifications necessary to circumvent Effective 171 | Technological Measures. For purposes of this Public License, 172 | simply making modifications authorized by this Section 2(a) 173 | (4) never produces Adapted Material. 174 | 175 | 5. Downstream recipients. 176 | 177 | a. Offer from the Licensor -- Licensed Material. Every 178 | recipient of the Licensed Material automatically 179 | receives an offer from the Licensor to exercise the 180 | Licensed Rights under the terms and conditions of this 181 | Public License. 182 | 183 | b. No downstream restrictions. You may not offer or impose 184 | any additional or different terms or conditions on, or 185 | apply any Effective Technological Measures to, the 186 | Licensed Material if doing so restricts exercise of the 187 | Licensed Rights by any recipient of the Licensed 188 | Material. 189 | 190 | 6. No endorsement. Nothing in this Public License constitutes or 191 | may be construed as permission to assert or imply that You 192 | are, or that Your use of the Licensed Material is, connected 193 | with, or sponsored, endorsed, or granted official status by, 194 | the Licensor or others designated to receive attribution as 195 | provided in Section 3(a)(1)(A)(i). 196 | 197 | b. Other rights. 198 | 199 | 1. Moral rights, such as the right of integrity, are not 200 | licensed under this Public License, nor are publicity, 201 | privacy, and/or other similar personality rights; however, to 202 | the extent possible, the Licensor waives and/or agrees not to 203 | assert any such rights held by the Licensor to the limited 204 | extent necessary to allow You to exercise the Licensed 205 | Rights, but not otherwise. 206 | 207 | 2. Patent and trademark rights are not licensed under this 208 | Public License. 209 | 210 | 3. To the extent possible, the Licensor waives any right to 211 | collect royalties from You for the exercise of the Licensed 212 | Rights, whether directly or through a collecting society 213 | under any voluntary or waivable statutory or compulsory 214 | licensing scheme. In all other cases the Licensor expressly 215 | reserves any right to collect such royalties, including when 216 | the Licensed Material is used other than for NonCommercial 217 | purposes. 218 | 219 | Section 3 -- License Conditions. 220 | 221 | Your exercise of the Licensed Rights is expressly made subject to the 222 | following conditions. 223 | 224 | a. Attribution. 225 | 226 | 1. If You Share the Licensed Material (including in modified 227 | form), You must: 228 | 229 | a. retain the following if it is supplied by the Licensor 230 | with the Licensed Material: 231 | 232 | i. identification of the creator(s) of the Licensed 233 | Material and any others designated to receive 234 | attribution, in any reasonable manner requested by 235 | the Licensor (including by pseudonym if 236 | designated); 237 | 238 | ii. a copyright notice; 239 | 240 | iii. a notice that refers to this Public License; 241 | 242 | iv. a notice that refers to the disclaimer of 243 | warranties; 244 | 245 | v. a URI or hyperlink to the Licensed Material to the 246 | extent reasonably practicable; 247 | 248 | b. indicate if You modified the Licensed Material and 249 | retain an indication of any previous modifications; and 250 | 251 | c. indicate the Licensed Material is licensed under this 252 | Public License, and include the text of, or the URI or 253 | hyperlink to, this Public License. 254 | 255 | 2. You may satisfy the conditions in Section 3(a)(1) in any 256 | reasonable manner based on the medium, means, and context in 257 | which You Share the Licensed Material. For example, it may be 258 | reasonable to satisfy the conditions by providing a URI or 259 | hyperlink to a resource that includes the required 260 | information. 261 | 262 | 3. If requested by the Licensor, You must remove any of the 263 | information required by Section 3(a)(1)(A) to the extent 264 | reasonably practicable. 265 | 266 | 4. If You Share Adapted Material You produce, the Adapter's 267 | License You apply must not prevent recipients of the Adapted 268 | Material from complying with this Public License. 269 | 270 | Section 4 -- Sui Generis Database Rights. 271 | 272 | Where the Licensed Rights include Sui Generis Database Rights that 273 | apply to Your use of the Licensed Material: 274 | 275 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 276 | to extract, reuse, reproduce, and Share all or a substantial 277 | portion of the contents of the database for NonCommercial purposes 278 | only; 279 | 280 | b. if You include all or a substantial portion of the database 281 | contents in a database in which You have Sui Generis Database 282 | Rights, then the database in which You have Sui Generis Database 283 | Rights (but not its individual contents) is Adapted Material; and 284 | 285 | c. You must comply with the conditions in Section 3(a) if You Share 286 | all or a substantial portion of the contents of the database. 287 | 288 | For the avoidance of doubt, this Section 4 supplements and does not 289 | replace Your obligations under this Public License where the Licensed 290 | Rights include other Copyright and Similar Rights. 291 | 292 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 293 | 294 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 295 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 296 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 297 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 298 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 299 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 300 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 301 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 302 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 303 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 304 | 305 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 306 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 307 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 308 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 309 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 310 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 311 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 312 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 313 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 314 | 315 | c. The disclaimer of warranties and limitation of liability provided 316 | above shall be interpreted in a manner that, to the extent 317 | possible, most closely approximates an absolute disclaimer and 318 | waiver of all liability. 319 | 320 | Section 6 -- Term and Termination. 321 | 322 | a. This Public License applies for the term of the Copyright and 323 | Similar Rights licensed here. However, if You fail to comply with 324 | this Public License, then Your rights under this Public License 325 | terminate automatically. 326 | 327 | b. Where Your right to use the Licensed Material has terminated under 328 | Section 6(a), it reinstates: 329 | 330 | 1. automatically as of the date the violation is cured, provided 331 | it is cured within 30 days of Your discovery of the 332 | violation; or 333 | 334 | 2. upon express reinstatement by the Licensor. 335 | 336 | For the avoidance of doubt, this Section 6(b) does not affect any 337 | right the Licensor may have to seek remedies for Your violations 338 | of this Public License. 339 | 340 | c. For the avoidance of doubt, the Licensor may also offer the 341 | Licensed Material under separate terms or conditions or stop 342 | distributing the Licensed Material at any time; however, doing so 343 | will not terminate this Public License. 344 | 345 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 346 | License. 347 | 348 | Section 7 -- Other Terms and Conditions. 349 | 350 | a. The Licensor shall not be bound by any additional or different 351 | terms or conditions communicated by You unless expressly agreed. 352 | 353 | b. Any arrangements, understandings, or agreements regarding the 354 | Licensed Material not stated herein are separate from and 355 | independent of the terms and conditions of this Public License. 356 | 357 | Section 8 -- Interpretation. 358 | 359 | a. For the avoidance of doubt, this Public License does not, and 360 | shall not be interpreted to, reduce, limit, restrict, or impose 361 | conditions on any use of the Licensed Material that could lawfully 362 | be made without permission under this Public License. 363 | 364 | b. To the extent possible, if any provision of this Public License is 365 | deemed unenforceable, it shall be automatically reformed to the 366 | minimum extent necessary to make it enforceable. If the provision 367 | cannot be reformed, it shall be severed from this Public License 368 | without affecting the enforceability of the remaining terms and 369 | conditions. 370 | 371 | c. No term or condition of this Public License will be waived and no 372 | failure to comply consented to unless expressly agreed to by the 373 | Licensor. 374 | 375 | d. Nothing in this Public License constitutes or may be interpreted 376 | as a limitation upon, or waiver of, any privileges and immunities 377 | that apply to the Licensor or You, including from the legal 378 | processes of any jurisdiction or authority. 379 | 380 | ======================================================================= 381 | 382 | Creative Commons is not a party to its public 383 | licenses. Notwithstanding, Creative Commons may elect to apply one of 384 | its public licenses to material it publishes and in those instances 385 | will be considered the “Licensor.” The text of the Creative Commons 386 | public licenses is dedicated to the public domain under the CC0 Public 387 | Domain Dedication. Except for the limited purpose of indicating that 388 | material is shared under a Creative Commons public license or as 389 | otherwise permitted by the Creative Commons policies published at 390 | creativecommons.org/policies, Creative Commons does not authorize the 391 | use of the trademark "Creative Commons" or any other trademark or logo 392 | of Creative Commons without its prior written consent including, 393 | without limitation, in connection with any unauthorized modifications 394 | to any of its public licenses or any other arrangements, 395 | understandings, or agreements concerning use of licensed material. For 396 | the avoidance of doubt, this paragraph does not form part of the 397 | public licenses. 398 | 399 | Creative Commons may be contacted at creativecommons.org. -------------------------------------------------------------------------------- /cfgen/model.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright (C) The Zhejiang University DMAC Lab Authors. team - All Rights Reserved 3 | # 4 | # Written by Xiangji Zeng , March 2020 5 | """Model Zoo""" 6 | 7 | __all__ = ["LSTMTagger", "BERTTagger"] 8 | 9 | import math 10 | from collections import OrderedDict 11 | import torch 12 | import torch.nn as nn 13 | from torch import FloatTensor 14 | 15 | 16 | def gelu(inputs: torch.FloatTensor) -> torch.FloatTensor: 17 | """ 18 | Gaussian Error Linear Units (GELUs) 19 | 20 | References: 21 | [1] https://arxiv.org/abs/1606.08415 22 | 23 | Args: 24 | inputs (torch.FloatTensor): Inputs. 25 | """ 26 | return inputs * 0.5 * (1.0 + torch.erf(inputs / math.sqrt(2.0))) 27 | 28 | 29 | class BERTEmbeddings(nn.Module): 30 | """ 31 | BERTEmbedding: token_embedding + position_embedding + token_type_embedding. 32 | 33 | Args: 34 | n_tokens (int): The total number of tokens. 35 | hidden_dim (int): The dimension of embedding. 36 | max_seq_len (int): The maximum length of the input sequence. 37 | n_token_types (int): The number of token types. 38 | empty_id (int): The ID of the special token [EMPTY], we will conduct a DO operation on empty id. 39 | padding_id (int): PAD ID. 40 | hidden_dropout (float): Dropout probability for hidden states. 41 | layer_norm_eps (float): Layer normalization eps. 42 | """ 43 | 44 | def __init__( 45 | self, 46 | n_tokens: int, 47 | hidden_dim: int, 48 | max_seq_len: int, 49 | n_token_types: int, 50 | empty_id: int, 51 | padding_id: int, 52 | hidden_dropout: float, 53 | layer_norm_eps: float 54 | ): 55 | super(BERTEmbeddings, self).__init__() 56 | self.empty_id = empty_id 57 | self.token_embeddings = nn.Embedding(n_tokens, hidden_dim, padding_id) 58 | self.position_embeddings = nn.Embedding(max_seq_len, hidden_dim) 59 | self.token_type_embeddings = nn.Embedding(n_token_types, hidden_dim) 60 | self.layer_norm = nn.LayerNorm(hidden_dim, eps=layer_norm_eps) 61 | self.dropout = nn.Dropout(hidden_dropout) 62 | 63 | def forward(self, input_ids, token_type_ids=None, position_ids=None): 64 | """ 65 | Return BERT embeddings with do operation. 66 | 67 | Args: 68 | input_ids (torch.LongTensor): Batch sentence inputs with shape (batch_size, seq_len). 69 | token_type_ids (torch.LongTensor): Batch sentence token types with shape (batch_size, seq_len). 70 | position_ids (torch.LongTensor): Batch sentence token positions with shape (batch_size, seq_len). 71 | """ 72 | seq_len = input_ids.shape[1] 73 | 74 | if position_ids is None: 75 | position_ids = torch.arange(seq_len, dtype=torch.long, device=input_ids.device) 76 | position_ids = position_ids.unsqueeze(0).expand(input_ids.shape) 77 | if token_type_ids is None: 78 | token_type_ids = torch.zeros(input_ids.shape, dtype=torch.long, device=input_ids.device) 79 | 80 | token_embeds = self.token_embeddings(input_ids) 81 | position_embeddings = self.position_embeddings(position_ids) 82 | token_type_embeddings = self.token_type_embeddings(token_type_ids) 83 | 84 | embeddings = token_embeds + position_embeddings + token_type_embeddings 85 | embeddings = self.layer_norm(embeddings) 86 | embeddings = self.dropout(embeddings) 87 | embeddings[input_ids == self.empty_id] = 0.0 88 | 89 | return embeddings 90 | 91 | 92 | class BERTSelfAttention(nn.Module): 93 | """ 94 | BERTSelfAttention apllies multi-head attention to get a context-aware token representations. 95 | 96 | Args: 97 | hidden_dim (int): The dimension of hidden states. 98 | n_heads (int): The number of attention heads. 99 | attention_dropout (float): Attention dropout probability. 100 | """ 101 | def __init__(self, hidden_dim: int, n_heads: int, attention_dropout: float): 102 | super(BERTSelfAttention, self).__init__() 103 | assert hidden_dim % n_heads == 0 104 | self.n_heads = n_heads 105 | self.head_dim = hidden_dim // n_heads 106 | 107 | self.query = nn.Linear(hidden_dim, hidden_dim) 108 | self.key = nn.Linear(hidden_dim, hidden_dim) 109 | self.value = nn.Linear(hidden_dim, hidden_dim) 110 | self.dropout = nn.Dropout(attention_dropout) 111 | 112 | def forward(self, hidden_states, mask=None): 113 | """ 114 | Return a context-aware token representations. 115 | 116 | Args: 117 | hidden_states (torch.FloatTensor): Batch hidden states with shape (batch_size, seq_len, hidden_dim). 118 | mask (torch.FloatTensor): Batch masks with shape (batch_size, seq_len. hidden_dim). 119 | """ 120 | batch_size, seq_len, hidden_dim = hidden_states.shape 121 | attention_shape = (batch_size, seq_len, self.n_heads, self.head_dim) 122 | query = self.query(hidden_states).view(attention_shape).permute(0, 2, 1, 3) 123 | key = self.key(hidden_states).view(attention_shape).permute(0, 2, 1, 3) 124 | value = self.value(hidden_states).view(attention_shape).permute(0, 2, 1, 3) 125 | 126 | attention_scores = torch.matmul(query, key.transpose(-1, -2)) 127 | attention_scores = attention_scores / math.sqrt(self.head_dim) 128 | if mask is not None: 129 | attention_scores = attention_scores + mask 130 | attention_probs = nn.Softmax(dim=-1)(attention_scores) 131 | attention_probs = self.dropout(attention_probs) 132 | context = torch.matmul(attention_probs, value).permute(0, 2, 1, 3).contiguous() 133 | context = context.view(batch_size, seq_len, hidden_dim) 134 | 135 | outputs = (context, attention_probs) 136 | 137 | return outputs 138 | 139 | 140 | class BERTSelfOutput(nn.Module): 141 | """ 142 | BERTSelfOutput processes the attention outputs. 143 | 144 | Args: 145 | hidden_dim (int): The dimension of hidden states. 146 | layer_norm_eps (float): Layer normalization epsilon. 147 | hidden_dropout (float): Hidden dropout probability. 148 | """ 149 | 150 | def __init__(self, hidden_dim: int, layer_norm_eps: float, hidden_dropout: float): 151 | super(BERTSelfOutput, self).__init__() 152 | self.dense = nn.Linear(hidden_dim, hidden_dim) 153 | self.layer_norm = nn.LayerNorm(hidden_dim, eps=layer_norm_eps) 154 | self.dropout = nn.Dropout(hidden_dropout) 155 | 156 | def forward(self, hidden_states, input_tensor): 157 | hidden_states = self.dense(hidden_states) 158 | hidden_states = self.dropout(hidden_states) 159 | hidden_states = self.layer_norm(hidden_states + input_tensor) 160 | 161 | return hidden_states 162 | 163 | 164 | class BERTAttention(nn.Module): 165 | """ 166 | BERTAttention applies attention mechanism to get context-aware representations. 167 | 168 | Args: 169 | hidden_dim (int): The dimension of hidden states. 170 | n_heads (int): The number of attention heads. 171 | attention_dropout (float): Attention dropout probability. 172 | layer_norm_eps (float): Layer normalization epsilon. 173 | hidden_dropout (float): Hidden dropout probability. 174 | """ 175 | 176 | def __init__(self, hidden_dim: int, n_heads: int, attention_dropout: float, layer_norm_eps: float, hidden_dropout: float): 177 | super(BERTAttention, self).__init__() 178 | self.self = BERTSelfAttention(hidden_dim, n_heads, attention_dropout) 179 | self.output = BERTSelfOutput(hidden_dim, layer_norm_eps, hidden_dropout) 180 | 181 | def forward(self, hidden_states, mask=None): 182 | """ 183 | Return a context-aware token representations. 184 | 185 | Args: 186 | hidden_states (torch.FloatTensor): Batch hidden states with shape (batch_size, seq_len, hidden_dim). 187 | mask (torch.FloatTensor): Batch masks with shape (batch_size, seq_len. hidden_dim). 188 | """ 189 | self_outputs = self.self(hidden_states, mask) 190 | attention_output = self.output(self_outputs[0], hidden_states) 191 | outputs = (attention_output,) + self_outputs[1:] 192 | 193 | return outputs 194 | 195 | 196 | class BERTIntermediate(nn.Module): 197 | """ 198 | BERTIntermediate transforms the outputs of attention module. 199 | 200 | Args: 201 | hidden_dim (int): The dimension of hidden states. 202 | intermediate_size (int): The size of feedforward intermediate. 203 | """ 204 | 205 | def __init__(self, hidden_dim: int, intermediate_size: int): 206 | super(BERTIntermediate, self).__init__() 207 | self.dense = nn.Linear(hidden_dim, intermediate_size) 208 | 209 | def forward(self, hidden_states): 210 | """ 211 | Return the transformed representations. 212 | 213 | Args: 214 | hidden_states (torch.FloatTensor): Batch hidden states with shape (batch_size, seq_len, hidden_dim). 215 | """ 216 | hidden_states = self.dense(hidden_states) 217 | hidden_states = gelu(hidden_states) 218 | 219 | return hidden_states 220 | 221 | 222 | class BERTOutput(nn.Module): 223 | """ 224 | BERTOutput processes the feedforward outputs. 225 | 226 | Args: 227 | hidden_dim (int): The dimension of hidden states. 228 | intermediate_size (int): The size of feedforward intermediate. 229 | layer_norm_eps (float): Layer normalization epsilon. 230 | hidden_dropout (float): Hidden dropout probability. 231 | """ 232 | 233 | def __init__(self, hidden_dim: int, intermediate_size: int, layer_norm_eps: float, hidden_dropout: float): 234 | super(BERTOutput, self).__init__() 235 | self.dense = nn.Linear(intermediate_size, hidden_dim) 236 | self.layer_norm = nn.LayerNorm(hidden_dim, eps=layer_norm_eps) 237 | self.dropout = nn.Dropout(hidden_dropout) 238 | 239 | def forward(self, hidden_states, input_tensor): 240 | """ 241 | Return a context-aware token representations. 242 | 243 | Args: 244 | hidden_states (torch.FloatTensor): Batch hidden states with shape (batch_size, seq_len, hidden_dim). 245 | input_tensor (torch.FloatTensor): Batch input tensor with shape (batch_size, seq_len. hidden_dim). 246 | """ 247 | hidden_states = self.dense(hidden_states) 248 | hidden_states = self.dropout(hidden_states) 249 | hidden_states = self.layer_norm(hidden_states + input_tensor) 250 | 251 | return hidden_states 252 | 253 | 254 | class BERTLayer(nn.Module): 255 | """ 256 | BERTLayer applies self-attention to token embeddings of a given sentence. 257 | 258 | Args: 259 | hidden_dim (int): The dimension of hidden states. 260 | n_heads (int): The number of attention heads. 261 | intermediate_size (int): The size of feedforward intermediate. 262 | attention_dropout (float): Attention dropout probability. 263 | layer_norm_eps (float): Layer normalization epsilon. 264 | hidden_dropout (float): Hidden dropout probability. 265 | """ 266 | 267 | def __init__( 268 | self, 269 | hidden_dim: int, 270 | n_heads: int, 271 | attention_dropout: float, 272 | layer_norm_eps: float, 273 | hidden_dropout: float, 274 | intermediate_size: int 275 | ): 276 | super(BERTLayer, self).__init__() 277 | self.attention = BERTAttention(hidden_dim, n_heads, attention_dropout, layer_norm_eps, hidden_dropout) 278 | self.intermediate = BERTIntermediate(hidden_dim, intermediate_size) 279 | self.output = BERTOutput(hidden_dim, intermediate_size, layer_norm_eps, hidden_dropout) 280 | 281 | def forward(self, hidden_states, mask=None): 282 | """ 283 | Return a context-aware token representations. 284 | 285 | Args: 286 | hidden_states (torch.FloatTensor): Batch hidden states with shape (batch_size, seq_len, hidden_dim). 287 | mask (torch.FloatTensor): Batch masks with shape (batch_size, seq_len. hidden_dim). 288 | """ 289 | self_attention_outputs = self.attention(hidden_states, mask) 290 | attention_output = self_attention_outputs[0] 291 | outputs = self_attention_outputs[1:] 292 | intermediate_output = self.intermediate(attention_output) 293 | layer_output = self.output(intermediate_output, attention_output) 294 | outputs = (layer_output,) + outputs 295 | 296 | return outputs 297 | 298 | 299 | class BERTEncoder(nn.Module): 300 | """ 301 | BERTEncoder integrates multiple transformer layers into a module for calculating the context-aware 302 | representations. 303 | 304 | Args: 305 | hidden_dim (int): The dimension of hidden states. 306 | n_heads (int): The number of attention heads. 307 | intermediate_size (int): The size of feedforward intermediate. 308 | n_layers (int): The number of transformer layers. 309 | attention_dropout (float): Attention dropout probability. 310 | layer_norm_eps (float): Layer normalization epsilon. 311 | hidden_dropout (float): Hidden dropout probability. 312 | """ 313 | 314 | def __init__( 315 | self, 316 | hidden_dim: int, 317 | n_heads: int, 318 | attention_dropout: float, 319 | layer_norm_eps: float, 320 | hidden_dropout: float, 321 | intermediate_size: int, 322 | n_layers: int 323 | ): 324 | super(BERTEncoder, self).__init__() 325 | self.layer = nn.ModuleList( 326 | [ 327 | BERTLayer(hidden_dim, n_heads, attention_dropout, layer_norm_eps, hidden_dropout, intermediate_size) 328 | for _ in range(n_layers) 329 | ] 330 | ) 331 | 332 | def forward(self, hidden_states, mask=None): 333 | """ 334 | Return a context-aware token representations. 335 | 336 | Args: 337 | hidden_states (torch.FloatTensor): Batch hidden states with shape (batch_size, seq_len, hidden_dim). 338 | mask (torch.FloatTensor): Batch masks with shape (batch_size, seq_len. hidden_dim). 339 | """ 340 | all_hidden_states = () 341 | all_attentions = () 342 | for i, layer_module in enumerate(self.layer): 343 | layer_outputs = layer_module(hidden_states, mask) 344 | hidden_states = layer_outputs[0] 345 | all_attentions = all_attentions + (layer_outputs[1],) 346 | all_hidden_states = all_hidden_states + (hidden_states,) 347 | 348 | outputs = (hidden_states, all_hidden_states, all_attentions) 349 | 350 | return outputs 351 | 352 | 353 | class BERTPooler(nn.Module): 354 | """ 355 | BERTPooler pools the first token output of BERT outputs. 356 | 357 | Args: 358 | hidden_dim (int): The dimension of hidden states. 359 | """ 360 | 361 | def __init__(self, hidden_dim: int): 362 | super(BERTPooler, self).__init__() 363 | self.dense = nn.Linear(hidden_dim, hidden_dim) 364 | self.activation = nn.Tanh() 365 | 366 | def forward(self, hidden_states): 367 | """ 368 | Return the pooled outputs. 369 | 370 | Args: 371 | hidden_states (torch.FloatTensor): Batch hidden states with shape (batch_size, seq_len, hidden_dim). 372 | """ 373 | first_token_tensor = hidden_states[:, 0] 374 | pooled_output = self.dense(first_token_tensor) 375 | pooled_output = self.activation(pooled_output) 376 | 377 | return pooled_output 378 | 379 | 380 | class BERTModel(nn.Module): 381 | """ 382 | The implementation of the paper "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding". 383 | 384 | Args: 385 | n_tokens (int): The total number of tokens. 386 | hidden_dim (int): The dimension of hidden states. 387 | max_seq_len (int): The maximum length of sentences in a batch. 388 | n_token_types (int): The number of total token types. 389 | empty_id (int): The ID of the special token [EMPTY], we will conduct a DO operation on empty id.. 390 | padding_id (int): The ID of the special token [PAD]. 391 | n_heads (int): The number of attention heads. 392 | intermediate_size (int): The size of feedforward intermediate. 393 | n_layers (int): The number of transformer layers. 394 | attention_dropout (float): Attention dropout probability. 395 | layer_norm_eps (float): Layer normalization epsilon. 396 | hidden_dropout (float): Hidden dropout probability. 397 | """ 398 | 399 | def __init__( 400 | self, 401 | n_tokens: int, 402 | hidden_dim: int, 403 | max_seq_len: int, 404 | n_token_types: int, 405 | empty_id: int, 406 | padding_id: int, 407 | n_heads: int, 408 | intermediate_size: int, 409 | n_layers: int, 410 | attention_dropout: float, 411 | layer_norm_eps: float, 412 | hidden_dropout: float 413 | ): 414 | super(BERTModel, self).__init__() 415 | self.embeddings = BERTEmbeddings( 416 | n_tokens, hidden_dim, max_seq_len, n_token_types, empty_id, padding_id, hidden_dropout, layer_norm_eps 417 | ) 418 | self.encoder = BERTEncoder( 419 | hidden_dim, n_heads, attention_dropout, layer_norm_eps, hidden_dropout, intermediate_size, n_layers 420 | ) 421 | self.pooler = BERTPooler(hidden_dim) 422 | 423 | def forward(self, input_ids, mask=None, token_type_ids=None, position_ids=None): 424 | """ 425 | Return BERT representations. 426 | 427 | Args: 428 | input_ids (torch.LongTensor): Inputs with shape (batch_size, seq_len). 429 | mask (torch.LongTensor): Mask with shape (batch_size, seq_len). 430 | token_type_ids (torch.LongTensor): Token types with shape (batch_size, seq_len). 431 | position_ids (torch.LongTensor): Token positions with shape (batch_size, seq_len). 432 | """ 433 | if mask is None: 434 | mask = torch.ones(input_ids.size(), device=input_ids.device) 435 | if mask.dim() == 3: 436 | mask = mask[:, None, :, :] 437 | elif mask.dim() == 2: 438 | mask = mask[:, None, None, :] 439 | else: 440 | raise ValueError( 441 | "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format( 442 | input_ids.size(), mask.shape 443 | ) 444 | ) 445 | # (batch_size, n_heads, seq_len, head_dim) 446 | mask = (1.0 - mask) * -10000.0 447 | 448 | embedding_output = self.embeddings(input_ids, position_ids, token_type_ids) 449 | encoder_outputs = self.encoder(embedding_output, mask) 450 | pooled_output = self.pooler(encoder_outputs[0]) 451 | outputs = (pooled_output,) + encoder_outputs 452 | 453 | return outputs 454 | 455 | 456 | class BERTTagger(nn.Module): 457 | """ 458 | A BERT-based Tagger for the task sequence labeling. 459 | 460 | Args: 461 | n_tags (int): The number of tags. 462 | token_embeddings (OrderedDict): The pretrained BERTModel weights. 463 | """ 464 | def __init__( 465 | self, 466 | n_tokens: int, 467 | hidden_dim: int, 468 | max_seq_len: int, 469 | n_token_types: int, 470 | empty_id: int, 471 | padding_id: int, 472 | n_heads: int, 473 | intermediate_size: int, 474 | n_layers: int, 475 | attention_dropout: float, 476 | layer_norm_eps: float, 477 | hidden_dropout: float, 478 | n_tags: int, 479 | token_embeddings: OrderedDict = None 480 | ): 481 | super(BERTTagger, self).__init__() 482 | self.bert = BERTModel( 483 | n_tokens, hidden_dim, max_seq_len, n_token_types, empty_id, padding_id, n_heads, 484 | intermediate_size, n_layers, attention_dropout, layer_norm_eps, hidden_dropout 485 | ) 486 | if token_embeddings is not None: 487 | self.bert.load_state_dict(token_embeddings) 488 | self.dropout = nn.Dropout(p=hidden_dropout) 489 | self.tagger = nn.Sequential(nn.Linear(hidden_dim, hidden_dim*2), nn.PReLU(), nn.Linear(hidden_dim*2, n_tags)) 490 | 491 | def forward(self, inputs, mask, *args): 492 | """ 493 | Compute tagging logits by BERTTagger. 494 | 495 | Args: 496 | inputs (torch.LongTensor): Batch sequence inputs with expected shape (batch_size, seq_len). 497 | mask (torch.LongTensor): Mask with shape (batch_size, seq_len). 498 | """ 499 | bert_outputs = self.bert(inputs, mask) 500 | outputs = self.dropout(bert_outputs[1]) 501 | logits = self.tagger(outputs) 502 | 503 | return logits 504 | 505 | 506 | class LSTMTagger(nn.Module): 507 | """ 508 | A bidirectional LSTMTagger for the task sequence labeling. 509 | 510 | Args: 511 | n_tokens (int): The number of total tokens. 512 | token_dim (int): The dimension of token embedding. 513 | hidden_dim (int): The dimension of hidden states. 514 | n_layers (int): The number of LSTM layers. 515 | n_tags (int): The number of tags. 516 | empty_id (int): The ID of the special token [EMPTY], we will conduct a DO operation on empty id. 517 | dropout (float): Dropout probability. 518 | token_embeddings (FloatTensor): Token embeddings. 519 | """ 520 | 521 | def __init__( 522 | self, 523 | n_tokens: int, 524 | token_dim: int, 525 | hidden_dim: int, 526 | n_layers: int, 527 | n_tags: int, 528 | empty_id: int, 529 | dropout: float, 530 | token_embeddings: FloatTensor = None 531 | ): 532 | super(LSTMTagger, self).__init__() 533 | self.empty_id = empty_id 534 | if token_embeddings is None: 535 | self.embedding = nn.Embedding(n_tokens, token_dim) 536 | else: 537 | self.embedding = nn.Embedding.from_pretrained(token_embeddings) 538 | self.rnn = nn.LSTM(token_dim, hidden_dim, n_layers, batch_first=True, bidirectional=True) 539 | self.dropout = nn.Dropout(p=dropout) 540 | self.tagger = nn.Sequential(nn.Linear(hidden_dim*2, hidden_dim*2), nn.PReLU(), nn.Linear(hidden_dim*2, n_tags)) 541 | 542 | def forward(self, inputs, *args): 543 | """ 544 | Compute tagging logits by LSTMTagger. 545 | 546 | Args: 547 | inputs (torch.LongTensor): Batch sequence inputs with expected shape (batch_size, seq_len). 548 | """ 549 | embeds = self.embedding(inputs) 550 | embeds[inputs == self.empty_id] = 0.0 551 | self.rnn.flatten_parameters() 552 | rnn_output, _ = self.rnn(embeds) 553 | outputs = self.dropout(rnn_output) 554 | logits = self.tagger(outputs) 555 | 556 | return logits 557 | --------------------------------------------------------------------------------