├── saved_models └── .gitkeep ├── pretrained_model └── .gitkeep ├── imgs └── systemdiagram-q.png ├── config.json ├── run_reg.py ├── log └── mmregression.log ├── utils.py ├── README.md ├── models.py └── LICENSE /saved_models/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /pretrained_model/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /imgs/systemdiagram-q.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GeekDream-x/SemEval2022-Task8-TonyX/HEAD/imgs/systemdiagram-q.png -------------------------------------------------------------------------------- /config.json: -------------------------------------------------------------------------------- 1 | { 2 | "learning_rate":5e-6, 3 | "epoch":2, 4 | "gradient_acc":8, 5 | "batch_size":4, 6 | "max_len":512, 7 | "seed":8824, 8 | "weight_decay":1e-4, 9 | "warmup_rate":0.1, 10 | "overall_weight":0.75, 11 | "rdrop_weight":0.1, 12 | "model_pretrain_dir":"pretrained_models/xlmr-large", 13 | "model_save_path":"saved_models/best_mmregressor.pth", 14 | "training_set_path":"data/training_set.csv", 15 | "testing_set_path":"data/testing_set.csv", 16 | "log_path":"log/mmregression.log" 17 | } -------------------------------------------------------------------------------- /run_reg.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import argparse 3 | import transformers 4 | from utils import load 5 | from models import Reg_FT_Configer, Reg_Trainer 6 | 7 | transformers.logging.set_verbosity_error() 8 | 9 | 10 | def main(): 11 | 12 | parser = argparse.ArgumentParser(description="Reg-Argparser") 13 | parser.add_argument('--params', type=str, required=True, help="JSON dict of parameters for model training.") 14 | args = parser.parse_args() 15 | 16 | params = load(args.params) 17 | 18 | logging.basicConfig(filename=params['log_path'], filemode="w", 19 | format="%(asctime)s %(name)s:%(levelname)s:%(message)s", 20 | datefmt="%d-%m-%Y %H:%M:%S", 21 | level=logging.DEBUG) 22 | 23 | logging.info(f"Params:\n{params}") 24 | 25 | 26 | config = Reg_FT_Configer(params) 27 | trainer = Reg_Trainer(config) 28 | trainer.run_finetune() 29 | 30 | if __name__ == "__main__": 31 | main() 32 | -------------------------------------------------------------------------------- /log/mmregression.log: -------------------------------------------------------------------------------- 1 | 10-04-2022 16:52:04 root:INFO:Params: 2 | {'learning_rate': 5e-06, 'epoch': 2, 'gradient_acc': 8, 'batch_size': 4, 'max_len': 512, 'seed': 8824, 'weight_decay': 0.0001, 'warmup_rate': 0.1, 'model_pretrain_dir': 'pretrained_models/xlmr-large', 'model_save_dir': 'saved_models/', 'model_save_path': 'saved_models/best_mmregressor.pth', 'training_set_path': 'data/training_set.csv', 'testing_set_path': 'data/testing_set.csv', 'log_path': 'log/mmregression.log', 'overall_weight': 0.75, 'rdrop_weight': 0.1} 3 | 10-04-2022 16:52:23 root:INFO:—————————————————————— Epoch 1 —————————————————————— 4 | 10-04-2022 16:52:40 root:INFO:Epoch 01 | Step 032/320 | Loss 0.9602 | Time 16.87 5 | 10-04-2022 16:52:56 root:INFO:Epoch 01 | Step 064/320 | Loss 0.7350 | Time 32.93 6 | 10-04-2022 16:53:12 root:INFO:Epoch 01 | Step 096/320 | Loss 0.5926 | Time 48.98 7 | 10-04-2022 16:53:28 root:INFO:Epoch 01 | Step 128/320 | Loss 0.5024 | Time 65.02 8 | 10-04-2022 16:53:44 root:INFO:Epoch 01 | Step 160/320 | Loss 0.4448 | Time 81.08 9 | 10-04-2022 16:54:00 root:INFO:Epoch 01 | Step 192/320 | Loss 0.4005 | Time 97.15 10 | 10-04-2022 16:54:16 root:INFO:Epoch 01 | Step 224/320 | Loss 0.3687 | Time 113.24 11 | 10-04-2022 16:54:32 root:INFO:Epoch 01 | Step 256/320 | Loss 0.3424 | Time 129.35 12 | 10-04-2022 16:54:48 root:INFO:Epoch 01 | Step 288/320 | Loss 0.3232 | Time 145.46 13 | 10-04-2022 16:55:04 root:INFO:Epoch 01 | Step 320/320 | Loss 0.3069 | Time 161.59 14 | 10-04-2022 16:55:04 root:INFO:Start evaluating! 15 | 10-04-2022 16:55:52 root:INFO:Current dev pearson is 0.3607, best pearson is 0.3607 16 | 10-04-2022 16:55:52 root:INFO:Time costed : 208.889s 17 | 18 | 10-04-2022 16:55:52 root:INFO:—————————————————————— Epoch 2 —————————————————————— 19 | 10-04-2022 16:56:07 root:INFO:Epoch 02 | Step 032/320 | Loss 0.1643 | Time 15.14 20 | 10-04-2022 16:56:22 root:INFO:Epoch 02 | Step 064/320 | Loss 0.1508 | Time 30.29 21 | 10-04-2022 16:56:37 root:INFO:Epoch 02 | Step 096/320 | Loss 0.1555 | Time 45.44 22 | 10-04-2022 16:56:52 root:INFO:Epoch 02 | Step 128/320 | Loss 0.1529 | Time 60.59 23 | 10-04-2022 16:57:07 root:INFO:Epoch 02 | Step 160/320 | Loss 0.1521 | Time 75.72 24 | 10-04-2022 16:57:22 root:INFO:Epoch 02 | Step 192/320 | Loss 0.1507 | Time 90.87 25 | 10-04-2022 16:57:38 root:INFO:Epoch 02 | Step 224/320 | Loss 0.1497 | Time 106.02 26 | 10-04-2022 16:57:53 root:INFO:Epoch 02 | Step 256/320 | Loss 0.1486 | Time 121.17 27 | 10-04-2022 16:58:08 root:INFO:Epoch 02 | Step 288/320 | Loss 0.1492 | Time 136.32 28 | 10-04-2022 16:58:23 root:INFO:Epoch 02 | Step 320/320 | Loss 0.1484 | Time 151.47 29 | 10-04-2022 16:58:23 root:INFO:Start evaluating! 30 | 10-04-2022 16:59:10 root:INFO:Current dev pearson is 0.4619, best pearson is 0.4619 31 | 10-04-2022 16:59:10 root:INFO:Time costed : 198.82s 32 | 33 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import random 2 | import os 3 | import numpy as np 4 | import torch 5 | import json 6 | from tqdm import tqdm 7 | import pandas as pd 8 | from transformers import XLMRobertaTokenizer 9 | 10 | tokenizer = XLMRobertaTokenizer.from_pretrained("pretrained_model") 11 | 12 | 13 | def set_seed(seed=56): 14 | random.seed(seed) 15 | os.environ['PYTHONHASHSEED']=str(seed) 16 | np.random.seed(seed) 17 | torch.manual_seed(seed) 18 | torch.cuda.manual_seed(seed) 19 | torch.cuda.manual_seed_all(seed) 20 | 21 | def load(json_file): 22 | with open(json_file, 'r') as f: 23 | return json.load(f) 24 | 25 | # truncate text from either head or tail part 26 | def trunc_text(text, trunc_pos, length): 27 | 28 | text_ids = tokenizer.encode(text)[1:-1] 29 | 30 | if trunc_pos == 'head': 31 | text_trunc_ids = text_ids[:length] 32 | elif trunc_pos == 'tail': 33 | text_trunc_ids = text_ids[-length:] 34 | 35 | text_trunc_tokens = tokenizer.convert_ids_to_tokens(text_trunc_ids) 36 | text_trunc_back_sent = ''.join([x.replace('▁', ' ') for x in text_trunc_tokens])[:-1] 37 | 38 | return text_trunc_back_sent 39 | 40 | # extract the title and text parts of a single news by id 41 | def extract_news_byID(raw_data_root_dir, id: str): 42 | 43 | file_path = f"{raw_data_root_dir}/{id[-2:]}/{id}.json" 44 | 45 | if os.path.exists(file_path): 46 | 47 | with open(file_path, 'r', encoding='utf-8') as f: 48 | json_file = json.load(f) 49 | news_text = f"{json_file['title']} {json_file['text']}" 50 | news_truncated_text = f"{trunc_text(news_text, 'head', 200)} {trunc_text(news_text, 'tail', 56)}" 51 | return news_truncated_text 52 | else: 53 | return None 54 | 55 | 56 | def extract_data_from_raw(data_link_filepath, raw_data_root_dir, manual_crawl_file, dataset_save_filepath): 57 | 58 | # read the news missed by the tool provided by the organizers and crawled manually 59 | with open(manual_crawl_file, 'r', encoding='utf-8') as f: 60 | manual_crawl_dict = json.load(f) 61 | 62 | final_data = [] 63 | final_columns = ['pair_id', 'lang1', 'lang2', 'text1', 'text2', 'Geography', 'Entities', 'Time', 'Narrative', 'Overall', 'Style', 'Tone'] 64 | 65 | for _, row in tqdm(pd.read_csv(data_link_filepath).iterrows()): 66 | 67 | id1, id2 = row['pair_id'].strip().split('_') 68 | text1, text2 = extract_news_byID(raw_data_root_dir, id1), extract_news_byID(raw_data_root_dir, id2) 69 | 70 | if not text1: text1 = manual_crawl_dict[f"{row['pair_id']}"]['text1'] 71 | if not text2: text2 = manual_crawl_dict[f"{row['pair_id']}"]['text2'] 72 | 73 | cur_data = [row['pair_id'], row['lang1'], row['lang2'], text1, text2, row['Geography'], row['Entities'], row['Time'], row['Narrative'], row['Overall'], row['Style'], row['Tone']] 74 | final_data.append(cur_data) 75 | 76 | pd.DataFrame(final_data, columns=final_columns).to_csv(dataset_save_filepath) 77 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HFL at SemEval-2022 Task 8: A Linguistics-inspired Regression Model with Data Augmentation for Multilingual News Similarity 2 | 3 | 4 | # Introduction 5 | 6 | Here, we provide the implementation of our winning system in Semeval-2022 Task8 —— Multilingual News Article Similarity. This is a competition about assessing the similarity of multilingual and crosslingual news articles which covers 18 language pairs. 7 | 8 | We proposed a linguistics-inspired model trained with a few task-specific strategies. The main techniques of our system are: 1) data augmentation, 2) multi-label loss, 3) adapted R-Drop, 4) samples reconstruction with the head-tail combination. We also present a brief analysis of some negative methods like two-tower architecture in our paper. Our system ranked 1st on the leaderboard while achieving a Pearson's Correlation Coefficient of 0.818 on the official evaluation set. 9 | 10 | For more imformation about the contest, please refer to the official site [Semeval2022-Task8](https://competitions.codalab.org/competitions/33835). 11 | 12 | For more detailed description of our system, please refer to our paper [HFL at SemEval-2022 Task 8: A Linguistics-inspired Regression Model with Data Augmentation for Multilingual News Similarity](https://aclanthology.org/2022.semeval-1.157/). 13 | 14 | Citation: 15 | ``` 16 | @inproceedings{xu-etal-2022-hfl, 17 | title = "{HFL} at {S}em{E}val-2022 Task 8: A Linguistics-inspired Regression Model with Data Augmentation for Multilingual News Similarity", 18 | author = "Xu, Zihang and 19 | Yang, Ziqing and 20 | Cui, Yiming and 21 | Chen, Zhigang", 22 | booktitle = "Proceedings of the 16th International Workshop on Semantic Evaluation (SemEval-2022)", 23 | month = jul, 24 | year = "2022", 25 | address = "Seattle, United States", 26 | publisher = "Association for Computational Linguistics", 27 | url = "https://aclanthology.org/2022.semeval-1.157", 28 | pages = "1114--1120", 29 | abstract = "This paper describes our system designed for SemEval-2022 Task 8: Multilingual News Article Similarity. We proposed a linguistics-inspired model trained with a few task-specific strategies. The main techniques of our system are: 1) data augmentation, 2) multi-label loss, 3) adapted R-Drop, 4) samples reconstruction with the head-tail combination. We also present a brief analysis of some negative methods like two-tower architecture. Our system ranked 1st on the leaderboard while achieving a Pearson{'}s Correlation Coefficient of 0.818 on the official evaluation set.", 30 | } 31 | 32 | ``` 33 | 34 | # System Overview 35 | 36 | ### System Structure 37 | 38 | 39 |

40 |
41 | 42 |
43 |

44 | 45 | 46 | ### System Performance 47 | 48 | Finally, our system got 0.818 on the evaluation set according to the official scoring system and ranked 1st out of more than 30 teams. The performance of our system on individual language pairs on the official evaluation set is as displayed below: 49 | 50 | | **Language** | en | de | es | pl | tr | ar | ru | zh | fr | it | esen | deen | plen | zhen | esit | defr | depl | frpl | 51 | | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | 52 | | **Pearson's CC** | 87.19 | 84.96 | 86.64 | 75.29 | 83.54 | 79.42 | 78.47 | 76.78 | 86.53 | 86.17 | 86.35 | 85.98 | 88.18 | 81.00 | 81.97 | 68.89 | 64.31 | 82.68 | 53 | 54 | # Project Structure 55 | 56 | - `data/` 57 | - `training_set.csv`: an example of training set 58 | - `testing_set.csv`: an example of testing set 59 | - `log/` 60 | - `mmregression.log`: an example of training log 61 | - `pretrained_model/`: pretrained model files like `pytorch_model.bin` and `config.json` 62 | - `saved_models`: models saved during training 63 | - `config.json`: configuration file for training parameters 64 | - `models.py`: main classes 65 | - `run_reg.py`: project entry 66 | - `utils.py`: helpful functions for data processing 67 | 68 | 69 | # Preparation 70 | 71 | ### Model 72 | 73 | In this project, the foundation model we choose is XLM-RoBERTa and it is easily accessible on [Hugging Face](https://huggingface.co/). 74 | 75 | ### Data 76 | 77 | 1. Download dataset files where the news is provided via links. 78 | 79 | These files are provided on the official website of this [task](https://competitions.codalab.org/competitions/33835#learn_the_details-timetable). 80 | 81 | 2. Crawl the news based on the files downloaded. 82 | 83 | The task organizers offered [a python script](https://github.com/euagendas/semeval_8_2022_ia_downloader) that helps with this. 84 | 85 | 3. Make the training and testing datasets. 86 | 87 | With the help of the functions provided in `utils.py`, you can easily transfer the data crawled into datasets for training. As for the dataset format, you can refer to the files in `data/`. 88 | 89 | 4. Clean the texts. 90 | 91 | Feel free to customize your own function to clean the data like removing the URLs in the texts. 92 | 93 | 5. Combine the head and tail parts. 94 | 95 | For the detailed description of this operation, please read our [paper](https://arxiv.org/abs/2204.04844). Helpful functions are also provided in `utils.py`. 96 | 97 | ### Requirements 98 | 99 | Main tools and libraries: 100 | 101 | - NumPy: 1.21.2 102 | - pandas: 1.2.4 103 | - Python: 3.7.10 104 | - PyTorch: 1.9.0 105 | - Transformers: 4.5.1 106 | 107 | 108 | # Training 109 | 110 | ### Parameters Configuration 111 | 112 | Customize the training parameters in `config.json` as you need. This is a Json dictionary like: 113 | 114 | ```json 115 | { 116 | "learning_rate":5e-6, 117 | "epoch":2, 118 | "gradient_acc":8, 119 | "batch_size":4, 120 | "max_len":512, 121 | "seed":8824, 122 | "weight_decay":1e-4, 123 | "warmup_rate":0.1, 124 | "overall_weight":0.75, 125 | "rdrop_weight":0.1, 126 | "model_pretrain_dir":"pretrained_models/xlmr-large", 127 | "model_save_path":"saved_models/best_mmregressor.pth", 128 | "training_set_path":"data/training_set.csv", 129 | "testing_set_path":"data/testing_set.csv", 130 | "log_path":"log/mmregression.log" 131 | } 132 | ``` 133 | 134 | ### Run command 135 | 136 | ```shell 137 | python run_reg.py --params config.json 138 | ``` 139 | After running this program, you could check the log messages and model testing results in `log/mmregression.log`. 140 | 141 | 142 | 143 | # Notice 144 | 145 | For copyright reasons, the complete datasets including the augmented one will not be provided here but the method of generating it has been introduced in our paper detailedly. 146 | 147 | -------------------------------------------------------------------------------- /models.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import time 3 | import logging 4 | import numpy as np 5 | import torch 6 | import torch.nn as nn 7 | from torch.utils.data import TensorDataset, DataLoader 8 | from transformers import XLMRobertaConfig, XLMRobertaModel, XLMRobertaTokenizer, AdamW, get_cosine_schedule_with_warmup 9 | 10 | from utils import set_seed 11 | 12 | class MMRegressor(nn.Module): 13 | 14 | def __init__(self, model_path): 15 | 16 | super(MMRegressor, self).__init__() 17 | self.config = XLMRobertaConfig.from_pretrained(model_path) 18 | self.reg_model = XLMRobertaModel.from_pretrained(model_path) 19 | 20 | self.fc1 = nn.Linear(self.config.hidden_size, 512) 21 | self.fc2 = nn.Linear(512, 7) 22 | self.activation = nn.GELU() 23 | 24 | def forward(self, input_ids, attention_mask): 25 | 26 | output1 = self.reg_model(input_ids, attention_mask)[1] 27 | logits1 = self.fc2(self.activation(self.fc1(output1))) 28 | 29 | output2 = self.reg_model(input_ids, attention_mask)[1] 30 | logits2 = self.fc2(self.activation(self.fc1(output2))) 31 | 32 | return logits1, logits2 33 | 34 | class Reg_FT_Configer(): 35 | 36 | def __init__(self, params_dict: dict): 37 | 38 | super().__init__() 39 | 40 | self.learning_rate = params_dict['learning_rate'] 41 | self.epoch =params_dict['epoch'] 42 | self.gradient_acc = params_dict['gradient_acc'] 43 | self.batch_size = params_dict['batch_size'] 44 | self.max_len = params_dict['max_len'] 45 | self.model_save_path = params_dict['model_save_path'] 46 | self.warmup_rate = params_dict['warmup_rate'] 47 | self.weight_decay = params_dict['weight_decay'] 48 | self.model_pretrain_dir = params_dict['model_pretrain_dir'] 49 | self.training_set_path = params_dict['training_set_path'] 50 | self.testing_set_path = params_dict['testing_set_path'] 51 | self.seed = params_dict['seed'] 52 | 53 | # weights for the 7 sub-dimensions 54 | self.dims_weights = [params_dict['overall_weight'] if i == 4 else (1-params_dict['overall_weight'])/6 for i in range(7)] 55 | 56 | # weights for forward loss and adapted R-Drop loss 57 | self.losses_weights = { 58 | 'forward_weight': (1-params_dict['rdrop_weight'])/2, 59 | 'rdrop_weight': params_dict['rdrop_weight'] 60 | } 61 | 62 | 63 | class Reg_Trainer(): 64 | 65 | def __init__(self, config: Reg_FT_Configer): 66 | 67 | super().__init__() 68 | 69 | self.config = config 70 | self.device = torch.device("cuda") 71 | self.tokenizer = XLMRobertaTokenizer.from_pretrained(self.config.model_pretrain_dir) 72 | 73 | set_seed(self.config.seed) 74 | 75 | 76 | def dataset(self, data_path): 77 | 78 | input_ids, attention_masks, labels = [], [], [] 79 | 80 | for idx, row in pd.read_csv(data_path).iterrows(): 81 | text1, text2 = row['text1'], row['text2'] 82 | encode_dict = self.tokenizer.__call__(text1,text2, 83 | max_length=self.config.max_len, 84 | padding='max_length', 85 | truncation=True, 86 | add_special_tokens=True 87 | ) 88 | input_ids.append(encode_dict['input_ids']) 89 | attention_masks.append(encode_dict['attention_mask']) 90 | labels.append([float(x) for x in [row['Geography'],row['Entities'],row['Time'],row['Narrative'],row['Overall'],row['Style'],row['Tone']]]) 91 | 92 | return torch.tensor(input_ids), torch.tensor(attention_masks), torch.tensor(labels) 93 | 94 | 95 | def data_loader(self, input_ids, attention_masks, labels): 96 | 97 | data = TensorDataset(input_ids, attention_masks, labels) 98 | loader = DataLoader(data, batch_size=self.config.batch_size, shuffle=True, drop_last=True) 99 | 100 | return loader 101 | 102 | def predict(self, model, data_loader): 103 | 104 | model.eval() 105 | test_pred, test_true = [], [] 106 | with torch.no_grad(): 107 | for idx, (ids, att, y) in enumerate(data_loader): 108 | y_pred = model(ids.to(self.device), att.to(self.device)) 109 | y_pred = torch.squeeze(torch.add(torch.mul(y_pred[0], 0.5), torch.mul(y_pred[1], 0.5))).detach().cpu().numpy().tolist() 110 | y = y.squeeze().cpu().numpy().tolist() 111 | 112 | test_true.extend([x[4] for x in y]) 113 | test_pred.extend([x[4] for x in y_pred]) 114 | 115 | return test_true, test_pred 116 | 117 | 118 | def calculate_weighted_loss(self, y_pred, y, criterion): 119 | 120 | loss = 0.0 121 | for i in range(7): 122 | y_pred_i, y_i = y_pred[:, i], y[:, i] 123 | loss += criterion(y_pred_i, y_i) * self.config.dims_weights[i] 124 | return loss 125 | 126 | 127 | def train(self, model, train_loader, valid_loader, optimizer, schedule): 128 | 129 | best_pearson = 0.0 130 | criterion = nn.MSELoss() 131 | model.train() 132 | 133 | for i in range(self.config.epoch): 134 | start_time = time.time() 135 | train_loss_sum = 0.0 136 | 137 | logging.info(f"—————————————————————— Epoch {i+1} ——————————————————————") 138 | 139 | for idx, (ids, att, y) in enumerate(train_loader): 140 | 141 | ids, att, y = ids.to(self.device), att.to(self.device), y.to(self.device) 142 | y_pred1, y_pred2 = model(ids, att) 143 | y_pred1, y_pred2, y = torch.squeeze(y_pred1), torch.squeeze(y_pred2), torch.squeeze(y) 144 | 145 | loss1 = self.calculate_weighted_loss(y_pred1, y, criterion) * self.config.losses_weights['forward_weight'] 146 | loss2 = self.calculate_weighted_loss(y_pred2, y, criterion) * self.config.losses_weights['forward_weight'] 147 | loss_r = self.calculate_weighted_loss(y_pred1, y_pred2, criterion) * self.config.losses_weights['rdrop_weight'] 148 | loss = (loss1 + loss2 + loss_r) / self.config.gradient_acc 149 | 150 | optimizer.zero_grad() 151 | loss.backward() 152 | optimizer.step() 153 | schedule.step() 154 | train_loss_sum += loss.item() 155 | 156 | if (idx+1) % (len(train_loader) // 10) == 0: 157 | logging.info("Epoch {:02d} | Step {:03d}/{:03d} | Loss {:.4f} | Time {:.2f}".format(i+1, idx+1, len(train_loader), train_loss_sum/(idx+1), time.time()-start_time)) 158 | 159 | 160 | logging.info("Start evaluating!") 161 | dev_true, dev_pred = self.predict(model, valid_loader) 162 | cur_pearson = np.corrcoef(dev_true, dev_pred)[0][1] 163 | 164 | if cur_pearson > best_pearson: 165 | best_pearson = cur_pearson 166 | torch.save(model.state_dict(), self.config.model_save_path) 167 | 168 | logging.info("Current dev pearson is {:.4f}, best pearson is {:.4f}".format(cur_pearson, best_pearson)) 169 | logging.info("Time costed : {}s \n".format(round(time.time() - start_time, 3))) 170 | 171 | 172 | def run_finetune(self): 173 | 174 | train_loader = self.data_loader(*self.dataset(self.config.training_set_path)) 175 | dev_loader = self.data_loader(*self.dataset(self.config.testing_set_path)) 176 | 177 | model = MMRegressor(self.config.model_pretrain_dir).to(self.device) 178 | 179 | for param in model.parameters(): 180 | param.requires_grad = True 181 | 182 | total_steps = len(train_loader) * self.config.epoch 183 | 184 | optimizer = AdamW(params=model.parameters(), 185 | lr=self.config.learning_rate, 186 | weight_decay=self.config.weight_decay) 187 | schedule = get_cosine_schedule_with_warmup(optimizer=optimizer, 188 | num_warmup_steps=self.config.warmup_rate*total_steps, 189 | num_training_steps=total_steps) 190 | 191 | self.train(model, train_loader, dev_loader, optimizer, schedule) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------