SS3M commited on
Commit
1d59734
·
verified ·
1 Parent(s): fd81263

Upload 20_sampled_instead_all_27's state dict

Browse files
.gitattributes CHANGED
@@ -89,3 +89,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
89
  27_top_50_28/logs/27_top_50_28_log_plot.jpg filter=lfs diff=lfs merge=lfs -text
90
  20_entities_pos_weight_0_5_23/logs/20_entities_pos_weight_0_5_23_log_plot.jpg filter=lfs diff=lfs merge=lfs -text
91
  20_entities_top_100_26/logs/20_entities_top_100_26_log_plot.jpg filter=lfs diff=lfs merge=lfs -text
 
 
89
  27_top_50_28/logs/27_top_50_28_log_plot.jpg filter=lfs diff=lfs merge=lfs -text
90
  20_entities_pos_weight_0_5_23/logs/20_entities_pos_weight_0_5_23_log_plot.jpg filter=lfs diff=lfs merge=lfs -text
91
  20_entities_top_100_26/logs/20_entities_top_100_26_log_plot.jpg filter=lfs diff=lfs merge=lfs -text
92
+ 20_sampled_instead_all_27/logs/20_sampled_instead_all_27_log_plot.jpg filter=lfs diff=lfs merge=lfs -text
20_sampled_instead_all_27/20_sampled_instead_all_27.py ADDED
@@ -0,0 +1,2461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # %% [code]
2
+ get_ipython().system('pip install evaluate seqeval underthesea positional-encodings[pytorch] pytorch-crf')
3
+
4
+ # %% [code]
5
+ import warnings
6
+ warnings.filterwarnings('ignore')
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.optim as optim
11
+ from torch.utils.data import Dataset, TensorDataset, DataLoader
12
+ import torch.nn.functional as F
13
+ import albumentations as albu
14
+ from transformers import AutoTokenizer, AutoModel
15
+ import torch.distributed as dist
16
+ from torch.nn.parallel import DistributedDataParallel as DDP
17
+ from positional_encodings.torch_encodings import PositionalEncoding1D
18
+ from torchcrf import CRF
19
+
20
+ from sklearn.metrics import f1_score
21
+ from sklearn.preprocessing import MinMaxScaler, StandardScaler
22
+ from scipy.spatial.transform import Rotation as R
23
+ from sklearn.model_selection import KFold, StratifiedGroupKFold, GroupKFold, StratifiedKFold
24
+ from sklearn.metrics import precision_recall_fscore_support
25
+ from timm.utils import ModelEmaV3
26
+ import timm
27
+
28
+ import os
29
+ import gc
30
+ import json
31
+ from pathlib import Path
32
+ import pickle
33
+ from tqdm.auto import tqdm
34
+ import copy
35
+ import numpy as np
36
+ import pandas as pd
37
+ import polars as pl
38
+ from PIL import Image
39
+ import time
40
+ from tqdm import tqdm
41
+ from matplotlib import pyplot as plt
42
+ import seaborn as sns
43
+ from multiprocessing import Manager as MemoryManager
44
+ from functools import lru_cache
45
+ import shutil
46
+ import glob
47
+ import cv2
48
+ import random
49
+ import re
50
+ import joblib
51
+ import math
52
+ from huggingface_hub import HfApi, snapshot_download
53
+ import evaluate
54
+ from underthesea import word_tokenize as vi_tokenize_tool
55
+ import spacy
56
+ en_tokenize_tool = spacy.load("en_core_web_sm")
57
+ from collections import defaultdict, Counter
58
+
59
+ # %% [code]
60
+ # Global config
61
+ SEEDS = [26092004]
62
+ topk = 1
63
+ nfolds = 5
64
+ only_fold_idx = 0
65
+ test_only = 0
66
+ debug_only = 0
67
+
68
+ # Config thư mục
69
+ dataset = 'kltn/only_entities' # conll003, ontonotes, phoner, vietbio, vietmed, vimed, kltn/only_entities, kltn/raw
70
+ root_dir = f'/kaggle/input/notebooks/sambui22022517/kltn-data/{dataset}' ## Thư mục chứa file train, val, test
71
+ train_dir = f'{root_dir}'
72
+ # val_dir = f'{root_dir}/val'
73
+ test_dir = f'{root_dir}'
74
+
75
+ # Config checkpoints
76
+
77
+ # Config training
78
+ epochs = 18 if not debug_only else 2
79
+ batch_size = 32
80
+ device = "cuda" if torch.cuda.is_available() else "cpu"
81
+ # # Thêm biến toàn cục nào đó vào đây
82
+ repo_name = 'SS3M/kltn-experiments'
83
+ state_dict_save_name = "20_sampled_instead_all_27"
84
+ checkpoints_dir = state_dict_save_name
85
+ pretrained_dir = "/kaggle/working"
86
+ os.makedirs(f'{checkpoints_dir}', exist_ok=True)
87
+
88
+ backbone_model_name = "bert-base-uncased" if dataset in ["conll003", "ontonotes"] else "vinai/phobert-base"
89
+ word_tokenize = lambda text: [token.text for token in en_tokenize_tool(text)] if dataset == dataset in ["conll003", "ontonotes"] else vi_tokenize_tool(text)
90
+ max_len_dict = {
91
+ 'kltn/raw': 256,
92
+ 'kltn/only_entities': 68,
93
+ 'conll003': 46,
94
+ 'ontonotes': 61,
95
+ 'phoner': 68,
96
+ 'vietbio': 125,
97
+ 'vietmed': 36,
98
+ 'vimed': 100,
99
+ }
100
+ zero_entities_rate_dict = {
101
+ 'kltn/raw': 1000,
102
+ 'kltn/only_entities': 0.2,
103
+ 'conll003': 1000, # mean keep all zero-entities samples
104
+ 'ontonotes': 1000,
105
+ 'phoner': 1000,
106
+ 'vietbio': 1000,
107
+ 'vietmed': 1000,
108
+ 'vimed': 1000,
109
+ }
110
+
111
+ max_len = max_len_dict[dataset]
112
+ max_n_parts = 3 if dataset in ['kltn/raw'] else 1
113
+ max_span_len = 10
114
+ zero_entities_rate = zero_entities_rate_dict[dataset]
115
+ topk_spans = 200
116
+
117
+ # Trainer
118
+ trainer_params = {
119
+ "training_time": "00:11:30:00",
120
+ "eval_mode": "max",
121
+ "topk": topk,
122
+ "save_name": state_dict_save_name,
123
+ "save_best": True,
124
+ "save_last": True,
125
+ "device": device,
126
+ "logging": True,
127
+ "logging_file": True,
128
+ "checkpoints_dir": checkpoints_dir,
129
+ "early_stopping": 30,
130
+ "eval_from_ratio": 0.4,
131
+ "eval_every": 1,
132
+ "schedule_in_step": False,
133
+ "use_ema": True,
134
+ "ema_from_ratio": 0.3,
135
+ "ema_decay": 0.9995,
136
+ "max_grad_norm": 200.0,
137
+ "return_best": True,
138
+ "return_last": True,
139
+ }
140
+
141
+ # Memory
142
+ train_memory_params = {
143
+ 'n_spans': topk_spans,
144
+ 'max_len': max_len,
145
+ 'max_n_parts': max_n_parts,
146
+ 'max_span_len': max_span_len,
147
+ 'weight_rate': 3,
148
+ }
149
+ val_memory_params = {
150
+ 'n_spans': topk_spans,
151
+ 'max_len': max_len,
152
+ 'max_n_parts': max_n_parts,
153
+ 'max_span_len': max_span_len,
154
+ 'weight_rate': 3,
155
+ }
156
+
157
+ # Data Loader
158
+ def seed_worker(worker_id):
159
+ worker_seed = torch.initial_seed() % 2**32
160
+ np.random.seed(worker_seed)
161
+ random.seed(worker_seed)
162
+
163
+ train_loader_params = {
164
+ 'batch_size': batch_size,
165
+ 'shuffle': True,
166
+ 'pin_memory':True,
167
+ 'num_workers': 2,
168
+ 'drop_last': False,
169
+ 'worker_init_fn': seed_worker,
170
+ 'persistent_workers': False,
171
+ }
172
+ val_loader_params = {
173
+ 'batch_size': batch_size,
174
+ 'shuffle': False,
175
+ 'pin_memory':True,
176
+ 'num_workers': 1,
177
+ 'drop_last': False,
178
+ 'worker_init_fn': seed_worker,
179
+ 'persistent_workers': False,
180
+ }
181
+
182
+ # Model
183
+ model_params = {
184
+ 'backbone_model_name': backbone_model_name,
185
+ 'max_span_len': max_span_len,
186
+ 'topk_spans': topk_spans,
187
+ 'keep_neighbor': 2,
188
+ }
189
+
190
+ # Loss Func
191
+ loss_func_params = {
192
+ 'lambda_ce': 1.0,
193
+ }
194
+ eval_func_params = {}
195
+
196
+ # Optim
197
+ optim_params = {
198
+ 'name': 'AdamW',
199
+ 'lr': 1e-4,
200
+ 'weight_decay': 1e-4,
201
+ }
202
+ scheduler_params = {
203
+ 'name': 'CosineAnnealingLR',
204
+ 'T_max': 20, # Số epoch để hoàn thành một chu kỳ giảm LR
205
+ 'eta_min': 1e-6 # Learning rate nhỏ nhất trong chu kỳ
206
+ }
207
+
208
+ # %% [code]
209
+ def set_seed(seed=42):
210
+ random.seed(seed)
211
+ np.random.seed(seed)
212
+ torch.manual_seed(seed)
213
+ torch.cuda.manual_seed(seed)
214
+ torch.cuda.manual_seed_all(seed) # if using multi-GPU
215
+ torch.use_deterministic_algorithms(False)
216
+ torch.backends.cudnn.deterministic = True
217
+ torch.backends.cudnn.benchmark = False
218
+ os.environ['PYTHONHASHSEED'] = str(seed)
219
+
220
+ # %% [code]
221
+ class CustomLoss(nn.Module):
222
+ def __init__(self, lambda_ce=1.0):
223
+ super().__init__()
224
+ self.lambda_ce = lambda_ce
225
+
226
+ self.ce = nn.CrossEntropyLoss(
227
+ ignore_index=-100,
228
+ reduction='none'
229
+ )
230
+
231
+ def forward(
232
+ self,
233
+ logits, labels, weights, # weights: (B, N)
234
+ start_logits, start_labels,
235
+ end_logits, end_labels,
236
+ ):
237
+ # =====================================
238
+ # SPAN LOSS
239
+ # =====================================
240
+
241
+ B, N, C = logits.shape
242
+
243
+ flat_logits = logits.reshape(-1, C)
244
+ flat_labels = labels.reshape(-1)
245
+ flat_weights = weights.reshape(-1)
246
+
247
+ valid_mask = flat_labels != -100
248
+
249
+ if valid_mask.any():
250
+ ce_loss = self.ce(flat_logits, flat_labels) # (B*N,)
251
+
252
+ ce_loss = ce_loss[valid_mask]
253
+ valid_weights = flat_weights[valid_mask]
254
+
255
+ loss = (ce_loss * valid_weights).sum() / valid_weights.sum().clamp(min=1e-8)
256
+
257
+ else:
258
+ loss = logits.sum() * 0.0
259
+
260
+ # =====================================
261
+ # START LOSS
262
+ # =====================================
263
+
264
+ B, L, C = start_logits.shape
265
+
266
+ start_logits_flat = start_logits.reshape(B * L, C)
267
+ start_labels_flat = start_labels.reshape(-1)
268
+
269
+ start_loss = self.ce(start_logits_flat, start_labels_flat)
270
+ start_valid = start_labels_flat != -100
271
+
272
+ if start_valid.any():
273
+ start_loss = start_loss[start_valid].mean()
274
+ else:
275
+ start_loss = logits.sum() * 0.0
276
+
277
+ # =====================================
278
+ # END LOSS
279
+ # =====================================
280
+
281
+ end_logits_flat = end_logits.reshape(B * L, C)
282
+ end_labels_flat = end_labels.reshape(-1)
283
+
284
+ end_loss = self.ce(end_logits_flat, end_labels_flat)
285
+ end_valid = end_labels_flat != -100
286
+
287
+ if end_valid.any():
288
+ end_loss = end_loss[end_valid].mean()
289
+ else:
290
+ end_loss = logits.sum() * 0.0
291
+
292
+ return {
293
+ "total": loss + start_loss + end_loss,
294
+ "span_loss": loss,
295
+ "start_loss": start_loss,
296
+ "end_loss": end_loss,
297
+ }
298
+
299
+ # %% [code]
300
+ ## Viết eval_fn vào đây
301
+
302
+ # Bỏ hết eval_fn và trọng số vào đây
303
+ class CustomEvalFn(nn.Module):
304
+ def __init__(self):
305
+ super().__init__()
306
+
307
+ def compute_f1(self, tp, fp, fn):
308
+ precision = tp / (tp + fp + 1e-8)
309
+ recall = tp / (tp + fn + 1e-8)
310
+ f1 = 2 * precision * recall / (precision + recall + 1e-8)
311
+ return precision, recall, f1
312
+
313
+ def forward(self, pred, gold):
314
+ pred_set = set(pred)
315
+ gold_set = set(gold)
316
+
317
+ tp = len(pred_set & gold_set)
318
+ fp = len(pred_set - gold_set)
319
+ fn = len(gold_set - pred_set)
320
+
321
+ precision, recall, f1 = self.compute_f1(tp, fp, fn)
322
+
323
+ return {
324
+ f"precision": precision,
325
+ f"recall": recall,
326
+ f"f1": f1,
327
+ }
328
+
329
+ class SpanErrorAnalyzer:
330
+ def __init__(self, pad_token_id=0):
331
+ self.pad_token_id = pad_token_id
332
+
333
+ # ===== helper =====
334
+ def _to_set(self, data):
335
+ """
336
+ data: list of (b, tuple(ids))
337
+ -> dict[b] = set(tuple(ids))
338
+ """
339
+ res = defaultdict(set)
340
+ for b, ids in data:
341
+ ids = tuple([i for i in ids if i != self.pad_token_id])
342
+ if len(ids) > 0:
343
+ res[b].add(ids)
344
+ return res
345
+
346
+ def _iou(self, a, b):
347
+ """
348
+ a, b: tuple(ids)
349
+ """
350
+ set_a, set_b = set(a), set(b)
351
+ inter = len(set_a & set_b)
352
+ union = len(set_a | set_b)
353
+ if union == 0:
354
+ return 0.0
355
+ return inter / union
356
+
357
+ def _boundary_error(self, pred, gold):
358
+ """
359
+ đo lệch boundary dựa trên overlap prefix/suffix
360
+ """
361
+ # left match
362
+ left = 0
363
+ for i in range(min(len(pred), len(gold))):
364
+ if pred[i] == gold[i]:
365
+ left += 1
366
+ else:
367
+ break
368
+
369
+ # right match
370
+ right = 0
371
+ for i in range(1, min(len(pred), len(gold)) + 1):
372
+ if pred[-i] == gold[-i]:
373
+ right += 1
374
+ else:
375
+ break
376
+
377
+ return {
378
+ "left_match": left,
379
+ "right_match": right,
380
+ "pred_len": len(pred),
381
+ "gold_len": len(gold),
382
+ }
383
+
384
+ # ===== main =====
385
+ def analyze(self, preds, golds):
386
+ pred_map = self._to_set(preds)
387
+ gold_map = self._to_set(golds)
388
+
389
+ all_batches = set(pred_map.keys()) | set(gold_map.keys())
390
+
391
+ stats = Counter()
392
+
393
+ detailed_errors = []
394
+
395
+ for b in all_batches:
396
+ pset = pred_map.get(b, set())
397
+ gset = gold_map.get(b, set())
398
+
399
+ matched_gold = set()
400
+
401
+ # ===== check predictions =====
402
+ for p in pset:
403
+ if p in gset:
404
+ stats["exact_match"] += 1
405
+ matched_gold.add(p)
406
+ else:
407
+ # tìm gold gần nhất
408
+ best_iou = 0
409
+ best_g = None
410
+
411
+ for g in gset:
412
+ iou = self._iou(p, g)
413
+ if iou > best_iou:
414
+ best_iou = iou
415
+ best_g = g
416
+
417
+ if best_iou > 0:
418
+ stats["partial_match"] += 1
419
+
420
+ boundary = self._boundary_error(p, best_g)
421
+
422
+ detailed_errors.append({
423
+ "type": "boundary_error",
424
+ "batch": b,
425
+ "pred": p,
426
+ "gold": best_g,
427
+ "iou": best_iou,
428
+ **boundary
429
+ })
430
+ else:
431
+ if b not in gold_map:
432
+ stats["no_event_sample"] += 1
433
+ err_type = "no_event_sample"
434
+ else:
435
+ stats["completely_wrong"] += 1
436
+ err_type = "completely_wrong"
437
+
438
+ detailed_errors.append({
439
+ "type": err_type,
440
+ "batch": b,
441
+ "pred": p
442
+ })
443
+
444
+ # ===== check missing =====
445
+ for g in gset:
446
+ if g not in matched_gold:
447
+ # check if any pred overlaps
448
+ overlap = any(self._iou(p, g) > 0 for p in pset)
449
+
450
+ if overlap:
451
+ stats["miss_with_overlap"] += 1
452
+ else:
453
+ stats["miss"] += 1
454
+
455
+ detailed_errors.append({
456
+ "type": "miss",
457
+ "batch": b,
458
+ "gold": g
459
+ })
460
+
461
+ return {
462
+ "summary": {
463
+ "exact_match": (stats["exact_match"], stats["exact_match"] / len(preds)),
464
+ "partial_match": (stats["partial_match"], stats["partial_match"] / len(preds)),
465
+ "no_event_sample": (stats["no_event_sample"], stats["no_event_sample"] / len(preds)),
466
+ "completely_wrong": (stats["completely_wrong"], stats["completely_wrong"] / len(preds)),
467
+ "miss": (stats["miss"], stats["miss"] / len(golds)),
468
+ "miss_with_overlap": (stats["miss_with_overlap"], stats["miss_with_overlap"] / len(golds)),
469
+ },
470
+ "details": detailed_errors
471
+ }
472
+
473
+ # %% [code]
474
+ class DataParallelProxy(nn.DataParallel):
475
+
476
+ def __getattr__(self, name):
477
+ try:
478
+ return super().__getattr__(name)
479
+
480
+ except AttributeError:
481
+
482
+ attr = getattr(self.module, name)
483
+
484
+ if callable(attr):
485
+
486
+ def wrapper(*args, **kwargs):
487
+ return self._parallel_apply_method(
488
+ name,
489
+ *args,
490
+ **kwargs
491
+ )
492
+
493
+ return wrapper
494
+
495
+ return attr
496
+
497
+ # =========================================================
498
+ # parallel custom method
499
+ # =========================================================
500
+
501
+ def _parallel_apply_method(self, method_name, *inputs, **kwargs):
502
+
503
+ if not self.device_ids:
504
+ return getattr(self.module, method_name)(*inputs, **kwargs)
505
+
506
+ inputs_scattered, kwargs_scattered = self.scatter(
507
+ inputs,
508
+ kwargs,
509
+ self.device_ids
510
+ )
511
+
512
+ replicas = self.replicate(
513
+ self.module,
514
+ self.device_ids[:len(inputs_scattered)]
515
+ )
516
+
517
+ outputs = self.parallel_apply(
518
+ [getattr(replica, method_name) for replica in replicas],
519
+ inputs_scattered,
520
+ kwargs_scattered
521
+ )
522
+
523
+ return self._custom_gather(
524
+ outputs,
525
+ self.output_device
526
+ )
527
+
528
+ # =========================================================
529
+ # OVERRIDE FORWARD GATHER
530
+ # =========================================================
531
+
532
+ def gather(self, outputs, output_device):
533
+
534
+ return self._custom_gather(
535
+ outputs,
536
+ output_device
537
+ )
538
+
539
+ # =========================================================
540
+ # recursive gather
541
+ # =========================================================
542
+
543
+ def _custom_gather(self, outputs, output_device):
544
+
545
+ first = outputs[0]
546
+
547
+ # =====================================================
548
+ # tensor
549
+ # =====================================================
550
+
551
+ if torch.is_tensor(first):
552
+
553
+ return self._gather_tensor(
554
+ outputs,
555
+ output_device
556
+ )
557
+
558
+ # =====================================================
559
+ # tuple
560
+ # =====================================================
561
+
562
+ if isinstance(first, tuple):
563
+
564
+ return tuple(
565
+ self._custom_gather(
566
+ list(items),
567
+ output_device
568
+ )
569
+ for items in zip(*outputs)
570
+ )
571
+
572
+ # =====================================================
573
+ # list
574
+ # =====================================================
575
+
576
+ if isinstance(first, list):
577
+
578
+ # list[tensor]
579
+ if len(first) > 0 and torch.is_tensor(first[0]):
580
+
581
+ return self._gather_tensor_list(
582
+ outputs,
583
+ output_device
584
+ )
585
+
586
+ merged = []
587
+
588
+ for out in outputs:
589
+ merged.extend(out)
590
+
591
+ return merged
592
+
593
+ # =====================================================
594
+ # dict
595
+ # =====================================================
596
+
597
+ if isinstance(first, dict):
598
+
599
+ return {
600
+ k: self._custom_gather(
601
+ [o[k] for o in outputs],
602
+ output_device
603
+ )
604
+ for k in first.keys()
605
+ }
606
+
607
+ # =====================================================
608
+ # fallback
609
+ # =====================================================
610
+
611
+ return outputs
612
+
613
+ # =========================================================
614
+ # gather tensor with auto pad
615
+ # =========================================================
616
+
617
+ def _gather_tensor(self, tensors, output_device):
618
+
619
+ # move same device first
620
+ tensors = [
621
+ t.to(output_device)
622
+ for t in tensors
623
+ ]
624
+
625
+ # =====================================================
626
+ # fast path
627
+ # =====================================================
628
+
629
+ try:
630
+ return torch.cat(tensors, dim=0)
631
+
632
+ except RuntimeError:
633
+ pass
634
+
635
+ # =====================================================
636
+ # auto max shape
637
+ # =====================================================
638
+
639
+ max_shape = list(tensors[0].shape)
640
+
641
+ for t in tensors[1:]:
642
+
643
+ for d in range(len(max_shape)):
644
+
645
+ max_shape[d] = max(
646
+ max_shape[d],
647
+ t.shape[d]
648
+ )
649
+
650
+ # =====================================================
651
+ # pad tensors
652
+ # =====================================================
653
+
654
+ padded = []
655
+
656
+ for t in tensors:
657
+
658
+ pad = []
659
+
660
+ # reverse order for F.pad
661
+ for d in reversed(range(len(max_shape))):
662
+
663
+ # never pad batch dim
664
+ if d == 0:
665
+ pad.extend([0, 0])
666
+ continue
667
+
668
+ diff = max_shape[d] - t.shape[d]
669
+
670
+ pad.extend([0, diff])
671
+
672
+ t = F.pad(t, pad)
673
+
674
+ padded.append(t)
675
+
676
+ return torch.cat(padded, dim=0)
677
+
678
+ # =========================================================
679
+ # list[tensor]
680
+ # =========================================================
681
+
682
+ def _gather_tensor_list(self, outputs, output_device):
683
+
684
+ merged = []
685
+
686
+ for out in outputs:
687
+ merged.extend(out)
688
+
689
+ return self._gather_tensor(
690
+ merged,
691
+ output_device
692
+ )
693
+
694
+ # %% [code]
695
+ ## Viết cấu trúc model vào đây
696
+ def get_span_reprs(hidden, spans):
697
+ """
698
+ Args:
699
+ hidden: (B, L, H)
700
+ spans: (B, N, 2)
701
+
702
+ Return:
703
+ span_repr: (B, N, 4*H)
704
+ """
705
+
706
+ B, N, _ = spans.shape
707
+ H = hidden.size(-1)
708
+
709
+ batch_idx = torch.arange(B, device=hidden.device).unsqueeze(1)
710
+
711
+ start_idx = spans[..., 0] # (B, N)
712
+ end_idx = spans[..., 1] # (B, N)
713
+ start_h = hidden[batch_idx, start_idx]
714
+ end_h = hidden[batch_idx, end_idx]
715
+
716
+ span_repr = torch.cat(
717
+ [start_h, end_h, end_h - start_h, end_h * start_h],
718
+ dim=-1
719
+ )
720
+
721
+ return span_repr
722
+
723
+ def filter_spans(
724
+ start_logits, # (B, L, C)
725
+ end_logits, # (B, L, C)
726
+ attn_mask, # (B, L)
727
+ max_span_length=10,
728
+ topk_spans=20,
729
+ keep_neighbor=1
730
+ ):
731
+ """
732
+ Return:
733
+ spans: (B, N, 2)
734
+ N là số span lớn nhất trong batch sau expand + remove duplicate.
735
+ Padding bằng (0, 0)
736
+ """
737
+
738
+ device = start_logits.device
739
+ B, L, C = start_logits.shape
740
+
741
+ # Clone
742
+ start_logits = start_logits.detach()
743
+ end_logits = end_logits.detach()
744
+
745
+ # Prob
746
+ prob_s = F.softmax(start_logits, dim=-1) # (B, L, C)
747
+ prob_e = F.softmax(end_logits, dim=-1) # (B, L, C)
748
+
749
+ all_batch_spans = []
750
+
751
+ for b in range(B):
752
+
753
+ valid_len = int(attn_mask[b].sum().item())
754
+
755
+ candidate_spans = []
756
+
757
+ # Enumerate all valid spans
758
+ for s in range(1, valid_len):
759
+
760
+ max_e = min(valid_len - 1, s + max_span_length - 1)
761
+
762
+ for e in range(s, max_e + 1):
763
+
764
+ length = e - s + 1
765
+
766
+ score = (
767
+ (1.0 - prob_s[b, s, 0].item())
768
+ + (1.0 - prob_e[b, e, 0].item())
769
+ - (length / max_span_length)
770
+ )
771
+ candidate_spans.append((score, s, e))
772
+
773
+ # Top-k
774
+ candidate_spans = sorted(
775
+ candidate_spans,
776
+ key=lambda x: x[0],
777
+ reverse=True
778
+ )[:topk_spans]
779
+
780
+ # Expand neighbors
781
+ final_spans = set()
782
+
783
+ for _, s, e in candidate_spans:
784
+
785
+ for ds in range(-keep_neighbor, keep_neighbor + 1):
786
+ for de in range(-keep_neighbor, keep_neighbor + 1):
787
+
788
+ ns = s + ds
789
+ ne = e + de
790
+
791
+ if ns <= 0:
792
+ continue
793
+
794
+ if ne >= valid_len:
795
+ continue
796
+
797
+ if ns > ne:
798
+ continue
799
+
800
+ if (ne - ns + 1) > max_span_length:
801
+ continue
802
+
803
+ final_spans.add((ns, ne))
804
+
805
+ final_spans = sorted(list(final_spans))
806
+
807
+ if len(final_spans) == 0:
808
+ final_spans = [(0, 0)]
809
+
810
+ all_batch_spans.append(final_spans)
811
+
812
+ # Padding
813
+ max_num_spans = max(len(x) for x in all_batch_spans)
814
+
815
+ padded_spans = []
816
+
817
+ for spans in all_batch_spans:
818
+
819
+ pad_size = max_num_spans - len(spans)
820
+
821
+ spans = spans + [(0, 0)] * pad_size
822
+
823
+ padded_spans.append(spans)
824
+
825
+ spans = torch.tensor(
826
+ padded_spans,
827
+ dtype=torch.long,
828
+ device=device
829
+ ) # (B, N, 2)
830
+
831
+ return spans
832
+
833
+ class MLP(nn.Module):
834
+ def __init__(self, in_size, hid_size, out_size):
835
+ super().__init__()
836
+ self.mlp = nn.Sequential(
837
+ nn.Linear(in_size, hid_size),
838
+ nn.ReLU(),
839
+ nn.Linear(hid_size, out_size)
840
+ )
841
+
842
+ def forward(self, x):
843
+ return self.mlp(x)
844
+
845
+ class IEModel(nn.Module):
846
+ def __init__(self, backbone_model_name, num_labels, max_span_len, topk_spans, keep_neighbor):
847
+ super().__init__()
848
+ self.max_span_len = max_span_len
849
+ self.topk_spans = topk_spans
850
+ self.keep_neighbor = keep_neighbor
851
+
852
+ self.encoder = AutoModel.from_pretrained(backbone_model_name)
853
+ hidden_size = self.encoder.config.hidden_size
854
+
855
+ self.start_classifier = MLP(hidden_size, hidden_size, num_labels)
856
+ self.end_classifier = MLP(hidden_size, hidden_size, num_labels)
857
+
858
+ self.span_classifier = MLP(4*hidden_size, hidden_size, num_labels)
859
+
860
+ def encode(self, input_ids, attention_mask):
861
+ B, n_parts, L = input_ids.shape
862
+ input_ids = input_ids.view(-1, L)
863
+ attention_mask = attention_mask.view(-1, L)
864
+
865
+ outputs = self.encoder(input_ids=input_ids, attention_mask=attention_mask)
866
+ hidden_states = outputs.last_hidden_state # B * n_parts, L, H
867
+
868
+ hidden_states = hidden_states.view(B, n_parts, L, -1).reshape(B, n_parts*L, -1) # B, L, H
869
+ attention_mask = attention_mask.view(B, n_parts, L).reshape(B, n_parts*L) # B, L, H
870
+ return hidden_states, attention_mask
871
+
872
+ def get_token_logits(self, hidden_states):
873
+ start_logits = self.start_classifier(hidden_states) # B, N, classes
874
+ end_logits = self.end_classifier(hidden_states) # B, N, classes
875
+ return start_logits, end_logits
876
+
877
+ def get_logits(self, span_reprs):
878
+ logits = self.span_classifier(span_reprs) # N, classes
879
+ return logits
880
+
881
+ def forward(self, input_ids, attention_mask, spans=None):
882
+ hidden_states, attention_mask = self.encode(input_ids, attention_mask)
883
+ start_logits, end_logits = self.get_token_logits(hidden_states)
884
+ if spans is None:
885
+ spans = filter_spans(start_logits, end_logits, attention_mask, self.max_span_len, self.topk_spans, self.keep_neighbor)
886
+ span_reprs = get_span_reprs(hidden_states, spans)
887
+ logits = self.get_logits(span_reprs)
888
+ return start_logits, end_logits, logits, spans
889
+
890
+ def test_model():
891
+ model = DataParallelProxy(IEModel(backbone_model_name, 7, 10, 100, 2)).to(device)
892
+ model.eval()
893
+ total_params = sum(p.numel() for p in model.parameters())
894
+ print(f"Total params: {total_params:,}")
895
+
896
+ vocab_size = model.module.encoder.config.vocab_size
897
+ max_len = model.module.encoder.config.max_position_embeddings
898
+
899
+ bz = 32
900
+ i = torch.randint(0, vocab_size, (bz, 5, 10)).to(device)
901
+ a = torch.ones(bz, 5, 10).to(device)
902
+ s = torch.ones(bz, 3, 2, dtype=torch.long).to(device)
903
+
904
+ with torch.no_grad():
905
+ r = model(i, a)
906
+
907
+ if type(r) == tuple:
908
+ print([r[i].shape if type(r[i]) == type(torch.Tensor()) else len(r[i]) for i in range(len(r))])
909
+ else:
910
+ print(r.shape)
911
+
912
+ test_model()
913
+
914
+ # %% [code]
915
+ def configure_optimizers(network, optim_params, scheduler_params):
916
+ try:
917
+ optim_params = copy.copy(optim_params)
918
+ scheduler_params = copy.copy(scheduler_params)
919
+
920
+ optim_name = optim_params.pop('name')
921
+ scheduler_name = scheduler_params.pop('name')
922
+
923
+ optimizer_cls = globals().get(optim_name) or getattr(optim, optim_name, None)
924
+ scheduler_cls = globals().get(scheduler_name) or getattr(optim.lr_scheduler, scheduler_name, None)
925
+
926
+ if optimizer_cls is None:
927
+ raise ValueError(f"Optimizer '{optim_name}' is not available!")
928
+
929
+ optimizer = optimizer_cls(network.parameters(), **optim_params)
930
+
931
+ scheduler = None
932
+ if scheduler_params and scheduler_cls: # Chỉ tạo scheduler nếu có tham số
933
+ scheduler = scheduler_cls(optimizer, **scheduler_params)
934
+
935
+ return optimizer, scheduler
936
+
937
+ except KeyError as e:
938
+ raise ValueError(f"Missing {e} in config!!")
939
+
940
+ def freeze(self, model):
941
+ model.eval()
942
+ for param in model.parameters():
943
+ param.requires_grad = False
944
+
945
+ def unfreeze(self, model):
946
+ model.train()
947
+ for param in model.parameters():
948
+ param.requires_grad = True
949
+
950
+ def reduce_batch_size(loader, ratio=0.5):
951
+ new_bs = max(1, int(loader.batch_size * ratio))
952
+
953
+ shuffle = isinstance(loader.sampler, RandomSampler)
954
+
955
+ new_loader = DataLoader(
956
+ dataset=loader.dataset,
957
+ batch_size=new_bs,
958
+ shuffle=shuffle,
959
+ sampler=None if shuffle else loader.sampler,
960
+ num_workers=loader.num_workers,
961
+ collate_fn=loader.collate_fn,
962
+ pin_memory=loader.pin_memory,
963
+ drop_last=loader.drop_last,
964
+ timeout=loader.timeout,
965
+ worker_init_fn=loader.worker_init_fn,
966
+ multiprocessing_context=loader.multiprocessing_context,
967
+ generator=loader.generator,
968
+ prefetch_factor=loader.prefetch_factor if loader.num_workers > 0 else None,
969
+ persistent_workers=loader.persistent_workers,
970
+ pin_memory_device=loader.pin_memory_device
971
+ )
972
+
973
+ return new_loader
974
+
975
+ def list_to_tuple(x):
976
+ if isinstance(x, (list, tuple)):
977
+ return tuple(list_to_tuple(i) for i in x)
978
+ return x
979
+
980
+ def fmt(x):
981
+ if isinstance(x, float):
982
+ return round(x, 5)
983
+ if isinstance(x, dict):
984
+ return {k: fmt(v) for k, v in x.items()}
985
+ if isinstance(x, list):
986
+ return [fmt(v) for v in x]
987
+ return x
988
+
989
+ class ModelEmaV3Proxy(ModelEmaV3):
990
+
991
+ def __getattr__(self, name):
992
+
993
+ try:
994
+ return super().__getattr__(name)
995
+
996
+ except AttributeError:
997
+
998
+ # tránh recursion
999
+ module = object.__getattribute__(self, "module")
1000
+
1001
+ return getattr(module, name)
1002
+
1003
+ def align(
1004
+ all_spans, # (B, N, 2)
1005
+ pred_spans, # (B, M, 2)
1006
+ obj, # (B, N)
1007
+ pad_value=0
1008
+ ):
1009
+ """
1010
+ Return:
1011
+ align_obj: (B, M)
1012
+ """
1013
+
1014
+ B, N, _ = all_spans.shape
1015
+ M = pred_spans.shape[1]
1016
+
1017
+ device = all_spans.device
1018
+
1019
+ # =========================================================
1020
+ # Compare spans
1021
+ # =========================================================
1022
+
1023
+ # (B, M, 1, 2)
1024
+ pred_expand = pred_spans.unsqueeze(2)
1025
+
1026
+ # (B, 1, N, 2)
1027
+ all_expand = all_spans.unsqueeze(1)
1028
+
1029
+ # (B, M, N)
1030
+ match = (pred_expand == all_expand).all(dim=-1)
1031
+
1032
+ # =========================================================
1033
+ # Gather obj
1034
+ # =========================================================
1035
+
1036
+ # default = pad_value
1037
+ align_obj = torch.full(
1038
+ (B, M),
1039
+ pad_value,
1040
+ dtype=obj.dtype,
1041
+ device=device
1042
+ )
1043
+
1044
+ # matched index
1045
+ has_match = match.any(dim=-1) # (B, M)
1046
+
1047
+ matched_idx = match.float().argmax(dim=-1) # (B, M)
1048
+
1049
+ gathered = torch.gather(
1050
+ obj,
1051
+ dim=1,
1052
+ index=matched_idx
1053
+ ) # (B, M)
1054
+
1055
+ align_obj[has_match] = gathered[has_match]
1056
+
1057
+ # =========================================================
1058
+ # Force padding spans -> pad_value
1059
+ # =========================================================
1060
+
1061
+ pad_mask = (pred_spans == 0).all(dim=-1)
1062
+
1063
+ align_obj[pad_mask] = pad_value
1064
+
1065
+ return align_obj
1066
+
1067
+ def extract_spans(
1068
+ all_spans, # (B, N, 2)
1069
+ all_label, # (B, N)
1070
+ pred_spans # (B, M, 2)
1071
+ ):
1072
+ """
1073
+ Return:
1074
+ pred_list:
1075
+ [(bidx, (s, e)), ...]
1076
+
1077
+ gold_list:
1078
+ [(bidx, (s, e)), ...]
1079
+ """
1080
+
1081
+ # =========================================================
1082
+ # Gold spans
1083
+ # =========================================================
1084
+
1085
+ gold_mask = all_label > 0 # (B, N)
1086
+
1087
+ gold_indices = gold_mask.nonzero(as_tuple=False)
1088
+
1089
+ gold_list = [
1090
+ (
1091
+ int(b),
1092
+ (
1093
+ int(all_spans[b, n, 0]),
1094
+ int(all_spans[b, n, 1])
1095
+ )
1096
+ )
1097
+ for b, n in gold_indices
1098
+ ]
1099
+
1100
+ # =========================================================
1101
+ # Pred spans
1102
+ # =========================================================
1103
+
1104
+ pred_mask = (pred_spans > 0).all(dim=-1) # (B, M)
1105
+
1106
+ pred_indices = pred_mask.nonzero(as_tuple=False)
1107
+
1108
+ pred_list = [
1109
+ (
1110
+ int(b),
1111
+ (
1112
+ int(pred_spans[b, m, 0]),
1113
+ int(pred_spans[b, m, 1])
1114
+ )
1115
+ )
1116
+ for b, m in pred_indices
1117
+ ]
1118
+
1119
+ return gold_list, pred_list
1120
+
1121
+ def extract_entities(
1122
+ input_ids, # (B, L)
1123
+ start_logits, # (B, L, C)
1124
+ end_logits, # (B, L, C)
1125
+ logits, # (B, N, C)
1126
+ pred_spans, # (B, N, 2)
1127
+ id2label,
1128
+ alpha=1.0
1129
+ ):
1130
+ """
1131
+ Return:
1132
+ [
1133
+ (batch_idx, ([token_ids], label_name)),
1134
+ ...
1135
+ ]
1136
+ """
1137
+
1138
+ # =========================================================
1139
+ # Log-softmax
1140
+ # =========================================================
1141
+
1142
+ start_logprob = F.log_softmax(start_logits, dim=-1) # (B, L, C)
1143
+ end_logprob = F.log_softmax(end_logits, dim=-1) # (B, L, C)
1144
+ span_logprob = F.log_softmax(logits, dim=-1) # (B, N, C)
1145
+
1146
+ # =========================================================
1147
+ # Gather start/end score for pred spans
1148
+ # =========================================================
1149
+
1150
+ start_idx = pred_spans[..., 0] # (B, N)
1151
+ end_idx = pred_spans[..., 1] # (B, N)
1152
+
1153
+ B, N = start_idx.shape
1154
+ C = logits.shape[-1]
1155
+
1156
+ # (B, N, C)
1157
+ start_score = torch.gather(
1158
+ start_logprob,
1159
+ dim=1,
1160
+ index=start_idx.unsqueeze(-1).expand(-1, -1, C)
1161
+ )
1162
+
1163
+ # (B, N, C)
1164
+ end_score = torch.gather(
1165
+ end_logprob,
1166
+ dim=1,
1167
+ index=end_idx.unsqueeze(-1).expand(-1, -1, C)
1168
+ )
1169
+
1170
+ # =========================================================
1171
+ # Ensemble score
1172
+ # =========================================================
1173
+
1174
+ score = (
1175
+ span_logprob
1176
+ + alpha * (start_score + end_score)
1177
+ ) # (B, N, C)
1178
+
1179
+ # =========================================================
1180
+ # Predict label
1181
+ # =========================================================
1182
+
1183
+ pred_labels = score.argmax(dim=-1) # (B, N)
1184
+
1185
+ keep = (
1186
+ (pred_labels > 0) &
1187
+ (start_idx > 0) &
1188
+ (end_idx > 0)
1189
+ )
1190
+
1191
+ # =========================================================
1192
+ # Extract entities
1193
+ # =========================================================
1194
+
1195
+ results = []
1196
+
1197
+ for bidx in range(B):
1198
+
1199
+ valid_idxes = keep[bidx].nonzero(as_tuple=False).squeeze(-1)
1200
+
1201
+ for idx in valid_idxes:
1202
+
1203
+ lb = pred_labels[bidx, idx]
1204
+
1205
+ s, e = pred_spans[bidx, idx].tolist()
1206
+
1207
+ token_ids = input_ids[bidx, s:e+1].tolist()
1208
+
1209
+ results.append(
1210
+ (
1211
+ bidx,
1212
+ (
1213
+ token_ids,
1214
+ id2label[lb.item()]
1215
+ )
1216
+ )
1217
+ )
1218
+
1219
+ return results
1220
+
1221
+ class Trainer:
1222
+ def __init__(
1223
+ self, training_time="00:11:30:00", eval_mode="max", topk=1, save_name="network", save_best=True, save_last=False, max_grad_norm=200.0,
1224
+ logging=0, logging_file=False, checkpoints_dir="", early_stopping=False, eval_from_ratio=-1, eval_every=1, device='cpu',
1225
+ schedule_in_step=True, use_ema=True, ema_from_ratio=-1, ema_decay=0.999, return_best=True, return_last=True
1226
+ ):
1227
+ self.ema_net = None
1228
+
1229
+ self.training_time = self._time_str_to_seconds(training_time)
1230
+ self.mode = eval_mode
1231
+ self.topk = topk
1232
+ self.device = device
1233
+ self.logging = logging if logging < epochs else 1
1234
+ self.logging_file = logging_file
1235
+ self.checkpoints_dir = checkpoints_dir
1236
+ self.early_stopping = early_stopping
1237
+ self.eval_from_ratio = eval_from_ratio
1238
+ self.eval_every = eval_every
1239
+ self.save_name = save_name
1240
+ self.save_best = save_best
1241
+ self.save_last = save_last
1242
+ self.return_best = return_best
1243
+ self.return_last = return_last
1244
+ self.max_grad_norm = max_grad_norm
1245
+ self.schedule_in_step = schedule_in_step
1246
+ self.use_ema = use_ema
1247
+ self.ema_from_ratio = ema_from_ratio
1248
+ self.ema_decay = ema_decay
1249
+
1250
+ self.best_stage = [[float('-inf') if self.mode == 'max' else float('inf'), None, None]]
1251
+ self.grad_scaler = torch.amp.GradScaler(self.device, init_scale=1024.0)
1252
+
1253
+ def fit(self, network, optimizer, scheduler, loss_fn, epochs, train_loader, val_loader=None, eval_fn=None, start_epoch=1, start_training_time=None, id2label=None):
1254
+ if eval_fn is None:
1255
+ if self.mode == "max":
1256
+ eval_fn = lambda *x: -loss_fn(*x)
1257
+ else:
1258
+ eval_fn = lambda *x: loss_fn(*x)
1259
+
1260
+ if torch.cuda.device_count() > 1:
1261
+ network = DataParallelProxy(network)
1262
+ network = network.to(self.device)
1263
+
1264
+ if not start_training_time:
1265
+ start_training_time = time.time()
1266
+
1267
+ start_ema = int(epochs * self.ema_from_ratio)
1268
+ start_eval = int(epochs * self.eval_from_ratio)
1269
+
1270
+ if val_loader is None:
1271
+ print(f'[Trainer CallBack] 📢 Không có Val Set, không thể đánh giá và Early Stopping!')
1272
+ else:
1273
+ model_to_use_str = 'mô hình EMA' if self.use_ema else 'mô hình gốc'
1274
+ start_model_update_str = f'Bắt đầu cập nhật EMA từ epoch {start_epoch + start_ema}!' if self.use_ema else ''
1275
+ print(f'[Trainer CallBack] 📢 Đánh giá bằng {model_to_use_str} từ epoch {start_epoch + start_eval}!', start_model_update_str)
1276
+
1277
+ training_log = {}
1278
+ for epoch in range(start_epoch, epochs+start_epoch):
1279
+ if self.use_ema and self.ema_net is None and epoch - start_epoch >= start_ema:
1280
+ self.ema_net = ModelEmaV3Proxy(network, self.ema_decay, device=self.device)
1281
+
1282
+ try:
1283
+ teaching_rate = math.cos(math.pi / 2 * epoch / epochs)
1284
+ train_loss_epoch, train_loss_epoch_dict = self._train_epoch(network, train_loader, optimizer, scheduler, loss_fn, teaching_rate)
1285
+ logging_dict = {'lr': [group['lr'] for group in optimizer.param_groups], 'train_loss': train_loss_epoch}
1286
+ logging_dict.update(train_loss_epoch_dict)
1287
+
1288
+ if val_loader is not None and epoch - start_epoch >= start_eval and (epoch - start_epoch - start_eval) % self.eval_every == 0:
1289
+ eval_net = self.ema_net.module if (self.use_ema and self.ema_net is not None) else network
1290
+
1291
+ val_score, val_score_dict, _ = self._eval_epoch(eval_net, val_loader, eval_fn, id2label)
1292
+ update = self._update_best_network(eval_net, val_score, epoch)
1293
+ logging_dict.update({'val_score': val_score, 'best_score': self.best_stage[0][0], 'new_best_model': update})
1294
+ logging_dict.update(val_score_dict)
1295
+ if not self.schedule_in_step and scheduler:
1296
+ scheduler.step()
1297
+
1298
+ except RuntimeError as e:
1299
+ if "out of memory" in str(e).lower():
1300
+ print(f"[Trainer CallBack] ⚠️ Epoch {epoch}/{epochs}: CUDA Out of Memory! Clearing GPU cache...")
1301
+ torch.cuda.empty_cache()
1302
+ gc.collect()
1303
+ if torch.cuda.is_available():
1304
+ torch.cuda.synchronize()
1305
+ print(f"[Trainer CallBack] ✅ Epoch {epoch}/{epochs}: GPU memory cleared")
1306
+
1307
+ train_loader = reduce_batch_size(train_loader, ratio=0.5)
1308
+ if val_loader is not None:
1309
+ val_loader = reduce_batch_size(val_loader, ratio=0.5)
1310
+
1311
+ logging_dict = {'lr': [group['lr'] for group in optimizer.param_groups], 'train_loss': float('inf')}
1312
+ else:
1313
+ raise
1314
+
1315
+ training_log[epoch] = logging_dict
1316
+ if self.is_early_stopping(epoch):
1317
+ print(f'[Trainer CallBack] 📢 Epoch {epoch}/{epochs}: Detect Overfitting! Breaking Training Process...')
1318
+ break
1319
+ if self.logging:
1320
+ if epoch % self.logging == 0:
1321
+ print(f'[Trainer CallBack] 📢 Epoch {epoch}/{epochs}:', fmt(logging_dict))
1322
+ else:
1323
+ print(f'{epoch}...', end=' ')
1324
+
1325
+ if self._at_time_limit(start_training_time):
1326
+ print(f'[Trainer CallBack] ⚠️ Epoch {epoch}/{epochs}: Thời gian training giới hạn là {self.training_time}, hết giờ tại epoch {epoch}/{epochs}')
1327
+ break
1328
+
1329
+ if self.logging_file:
1330
+ os.makedirs(f'{self.checkpoints_dir}/logs', exist_ok=True)
1331
+ with open(f"{self.checkpoints_dir}/logs/{self.save_name}_logging.json", "a", encoding="utf-8") as f:
1332
+ f.write(json.dumps(training_log))
1333
+
1334
+ if self.use_ema and self.ema_net is not None:
1335
+ self._save_state_dict(self.ema_net.module)
1336
+ else:
1337
+ self._save_state_dict(network)
1338
+ print(f'[Trainer CallBack] 📢 Kết thúc training.\n')
1339
+
1340
+ best_model, last_model = None, None
1341
+ eval_net = self.ema_net.module if (self.use_ema and self.ema_net is not None) else network
1342
+ if self.return_best :
1343
+ best_model = self.best_stage[0][2] if self.best_stage[0][2] is not None else eval_net.state_dict()
1344
+ best_model = {k.replace("module.", ""): v.detach().cpu().clone() for k, v in best_model.items()}
1345
+ if self.return_last:
1346
+ last_model = eval_net.state_dict()
1347
+ last_model = {k.replace("module.", ""): v.detach().cpu().clone() for k, v in last_model.items()}
1348
+
1349
+ del network
1350
+ torch.cuda.empty_cache()
1351
+ gc.collect()
1352
+ return training_log, best_model, last_model
1353
+
1354
+ def _time_str_to_seconds(self, time_str):
1355
+ days, hours, minutes, seconds = map(int, time_str.split(":"))
1356
+ return days * 86400 + hours * 3600 + minutes * 60 + seconds
1357
+
1358
+ def _update_best_network(self, network, val_score, epoch):
1359
+ topk = max(1, self.topk)
1360
+ self.best_stage.append([val_score, epoch, {k: v.detach().cpu().clone() for k, v in network.state_dict().items()}])
1361
+ self.best_stage = sorted(self.best_stage, reverse=(self.mode == 'max'), key=lambda x: x[0])[:topk]
1362
+ if val_score in [x[0] for x in self.best_stage]:
1363
+ return True
1364
+ return False
1365
+
1366
+ def is_early_stopping(self, epoch):
1367
+ if self.best_stage[0][1] is None:
1368
+ return False
1369
+ if not self.early_stopping:
1370
+ return False
1371
+ return epoch - self.best_stage[0][1] >= self.early_stopping
1372
+
1373
+ def _at_time_limit(self, start_training_time):
1374
+ return time.time() - start_training_time >= self.training_time
1375
+
1376
+ def _save_state_dict(self, network):
1377
+ if self.topk <= 0:
1378
+ return
1379
+
1380
+ if self.save_best:
1381
+ for r in range(self.topk):
1382
+ os.makedirs(f'{self.checkpoints_dir}/r{r+1}s', exist_ok=True)
1383
+
1384
+ for rank, (score, epoch, state_dict) in enumerate(self.best_stage):
1385
+ if state_dict is None:
1386
+ continue
1387
+ state_dict = {k.replace("module.", ""): v.detach().cpu().clone() for k, v in state_dict.items()}
1388
+ torch.save(state_dict, f'{self.checkpoints_dir}/r{rank+1}s/{self.save_name}_r{rank+1}_vs{score:.5f}_{"ema" if self.ema_net is not None else ""}.pth')
1389
+ if self.save_last:
1390
+ os.makedirs(f'{self.checkpoints_dir}/lasts', exist_ok=True)
1391
+ state_dict = {k.replace("module.", ""): v.detach().cpu().clone() for k, v in network.state_dict().items()}
1392
+ torch.save(state_dict, f'{self.checkpoints_dir}/lasts/{self.save_name}_last_{"ema" if self.ema_net is not None else ""}.pth')
1393
+
1394
+ def _train_epoch(self, network, train_loader, optimizer, scheduler, loss_fn, teaching_rate):
1395
+ network.train()
1396
+ total_loss = 0
1397
+ total_loss_dict = {}
1398
+ for batch_idx, batch in enumerate(train_loader):
1399
+ optimizer.zero_grad()
1400
+ with torch.autocast(device_type=self.device, dtype=torch.float16):
1401
+ loss, loss_dict = self._cal_loss(network, batch, batch_idx, loss_fn, teaching_rate)
1402
+
1403
+ for k, v in loss_dict.items():
1404
+ t = total_loss_dict.get(k, 0)
1405
+ total_loss_dict[k] = t + v
1406
+ self.grad_scaler.scale(loss).backward()
1407
+ self.grad_scaler.unscale_(optimizer)
1408
+ grad_norm = nn.utils.clip_grad_norm_(network.parameters(), self.max_grad_norm)
1409
+ # print(grad_norm) # Bỏ cmt dòng này để biết nên chọn max_grad_norm bằng bao nhiêu...
1410
+ self.grad_scaler.step(optimizer)
1411
+ self.grad_scaler.update()
1412
+ if self.schedule_in_step and scheduler:
1413
+ scheduler.step()
1414
+ if self.use_ema and self.ema_net is not None:
1415
+ self.ema_net.update(network)
1416
+ total_loss += loss
1417
+ return (total_loss / len(train_loader)).item(), {k: v.item() / len(train_loader) for k, v in total_loss_dict.items()}
1418
+
1419
+ def _eval_epoch(self, network, val_loader, eval_fn, id2label):
1420
+ network.eval()
1421
+ total_score = 0.0
1422
+ total_score_dict = {}
1423
+ object_lists = None # sẽ init sau
1424
+
1425
+ with torch.no_grad():
1426
+ for batch_idx, batch in enumerate(val_loader):
1427
+ score, score_dict, objects = self._cal_val_score(network, batch, batch_idx, eval_fn, id2label)
1428
+ total_score += score
1429
+
1430
+ for k, v in score_dict.items():
1431
+ t = total_score_dict.get(k, 0)
1432
+ total_score_dict[k] = t + v
1433
+
1434
+ if objects:
1435
+ if object_lists is None:
1436
+ object_lists = [[] for _ in range(len(objects))]
1437
+
1438
+ for i, obj in enumerate(objects):
1439
+ object_lists[i].append(obj.detach())
1440
+
1441
+ if object_lists is not None:
1442
+ object_arrays = [
1443
+ torch.concat(obj_list, dim=0).cpu().numpy()
1444
+ for obj_list in object_lists
1445
+ ]
1446
+ else:
1447
+ object_arrays = []
1448
+
1449
+ return total_score / len(val_loader), {k: v / len(val_loader) for k, v in total_score_dict.items()}, object_arrays
1450
+
1451
+ def _cal_loss(self, network, batch, batch_idx, loss_fn, teaching_rate):
1452
+ # Bạn cần override _cal_loss để tính loss
1453
+ input_ids = batch['input_ids'].to(self.device)
1454
+ attention_mask = batch['attention_mask'].to(self.device)
1455
+ all_spans = batch['all_spans'].to(self.device)
1456
+ all_labels = batch['all_labels'].to(self.device)
1457
+ all_weights = batch['all_weights'].to(self.device)
1458
+ start_labels = batch['start_labels'].to(self.device)
1459
+ end_labels = batch['end_labels'].to(self.device)
1460
+
1461
+ choice = random.random()
1462
+ if choice < teaching_rate:
1463
+ start_logits, end_logits, logits, pred_spans = network(input_ids, attention_mask, all_spans)
1464
+ else:
1465
+ start_logits, end_logits, logits, pred_spans = network(input_ids, attention_mask)
1466
+
1467
+ align_labels = align(all_spans, pred_spans, all_labels, -100)
1468
+ align_weights = align(all_spans, pred_spans, all_weights, 0)
1469
+
1470
+ loss_dict = loss_fn(
1471
+ logits, align_labels, align_weights,
1472
+ start_logits, start_labels,
1473
+ end_logits, end_labels,
1474
+ )
1475
+ return loss_dict['total'], loss_dict
1476
+
1477
+ def _cal_val_score(self, network, batch, batch_idx, eval_fn, id2label):
1478
+ # Bạn cần override _cal_val_score để tính val score, list bên cạnh là để trả về y hay pred gì đó (nếu cần)
1479
+ input_ids = batch['input_ids'].to(self.device)
1480
+ attention_mask = batch['attention_mask'].to(self.device)
1481
+ all_spans = batch['all_spans'].to(self.device)
1482
+ all_labels = batch['all_labels'].to(self.device)
1483
+ gold_entities = batch['gold_entities']
1484
+
1485
+ B, _, _ = input_ids.shape
1486
+
1487
+ start_logits, end_logits, logits, pred_spans = network(input_ids, attention_mask)
1488
+
1489
+ gold_list, pred_list = extract_spans(all_spans, all_labels, pred_spans)
1490
+ gold_list = list_to_tuple(gold_list)
1491
+ pred_list = list_to_tuple(pred_list)
1492
+ span_score = eval_fn(pred_list, gold_list)['recall']
1493
+
1494
+ pred_ids = extract_entities(input_ids.reshape(B, -1), start_logits, end_logits, logits, pred_spans, id2label, alpha=0.5)
1495
+ pred_ids = list_to_tuple(pred_ids)
1496
+ gold_ids = list_to_tuple(gold_entities)
1497
+ score_dict = eval_fn(pred_ids, gold_ids)
1498
+
1499
+ score_dict.update({'span_recall': span_score})
1500
+ return score_dict['f1'] + score_dict['span_recall'], score_dict, []
1501
+
1502
+ # %% [code]
1503
+ class PhoBERTSpanAligner:
1504
+ def __init__(self, tokenizer, max_len):
1505
+ self.tokenizer = tokenizer
1506
+ self.max_len = max_len
1507
+
1508
+ # ===== 1. Extract discontinuous spans =====
1509
+ def extract_spans(self, sample):
1510
+ entity_spans = []
1511
+
1512
+ for event in sample["entities"]:
1513
+ entity_type = event["label"]
1514
+ spans = [tuple(event["offset"])]
1515
+ entity_spans.append({
1516
+ "spans": spans,
1517
+ "label": entity_type
1518
+ })
1519
+
1520
+ return entity_spans
1521
+
1522
+ # ===== 2. Word offsets =====
1523
+ def build_word_offsets(self, text, words):
1524
+ offsets = []
1525
+ pointer = 0
1526
+
1527
+ for word in words:
1528
+ start = text.find(word, pointer)
1529
+ end = start + len(word)
1530
+ offsets.append((start, end))
1531
+ pointer = end
1532
+
1533
+ return offsets
1534
+
1535
+ # ===== 3. Char → word =====
1536
+ def char_span_to_word_span(self, word_offsets, start, end):
1537
+ start_word = None
1538
+ end_word = None
1539
+
1540
+ for i, (w_start, w_end) in enumerate(word_offsets):
1541
+ if w_start <= start < w_end:
1542
+ start_word = i
1543
+ if w_start < end <= w_end:
1544
+ end_word = i
1545
+
1546
+ return start_word, end_word
1547
+
1548
+ # ===== 4. Word → subword =====
1549
+ def word_to_subword_map(self, words):
1550
+ mapping = []
1551
+ subword_index = 1 # <s>
1552
+
1553
+ for word in words:
1554
+ sub_tokens = self.tokenizer.tokenize(word)
1555
+ start = subword_index
1556
+ end = subword_index + len(sub_tokens) - 1
1557
+ mapping.append((start, end))
1558
+ subword_index += len(sub_tokens)
1559
+
1560
+ return mapping
1561
+
1562
+ # ===== 5. Span → subword =====
1563
+ def span_to_subword(self, word_offsets, word_subword_map, spans):
1564
+ sub_spans = []
1565
+
1566
+ for span_start, span_end in spans:
1567
+ w_start, w_end = self.char_span_to_word_span(
1568
+ word_offsets, span_start, span_end
1569
+ )
1570
+ if w_start is None or w_end is None:
1571
+ continue
1572
+
1573
+ sub_start = word_subword_map[w_start][0]
1574
+ sub_end = word_subword_map[w_end][1]
1575
+ sub_spans.append((sub_start, sub_end))
1576
+
1577
+ return sub_spans
1578
+
1579
+ def extract_valid_spans(self, sub_spans):
1580
+ valid_spans = []
1581
+ for s, e in sub_spans:
1582
+ if s < 0 or e < 0 or s >= self.max_len or e >= self.max_len or s > e:
1583
+ continue
1584
+ valid_spans.append((s, e))
1585
+ return valid_spans
1586
+
1587
+ def encode(self, sample):
1588
+ text = sample["text"]
1589
+ entities = self.extract_spans(sample)
1590
+
1591
+ # ===== 1. Word tokenize =====
1592
+ words = word_tokenize(text)
1593
+ sentence = " ".join(words)
1594
+
1595
+ # ===== 2. Mapping =====
1596
+ word_offsets = self.build_word_offsets(text, words)
1597
+ word_subword_map = self.word_to_subword_map(words)
1598
+
1599
+ # ===== 3. Tokenize FULL =====
1600
+ encoding = self.tokenizer(
1601
+ sentence,
1602
+ max_length=self.max_len,
1603
+ truncation=True,
1604
+ padding="max_length",
1605
+ return_tensors="pt"
1606
+ )
1607
+ input_ids = encoding["input_ids"][0]
1608
+ attention_mask = encoding["attention_mask"][0]
1609
+
1610
+ # ===== 5. Convert spans =====
1611
+ entities_gold_spans = []
1612
+
1613
+ for ent in entities:
1614
+ label = ent["label"]
1615
+
1616
+ sub_spans = self.span_to_subword(
1617
+ word_offsets,
1618
+ word_subword_map,
1619
+ ent["spans"]
1620
+ )
1621
+ valid_spans = self.extract_valid_spans(sub_spans)
1622
+ if len(valid_spans) == 0:
1623
+ continue
1624
+ entities_gold_spans.append((tuple(valid_spans), label))
1625
+
1626
+ return {
1627
+ "input_ids": input_ids,
1628
+ "attention_mask": attention_mask,
1629
+ "entities_gold_spans": entities_gold_spans,
1630
+ }
1631
+
1632
+ def generate_spans(attention_mask, max_span_len):
1633
+ seq_len = attention_mask.sum().item() - 2
1634
+ spans = []
1635
+ for i in range(1, seq_len+1):
1636
+ for j in range(i, min(i+max_span_len, seq_len+1)):
1637
+ spans.append((i, j))
1638
+ return spans
1639
+
1640
+ def match_gold_labels(
1641
+ gold_spans, # (N, 2)
1642
+ gold_labels, # (N,)
1643
+ pred_spans, # (M, 2)
1644
+ default_label=-100
1645
+ ):
1646
+ """
1647
+ Return:
1648
+ pred_labels: (M,)
1649
+ """
1650
+
1651
+ pred_labels = torch.full(
1652
+ (pred_spans.size(0),),
1653
+ default_label,
1654
+ dtype=gold_labels.dtype,
1655
+ device=gold_labels.device
1656
+ )
1657
+ if gold_spans.size(0) == 0:
1658
+ return pred_labels
1659
+
1660
+ # (M, N)
1661
+ matched = (pred_spans[:, None, :] == gold_spans[None, :, :]).all(dim=-1)
1662
+ has_match = matched.any(dim=1)
1663
+
1664
+ # lấy index gold đầu tiên match
1665
+ gold_idx = matched.float().argmax(dim=1)
1666
+
1667
+ pred_labels[has_match] = gold_labels[gold_idx[has_match]]
1668
+
1669
+ return pred_labels
1670
+
1671
+ class KLTNDataset(Dataset):
1672
+ def __init__(self, all_data, using_idxes, label2id, tokenizer, n_spans, max_len, max_n_parts, max_span_len, weight_rate):
1673
+ super().__init__()
1674
+ self.tokenizer = tokenizer
1675
+ self.aligner = PhoBERTSpanAligner(tokenizer, max_len*max_n_parts)
1676
+ self.all_data = all_data
1677
+ self.using_idxes = using_idxes
1678
+ self.label2id = label2id
1679
+ self.n_spans = n_spans
1680
+ self.max_len = max_len
1681
+ self.max_n_parts = max_n_parts
1682
+ self.max_span_len = max_span_len
1683
+ self.weight_rate = weight_rate
1684
+
1685
+ def __len__(self):
1686
+ return len(self.using_idxes)
1687
+
1688
+ def span_iou(self, span1, span2):
1689
+ s1, e1 = span1
1690
+ s2, e2 = span2
1691
+
1692
+ # intersection
1693
+ inter_left = max(s1, s2)
1694
+ inter_right = min(e1, e2)
1695
+ intersection = max(0, inter_right - inter_left + 1)
1696
+
1697
+ # lengths
1698
+ len1 = e1 - s1 + 1
1699
+ len2 = e2 - s2 + 1
1700
+
1701
+ # union
1702
+ union = len1 + len2 - intersection
1703
+ if union == 0:
1704
+ return 0.0
1705
+
1706
+ return intersection / union
1707
+
1708
+ def get_weights(self, spans, pos_spans):
1709
+ # spans: (N, 2), pos_spans: (K, 2)
1710
+ N, K = spans.size(0), pos_spans.size(0)
1711
+ device = spans.device
1712
+
1713
+ # ===== edge case =====
1714
+ if K == 0:
1715
+ weights = torch.ones(N, device=device, dtype=torch.float)
1716
+ return weights
1717
+
1718
+ # ===== IoU =====
1719
+ s1, e1 = spans[:, None, 0], spans[:, None, 1]
1720
+ s2, e2 = pos_spans[None, :, 0], pos_spans[None, :, 1]
1721
+
1722
+ inter_s = torch.maximum(s1, s2)
1723
+ inter_e = torch.minimum(e1, e2)
1724
+ inter = (inter_e - inter_s + 1).clamp(min=0)
1725
+
1726
+ len1 = (e1 - s1 + 1)
1727
+ len2 = (e2 - s2 + 1)
1728
+ union = len1 + len2 - inter
1729
+
1730
+ iou = inter / (union + 1e-8) # (N, K)
1731
+
1732
+ # ===== weights: IoU=0 -> 1, else 10*IoU =====
1733
+ max_iou, _ = iou.max(dim=1)
1734
+ if self.weight_rate is not None:
1735
+ weights = torch.where(max_iou > 0, 1 + self.weight_rate * max_iou, torch.ones_like(max_iou))
1736
+ else:
1737
+ weights = torch.ones_like(max_iou)
1738
+
1739
+ return weights
1740
+
1741
+ def to_span_label_tensors(self, data, label_map):
1742
+ if len(data) == 0:
1743
+ return (
1744
+ torch.zeros((0, 2), dtype=torch.long),
1745
+ torch.zeros((0,), dtype=torch.long)
1746
+ )
1747
+
1748
+ spans = torch.tensor([list(spans[0]) for spans, _ in data], dtype=torch.long)
1749
+ labels = torch.tensor([label_map[label] for _, label in data], dtype=torch.long)
1750
+ return spans, labels
1751
+
1752
+ def __getitem__(self, idx):
1753
+ ridx = self.using_idxes[idx]
1754
+ sample = self.all_data[ridx]
1755
+ result = self.aligner.encode(sample)
1756
+
1757
+ input_ids = result["input_ids"].squeeze(0)
1758
+ attention_mask = result["attention_mask"].squeeze(0)
1759
+ entities_gold_spans = result["entities_gold_spans"]
1760
+
1761
+ # Get all spans
1762
+ gold_spans = torch.tensor([spans[0] for spans, _ in entities_gold_spans], dtype=torch.long) if entities_gold_spans else torch.empty(0, 2, dtype=torch.long)
1763
+ gold_labels = torch.tensor([self.label2id[label] for _, label in entities_gold_spans], dtype=torch.long) if entities_gold_spans else torch.empty(0, dtype=torch.long)
1764
+
1765
+ all_spans = torch.tensor(generate_spans(attention_mask, self.max_span_len))
1766
+ all_labels = match_gold_labels(
1767
+ gold_spans, # (N, 2)
1768
+ gold_labels, # (N,)
1769
+ all_spans, # (M, 2)
1770
+ default_label=0
1771
+ )
1772
+ all_weights = self.get_weights(all_spans, gold_spans)
1773
+
1774
+ # Sample
1775
+ num_spans = all_spans.size(0)
1776
+
1777
+ if num_spans > self.n_spans:
1778
+ # ưu tiên giữ positive
1779
+ pos_mask = all_labels != 0
1780
+ neg_mask = ~pos_mask
1781
+
1782
+ pos_idx = torch.nonzero(pos_mask).squeeze(-1)
1783
+ neg_idx = torch.nonzero(neg_mask).squeeze(-1)
1784
+
1785
+ n_pos = min(len(pos_idx), self.n_spans)
1786
+
1787
+ # lấy toàn bộ hoặc random positive
1788
+ if len(pos_idx) > n_pos:
1789
+ perm = torch.randperm(len(pos_idx), device=pos_idx.device)
1790
+ pos_idx = pos_idx[perm[:n_pos]]
1791
+
1792
+ remaining = self.n_spans - len(pos_idx)
1793
+
1794
+ # sample negative
1795
+ if remaining > 0 and len(neg_idx) > 0:
1796
+ perm = torch.randperm(len(neg_idx), device=neg_idx.device)
1797
+ neg_idx = neg_idx[perm[:remaining]]
1798
+
1799
+ keep_idx = torch.cat([pos_idx, neg_idx], dim=0)
1800
+ else:
1801
+ keep_idx = pos_idx
1802
+
1803
+ # shuffle lại
1804
+ perm = torch.randperm(len(keep_idx), device=keep_idx.device)
1805
+ keep_idx = keep_idx[perm]
1806
+
1807
+ all_spans = all_spans[keep_idx]
1808
+ all_labels = all_labels[keep_idx]
1809
+ all_weights = all_weights[keep_idx]
1810
+
1811
+ # Get label
1812
+ gold_entities = []
1813
+ start_labels = torch.ones_like(input_ids) * (1-attention_mask) * (-100)
1814
+ end_labels = torch.ones_like(input_ids) * (1-attention_mask) * (-100)
1815
+ for spans, label in entities_gold_spans:
1816
+ s, e = spans[0]
1817
+
1818
+ start_labels[s] = self.label2id[f'{label}']
1819
+ end_labels[e] = self.label2id[f'{label}']
1820
+
1821
+ gold_entities.append((tuple(input_ids[s:e+1].tolist()), label))
1822
+
1823
+ input_ids = input_ids.reshape(self.max_n_parts, self.max_len)
1824
+ attention_mask = attention_mask.reshape(self.max_n_parts, self.max_len)
1825
+
1826
+ n_valid_parts = math.ceil(attention_mask.sum().item() / self.max_len)
1827
+ input_ids = input_ids[:n_valid_parts]
1828
+ attention_mask = attention_mask[:n_valid_parts]
1829
+ start_labels = start_labels[:n_valid_parts*self.max_len]
1830
+ end_labels = end_labels[:n_valid_parts*self.max_len]
1831
+
1832
+ return {
1833
+ "input_ids": input_ids,
1834
+ "attention_mask": attention_mask,
1835
+ "all_spans": all_spans,
1836
+ "all_labels": all_labels,
1837
+ "all_weights": all_weights,
1838
+ "start_labels": start_labels,
1839
+ "end_labels": end_labels,
1840
+ "gold_entities": gold_entities,
1841
+ }
1842
+
1843
+ def _pad_batch(tensor_list, pad_value=0):
1844
+ """
1845
+ tensor_list: list of tensors
1846
+ mỗi tensor shape: (Nk, n_parts_i, max_len_i)
1847
+
1848
+ return:
1849
+ padded tensor shape: (B, max_Nk, max_n_parts, max_len)
1850
+ """
1851
+
1852
+ # lấy max toàn batch
1853
+ max_Nk = max(t.size(0) for t in tensor_list)
1854
+ max_n_parts = max(t.size(1) for t in tensor_list)
1855
+ max_len = max(t.size(2) for t in tensor_list)
1856
+
1857
+ padded = []
1858
+
1859
+ for t in tensor_list:
1860
+ Nk, n_parts_i, max_len_i = t.shape
1861
+
1862
+ # pad chiều n_parts và max_len trước
1863
+ if n_parts_i < max_n_parts or max_len_i < max_len:
1864
+ new_t = t.new_full(
1865
+ (Nk, max_n_parts, max_len),
1866
+ pad_value
1867
+ )
1868
+ new_t[:, :n_parts_i, :max_len_i] = t
1869
+ t = new_t
1870
+
1871
+ # pad chiều Nk
1872
+ if Nk < max_Nk:
1873
+ pad_tensor = t.new_full(
1874
+ (max_Nk - Nk, max_n_parts, max_len),
1875
+ pad_value
1876
+ )
1877
+ t = torch.cat([t, pad_tensor], dim=0)
1878
+
1879
+ padded.append(t)
1880
+
1881
+ return torch.stack(padded) # (B, max_Nk, max_n_parts, max_len)
1882
+
1883
+ def collate_fn(batch):
1884
+ gold_entities = []
1885
+ for bidx, b in enumerate(batch):
1886
+ for entity in b['gold_entities']:
1887
+ gold_entities.append([bidx, entity])
1888
+
1889
+ input_ids = [b["input_ids"].unsqueeze(-1) for b in batch]
1890
+ attention_mask = [b["attention_mask"].unsqueeze(-1) for b in batch]
1891
+ all_spans = [b["all_spans"].unsqueeze(-1) for b in batch]
1892
+ all_labels = [b["all_labels"].unsqueeze(-1).unsqueeze(-1) for b in batch]
1893
+ all_weights = [b["all_weights"].unsqueeze(-1).unsqueeze(-1) for b in batch]
1894
+ start_labels = [b["start_labels"].unsqueeze(-1).unsqueeze(-1) for b in batch]
1895
+ end_labels = [b["end_labels"].unsqueeze(-1).unsqueeze(-1) for b in batch]
1896
+
1897
+ # pad theo Nk
1898
+ input_ids = _pad_batch(input_ids, pad_value=0).squeeze(-1)
1899
+ attention_mask = _pad_batch(attention_mask, pad_value=0).squeeze(-1)
1900
+ all_spans = _pad_batch(all_spans, pad_value=0).squeeze(-1)
1901
+ all_labels = _pad_batch(all_labels, pad_value=-100).squeeze(-1).squeeze(-1)
1902
+ all_weights = _pad_batch(all_weights, pad_value=0).squeeze(-1).squeeze(-1)
1903
+ start_labels = _pad_batch(start_labels, pad_value=-100).squeeze(-1).squeeze(-1)
1904
+ end_labels = _pad_batch(end_labels, pad_value=-100).squeeze(-1).squeeze(-1)
1905
+
1906
+ return {
1907
+ "input_ids": input_ids,
1908
+ "attention_mask": attention_mask,
1909
+ "all_spans": all_spans,
1910
+ "all_labels": all_labels,
1911
+ "all_weights": all_weights,
1912
+ "start_labels": start_labels,
1913
+ "end_labels": end_labels,
1914
+ "gold_entities": gold_entities,
1915
+ }
1916
+
1917
+ # %% [code]
1918
+ def shift_bidx(spans, batch_idx):
1919
+ shifted = []
1920
+ for bidx, ent in spans:
1921
+ new_bidx = bidx + batch_idx * batch_size
1922
+ shifted.append((new_bidx, ent))
1923
+ return shifted
1924
+
1925
+ def refactor_entities(entities, save_dict):
1926
+ i, c = [], []
1927
+ for bidx, (ids, lb) in entities:
1928
+ if (bidx, ids) not in i:
1929
+ i.append((bidx, ids))
1930
+
1931
+ if (bidx, (ids, lb)) not in c:
1932
+ c.append((bidx, (ids, lb)))
1933
+
1934
+ save_dict['Ent-I'].extend(i)
1935
+ save_dict['Ent-C'].extend(c)
1936
+
1937
+ def test(
1938
+ network, state_dicts, test_loader, eval_fn, analyzer, device, id2label, tokenizer,
1939
+ alphas=[0.0, 0.2, 0.4, 0.5, 0.6, 0.8, 1.0], keep_neighbors=[0, 1, 2, 3]
1940
+ ):
1941
+ if torch.cuda.device_count() > 1:
1942
+ network = DataParallelProxy(network)
1943
+ network = network.to(device)
1944
+ network.eval()
1945
+
1946
+ eval_types = ['Ent-I', 'Ent-C']
1947
+
1948
+ all_pred = {(keep_neighbor, alpha): {eval_type: [] for eval_type in eval_types} for alpha in alphas for keep_neighbor in keep_neighbors}
1949
+ all_gold = {eval_type: [] for eval_type in eval_types}
1950
+
1951
+ list_input_ids = []
1952
+
1953
+ with torch.no_grad():
1954
+ for batch_idx, batch in enumerate(test_loader):
1955
+ input_ids = batch['input_ids'].to(device)
1956
+ attention_mask = batch['attention_mask'].to(device)
1957
+ all_spans = batch['all_spans'].to(device)
1958
+ gold_entities = batch['gold_entities']
1959
+
1960
+ B, _, _ = input_ids.shape
1961
+ list_input_ids.extend(input_ids.reshape(B, -1).tolist())
1962
+
1963
+ list_hidden_states = []
1964
+ list_start_logits = []
1965
+ list_end_logits = []
1966
+ for sd in state_dicts:
1967
+ if torch.cuda.device_count() > 1:
1968
+ network.module.load_state_dict(sd)
1969
+ else:
1970
+ network.load_state_dict(sd)
1971
+
1972
+ hidden_states, attention_mask = network.encode(input_ids, attention_mask)
1973
+ start_logits, end_logits = network.get_token_logits(hidden_states)
1974
+ list_hidden_states.append(hidden_states)
1975
+ list_start_logits.append(start_logits)
1976
+ list_end_logits.append(end_logits)
1977
+
1978
+ ensemble_start_logits = torch.stack(list_start_logits, dim=0).mean(dim=0)
1979
+ ensemble_end_logits = torch.stack(list_end_logits, dim=0).mean(dim=0)
1980
+
1981
+ for keep_neighbor in keep_neighbors:
1982
+ list_logits = []
1983
+ spans = filter_spans(ensemble_start_logits, ensemble_end_logits, attention_mask, network.max_span_len, network.topk_spans, keep_neighbor)
1984
+
1985
+ for sd, hidden_states in zip(state_dicts, list_hidden_states):
1986
+ if torch.cuda.device_count() > 1:
1987
+ network.module.load_state_dict(sd)
1988
+ else:
1989
+ network.load_state_dict(sd)
1990
+ span_reprs = get_span_reprs(hidden_states, spans)
1991
+ logits = network.get_logits(span_reprs)
1992
+ list_logits.append(logits)
1993
+
1994
+ ensemble_logits = torch.stack(list_logits, dim=0).mean(dim=0)
1995
+ for alpha in alphas:
1996
+ pred_entities = extract_entities(input_ids.reshape(B, -1), ensemble_start_logits, ensemble_end_logits, ensemble_logits, spans, id2label, alpha=alpha)
1997
+ pred_entities = shift_bidx(pred_entities, batch_idx)
1998
+ refactor_entities(pred_entities, all_pred[keep_neighbor, alpha])
1999
+
2000
+ gold_entities = shift_bidx(gold_entities, batch_idx)
2001
+ refactor_entities(gold_entities, all_gold)
2002
+
2003
+ # ===== GLOBAL EVAL =====
2004
+ final_score = {}
2005
+ max_key = -1
2006
+ max_scores = -1
2007
+ for key in all_pred.keys():
2008
+ final_score[key] = {}
2009
+ for eval_type in eval_types:
2010
+ score = eval_fn(list_to_tuple(all_pred[key][eval_type]), list_to_tuple(all_gold[eval_type]))
2011
+ final_score[key][eval_type] = score
2012
+ if max_scores < final_score[key]['Ent-C']['f1']:
2013
+ max_scores = final_score[key]['Ent-C']['f1']
2014
+ max_key = key
2015
+
2016
+ analyze_result = analyzer.analyze(list_to_tuple(all_pred[max_key]['Ent-I']), list_to_tuple(all_gold['Ent-I']))
2017
+
2018
+ # ===== PREDICT =====
2019
+ predictions = []
2020
+ for input_ids in list_input_ids:
2021
+ predictions.append([tokenizer.decode(input_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)])
2022
+ for bidx, (ids, lb) in all_pred[max_key]['Ent-C']:
2023
+ predictions[bidx].append((tokenizer.decode(ids, skip_special_tokens=True, clean_up_tokenization_spaces=True), lb))
2024
+
2025
+ return final_score, analyze_result, predictions
2026
+
2027
+ # %% [code]
2028
+ with open(f'{train_dir}/train.json', "r", encoding="utf-8") as f:
2029
+ data_train = json.load(f)
2030
+
2031
+ with open(f'{test_dir}/test.json', "r", encoding="utf-8") as f:
2032
+ data_test = json.load(f)
2033
+
2034
+ print('Train:', len(data_train))
2035
+ print('Test:', len(data_test))
2036
+
2037
+ # %% [code]
2038
+ entity_types = ['O'] + sorted(list(set([e['label'] for d in data_train + data_test for e in d['entities']])))
2039
+ # bio_entity_type = ['O'] + [f'{prefix}-{ent}' for ent in entity_types for prefix in ['B', 'I']]
2040
+ label2id = {l: i for i, l in enumerate(entity_types)}
2041
+ id2label = {i: l for l, i in label2id.items()}
2042
+
2043
+ # %% [code]
2044
+ zero_entities_idxes = []
2045
+ for idx, d in enumerate(data_train):
2046
+ if len(d['entities']) == 0:
2047
+ zero_entities_idxes.append(idx)
2048
+
2049
+ n_zero_entities_samples = len(zero_entities_idxes)
2050
+ n_has_entities_samples = len(data_train) - n_zero_entities_samples
2051
+
2052
+ random.seed(42)
2053
+ k = min(int(n_has_entities_samples * zero_entities_rate), len(zero_entities_idxes))
2054
+ sampled_zero_entities_idxes = random.sample(zero_entities_idxes, k)
2055
+
2056
+ new_data_train = []
2057
+ for idx, d in enumerate(data_train):
2058
+ if len(d['entities']) == 0:
2059
+ if idx in sampled_zero_entities_idxes:
2060
+ new_data_train.append(d)
2061
+ else:
2062
+ new_data_train.append(d)
2063
+ data_train = new_data_train
2064
+
2065
+ print('Train:', len(data_train))
2066
+
2067
+ # %% [code]
2068
+ if debug_only:
2069
+ data_train = data_train[:10]
2070
+ data_test = data_test[:10]
2071
+
2072
+ print('Train:', len(data_train))
2073
+ print('Test:', len(data_test))
2074
+
2075
+ # %% [code]
2076
+ tokenizer = AutoTokenizer.from_pretrained(backbone_model_name)
2077
+
2078
+ # %% [code]
2079
+ print('Experiment name:', state_dict_save_name)
2080
+
2081
+ # %% [code]
2082
+ # trainset = KLTNDataset(data_train, np.array(range(len(data_train))), label2id, tokenizer, **train_memory_params)
2083
+ # train_loader = DataLoader(trainset, collate_fn=collate_fn, **train_loader_params)
2084
+ # for b in train_loader:
2085
+ # break
2086
+
2087
+ # %% [code]
2088
+ if not test_only:
2089
+ full_idxes = np.array(range(len(data_train)))
2090
+ training_logs, best_models, last_models = [], [], []
2091
+ start_training_time = time.time()
2092
+ for seed in SEEDS:
2093
+ kf = KFold(n_splits=nfolds, shuffle=True, random_state=seed)
2094
+ for fold_idx, (tr_idx, va_idx) in enumerate(kf.split(full_idxes)):
2095
+ if only_fold_idx is not None and only_fold_idx >= 0 and only_fold_idx != fold_idx:
2096
+ continue
2097
+ set_seed(seed)
2098
+
2099
+ train_idxes, val_idxes = full_idxes[tr_idx], full_idxes[va_idx]
2100
+
2101
+ trainset = KLTNDataset(data_train, train_idxes, label2id, tokenizer, **train_memory_params)
2102
+ valset = KLTNDataset(data_train, val_idxes, label2id, tokenizer, **val_memory_params)
2103
+
2104
+ generator = torch.Generator()
2105
+ generator.manual_seed(seed)
2106
+ train_loader = DataLoader(trainset, generator=generator, collate_fn=collate_fn, **train_loader_params)
2107
+ val_loader = DataLoader(valset, generator=generator, collate_fn=collate_fn, **val_loader_params)
2108
+
2109
+ my_model = IEModel(
2110
+ num_labels=len(label2id),
2111
+ **model_params
2112
+ )
2113
+ total_params = sum(p.numel() for p in my_model.parameters())
2114
+ print(f"Total params: {total_params:,}")
2115
+
2116
+ # optimizer, scheduler = configure_optimizers(my_model, optim_params, scheduler_params)
2117
+ encoder_params = set(map(id, my_model.encoder.parameters()))
2118
+ other_params = [
2119
+ p for p in my_model.parameters()
2120
+ if id(p) not in encoder_params
2121
+ ]
2122
+ optimizer = optim.AdamW([
2123
+ {"params": my_model.encoder.parameters(), "lr": 2e-5},
2124
+ {"params": other_params}
2125
+ ], lr=5e-4)
2126
+ scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=20, eta_min=1e-6)
2127
+
2128
+ loss_fn = CustomLoss(
2129
+ **loss_func_params
2130
+ )
2131
+ eval_fn = CustomEvalFn(**eval_func_params)
2132
+ trainer_params['save_name'] = f'{state_dict_save_name}_s{seed}_f{fold_idx}'
2133
+ trainer = Trainer(**trainer_params)
2134
+
2135
+ print(f'Start Training Fold {fold_idx}...')
2136
+ training_log, best_model, last_model = trainer.fit(
2137
+ my_model, optimizer, scheduler, loss_fn, epochs, train_loader, val_loader, eval_fn,
2138
+ start_epoch=1, start_training_time=start_training_time, id2label=id2label
2139
+ )
2140
+
2141
+ training_logs.append(training_log)
2142
+ best_models.append(best_model)
2143
+ last_models.append(last_model)
2144
+
2145
+ # %% [code]
2146
+ def load_all_state_dicts(folder):
2147
+ files = []
2148
+
2149
+ for file in os.listdir(folder):
2150
+ if file.endswith(".pt") or file.endswith(".pth"):
2151
+ m = re.search(r"f(\d+)", file) # tìm f<số>
2152
+ if m:
2153
+ fold = int(m.group(1))
2154
+ files.append((fold, file))
2155
+
2156
+ # sort theo fold
2157
+ files.sort(key=lambda x: x[0])
2158
+
2159
+ state_dicts = []
2160
+ for fold, file in files:
2161
+ path = os.path.join(folder, file)
2162
+ print(f"Loading fold {fold}: {file}")
2163
+ state_dict = torch.load(path, map_location="cpu")
2164
+ state_dicts.append(state_dict)
2165
+
2166
+ return state_dicts
2167
+
2168
+ if test_only:
2169
+ snapshot_download(repo_id=repo_name, local_dir="", repo_type="model", allow_patterns=[f"{state_dict_save_name}/**"])
2170
+ get_ipython().system('rm -rf .cache .gitattributes')
2171
+
2172
+ best_models = load_all_state_dicts(f"{state_dict_save_name}/r1s")
2173
+ last_models = load_all_state_dicts(f"{state_dict_save_name}/lasts")
2174
+
2175
+ # %% [code]
2176
+ def dict_to_df(data, row_names):
2177
+ """
2178
+ Input:
2179
+ {
2180
+ model_name: {
2181
+ (level1, ..., level(n-1)): {
2182
+ leveln: {
2183
+ metric: value
2184
+ }
2185
+ }
2186
+ }
2187
+ }
2188
+
2189
+ Output:
2190
+ - level1 -> level(n-1): columns thường
2191
+ - MultiIndex columns:
2192
+ (model_name, leveln, metric)
2193
+ """
2194
+
2195
+ rows = {}
2196
+
2197
+ for model_name, model_data in data.items():
2198
+
2199
+ for upper_levels, last_level_dict in model_data.items():
2200
+
2201
+ # đảm bảo tuple
2202
+ if not isinstance(upper_levels, tuple):
2203
+ upper_levels = (upper_levels,)
2204
+
2205
+ # ===== tạo key row =====
2206
+ row_key = upper_levels
2207
+
2208
+ if row_key not in rows:
2209
+
2210
+ row = {}
2211
+
2212
+ for i, lv in enumerate(upper_levels):
2213
+ row[row_names[i]] = lv
2214
+
2215
+ rows[row_key] = row
2216
+
2217
+ # ===== add metrics =====
2218
+ for last_level, metrics in last_level_dict.items():
2219
+
2220
+ for metric, value in metrics.items():
2221
+
2222
+ rows[row_key][
2223
+ (model_name, last_level, metric)
2224
+ ] = value
2225
+
2226
+ # ===== dataframe =====
2227
+ df = pd.DataFrame(rows.values())
2228
+
2229
+ # ===== split columns =====
2230
+ normal_cols = [
2231
+ c for c in df.columns
2232
+ if not isinstance(c, tuple)
2233
+ ]
2234
+
2235
+ metric_cols = [
2236
+ c for c in df.columns
2237
+ if isinstance(c, tuple)
2238
+ ]
2239
+
2240
+ df = df[normal_cols + metric_cols]
2241
+
2242
+ # ===== build multi columns =====
2243
+ df.columns = pd.MultiIndex.from_tuples([
2244
+ ("", "", c) if not isinstance(c, tuple) else c
2245
+ for c in df.columns
2246
+ ])
2247
+
2248
+ return df
2249
+
2250
+ def dict_to_records(data):
2251
+ """
2252
+ Input:
2253
+ {
2254
+ model_name: {
2255
+ (level1, level2, ..., leveln): {
2256
+ metric: value
2257
+ }
2258
+ }
2259
+ }
2260
+
2261
+ Output:
2262
+ [
2263
+ {
2264
+ "model": model_name,
2265
+ "levels": [...],
2266
+ "metrics": {...}
2267
+ },
2268
+ ...
2269
+ ]
2270
+ """
2271
+
2272
+ records = []
2273
+
2274
+ for model_name, model_data in data.items():
2275
+
2276
+ for levels, metrics in model_data.items():
2277
+
2278
+ # ensure tuple/list compatible
2279
+ if not isinstance(levels, (tuple, list)):
2280
+ levels = [levels]
2281
+
2282
+ records.append(
2283
+ {
2284
+ "model": model_name,
2285
+ "levels": list(levels),
2286
+ "metrics": metrics
2287
+ }
2288
+ )
2289
+
2290
+ return records
2291
+
2292
+ # %% [code]
2293
+ os.makedirs(f'{checkpoints_dir}/results', exist_ok=True)
2294
+ testset = KLTNDataset(data_test, range(len(data_test)), label2id, tokenizer, **val_memory_params)
2295
+ generator = torch.Generator()
2296
+ test_loader = DataLoader(testset, generator=generator, collate_fn=collate_fn, **val_loader_params)
2297
+ eval_fn = CustomEvalFn(**eval_func_params)
2298
+ analyzer = SpanErrorAnalyzer()
2299
+ my_model = IEModel(
2300
+ num_labels=len(label2id),
2301
+ **model_params
2302
+ )
2303
+ total_params = sum(p.numel() for p in my_model.parameters())
2304
+ print(f"Total params: {total_params:,}")
2305
+
2306
+ # %% [code]
2307
+ start_time = time.time()
2308
+
2309
+ best_score, best_analyze_result, best_pred_test = test(my_model, best_models, test_loader, eval_fn, analyzer, device, id2label, tokenizer)
2310
+ last_score, last_analyze_result, last_pred_test = test(my_model, last_models, test_loader, eval_fn, analyzer, device, id2label, tokenizer)
2311
+
2312
+ result_test = {"Best model": best_score, "Last model": last_score}
2313
+ analyze_result = {"Best model": best_analyze_result, "Last model": last_analyze_result}
2314
+ analyze_result_sumary = {"Best model": best_analyze_result['summary'], "Last model": last_analyze_result['summary']}
2315
+ pred_test = {"Best model": best_pred_test, "Last model": last_pred_test}
2316
+
2317
+ with open(f"{checkpoints_dir}/results/{state_dict_save_name}_test_{my_model.keep_neighbor}.json", "w", encoding="utf-8") as f:
2318
+ json.dump(dict_to_records(result_test), f, ensure_ascii=False, indent=2)
2319
+
2320
+ with open(f"{checkpoints_dir}/results/{state_dict_save_name}_error_analyze_result_{my_model.keep_neighbor}.json", "w", encoding="utf-8") as f:
2321
+ json.dump(analyze_result, f, ensure_ascii=False, indent=2)
2322
+
2323
+ with open(f"{checkpoints_dir}/results/{state_dict_save_name}_pred_test_{my_model.keep_neighbor}.json", "w", encoding="utf-8") as f:
2324
+ json.dump(pred_test, f, ensure_ascii=False, indent=2)
2325
+
2326
+ print('Test:', time.time() - start_time, 's --> Done!')
2327
+ print(json.dumps(analyze_result_sumary, ensure_ascii=False, indent=4))
2328
+
2329
+ # %% [code]
2330
+ result_test_df = dict_to_df(result_test, row_names=['keep_neightbor', 'alpha'])
2331
+
2332
+ col = ("Best model", "Ent-C", "f1")
2333
+ sorted_df = result_test_df.sort_values(
2334
+ by=col,
2335
+ ascending=False
2336
+ ).reset_index(drop=True)
2337
+ sorted_df.to_excel(f"{checkpoints_dir}/results/{state_dict_save_name}_test_df_.xlsx")
2338
+
2339
+ sorted_df
2340
+
2341
+ # %% [code]
2342
+ def get_avg_best_score(logs):
2343
+ return float(np.mean([list(log.values())[-1]['best_score'] for log in logs]))
2344
+
2345
+ def get_avg_log(logs, epochs):
2346
+ avg_log = {}
2347
+
2348
+ for epoch in range(1, epochs + 1):
2349
+ val_score = 0.0
2350
+ train_loss = 0.0
2351
+ n_eval = 0
2352
+
2353
+ for idx in range(len(logs)):
2354
+ log = logs[idx].get(epoch, logs[idx].get(str(epoch)))
2355
+ if log is None:
2356
+ continue
2357
+
2358
+ val_score += log.get('val_score', 0.0)
2359
+ train_loss += log.get('train_loss', 0.0)
2360
+ n_eval += 1
2361
+
2362
+ if n_eval == 0:
2363
+ continue
2364
+
2365
+ avg_log[epoch] = {
2366
+ 'train_loss': train_loss / n_eval,
2367
+ 'val_score': val_score / n_eval if val_score != 0 else float('inf')
2368
+ }
2369
+
2370
+ return avg_log
2371
+
2372
+ def parse_label_key(label: str):
2373
+ try:
2374
+ first = float(label.split('_', 1)[0]) # số đầu: trước dấu _
2375
+ last = float(re.findall(r'_(\d+(?:\.\d+)?)$', label)[0])
2376
+ return first, last
2377
+ except:
2378
+ return (0, 0)
2379
+
2380
+ def plot_training_logs(logs_dict, save_path=None, figsize=(24, 10)):
2381
+ fig, axes = plt.subplots(1, 2, figsize=figsize)
2382
+
2383
+ # ===== Plot Train Loss =====
2384
+ for name, log in logs_dict.items():
2385
+ epochs = sorted(log.keys())
2386
+ train_loss = [log[e]['train_loss'] for e in epochs]
2387
+ axes[0].plot(epochs, train_loss, label=name)
2388
+
2389
+ axes[0].set_xlabel('Epoch')
2390
+ axes[0].set_ylabel('Train Loss')
2391
+ axes[0].set_title('Training Loss')
2392
+ axes[0].grid(True)
2393
+
2394
+ # ===== Plot Validation Score =====
2395
+ for name, log in logs_dict.items():
2396
+ epochs = sorted(log.keys())
2397
+ val_score = [log[e]['val_score'] for e in epochs]
2398
+ axes[1].plot(epochs, val_score, label=name)
2399
+
2400
+ axes[1].set_xlabel('Epoch')
2401
+ axes[1].set_ylabel('Validation Score')
2402
+ axes[1].set_title('Validation Score')
2403
+ axes[1].grid(True)
2404
+
2405
+ # ===== Shared Legend =====
2406
+ handles, labels = axes[0].get_legend_handles_labels()
2407
+ pairs = list(zip(handles, labels))
2408
+ pairs_sorted = sorted(
2409
+ pairs,
2410
+ key=lambda x: parse_label_key(x[1])
2411
+ )
2412
+ handles_sorted, labels_sorted = zip(*pairs_sorted)
2413
+
2414
+ axes[0].legend(
2415
+ handles_sorted,
2416
+ labels_sorted,
2417
+ loc='center left',
2418
+ bbox_to_anchor=(1.01, 0.5),
2419
+ borderaxespad=0.
2420
+ )
2421
+
2422
+ plt.tight_layout(rect=[0, 0, 1, 1])
2423
+
2424
+ if save_path is not None:
2425
+ os.makedirs(os.path.dirname(save_path), exist_ok=True) if os.path.dirname(save_path) else None
2426
+ plt.savefig(save_path, dpi=300, bbox_inches='tight')
2427
+
2428
+ plt.show()
2429
+
2430
+ # %% [code]
2431
+ if not test_only:
2432
+ snapshot_download(repo_id=repo_name, local_dir="", repo_type="model", allow_patterns=["**/*ent*.json"], ignore_patterns=["**/*crf*.json"])
2433
+ get_ipython().system('rm -rf .cache .gitattributes')
2434
+
2435
+ # %% [code]
2436
+ if not test_only:
2437
+ experiments = {}
2438
+ for experiment in os.listdir(pretrained_dir):
2439
+ if '.virtual_documents' in experiment:
2440
+ continue
2441
+ experiment_logs = []
2442
+ try:
2443
+ for seed in SEEDS:
2444
+ for fold_idx in range(nfolds):
2445
+ with open(f"{pretrained_dir}/{experiment}/logs/{experiment}_s{seed}_f{fold_idx}_logging.json", "r", encoding="utf-8") as f:
2446
+ experiment_log = json.load(f)
2447
+ experiment_logs.append(experiment_log)
2448
+ except:
2449
+ pass
2450
+ experiments[experiment] = get_avg_log(experiment_logs, 1000)
2451
+ experiments[state_dict_save_name] = get_avg_log(training_logs, 1000)
2452
+
2453
+ # %% [code]
2454
+ if not test_only:
2455
+ score = get_avg_best_score(training_logs)
2456
+ state_dict_save_name, score
2457
+
2458
+ # %% [code]
2459
+ if not test_only:
2460
+ plot_training_logs(experiments, save_path=f'{checkpoints_dir}/logs/{state_dict_save_name}_log_plot.jpg', figsize=(18, 7.5))
2461
+
20_sampled_instead_all_27/lasts/20_sampled_instead_all_27_s26092004_f0_last_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e9aa05f51702a8b70ce1179e33c9aba02c1e1bff5928cd293e26cf73a03cb318
3
+ size 554300417
20_sampled_instead_all_27/logs/20_sampled_instead_all_27_log_plot.jpg ADDED

Git LFS Details

  • SHA256: 170a584cd9fea29a3a2e582bce991316e86b31c8da219d0a1a049d65aeb0efdb
  • Pointer size: 131 Bytes
  • Size of remote file: 611 kB
20_sampled_instead_all_27/logs/20_sampled_instead_all_27_s26092004_f0_logging.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"1": {"lr": [2e-05, 0.0005], "train_loss": 0.17227895557880402, "total": 0.17227896130104983, "span_loss": 0.03354588482485196, "start_loss": 0.06501491966695343, "end_loss": 0.07371815254463038}, "2": {"lr": [1.988303923565381e-05, 0.0004969282409784868], "train_loss": 0.12330415099859238, "total": 0.12330415063626676, "span_loss": 0.02212076416356794, "start_loss": 0.048158358834588105, "end_loss": 0.05302505535810203}, "3": {"lr": [1.9535036904803962e-05, 0.0004877886008156408], "train_loss": 0.11242742836475372, "total": 0.11242743162151952, "span_loss": 0.01987504612606554, "start_loss": 0.044473638475907455, "end_loss": 0.0480787171672482}, "4": {"lr": [1.8964561979789496e-05, 0.00047280612778499774], "train_loss": 0.10171417146921158, "total": 0.1017141752632188, "span_loss": 0.017819511750478727, "start_loss": 0.040544282796997275, "end_loss": 0.04335030501884345}, "5": {"lr": [1.8185661446562005e-05, 0.00045234974009654937], "train_loss": 0.0927867442369461, "total": 0.09278674309582867, "span_loss": 0.01617125654567081, "start_loss": 0.037246729689246784, "end_loss": 0.03936874619937596}, "6": {"lr": [1.7217514421272206e-05, 0.00042692314190604356], "train_loss": 0.08311714231967926, "total": 0.08311714014572562, "span_loss": 0.01446779591201603, "start_loss": 0.033587434959518235, "end_loss": 0.035061933795722124}, "7": {"lr": [1.60839598967785e-05, 0.00039715242044697206], "train_loss": 0.0741962268948555, "total": 0.0741962243086003, "span_loss": 0.012839413808670172, "start_loss": 0.030128747674591252, "end_loss": 0.031228195028374355}, "8": {"lr": [1.4812909747525698e-05, 0.00036377062968501693], "train_loss": 0.0661037415266037, "total": 0.06610373960252978, "span_loss": 0.011457064752807958, "start_loss": 0.026955717032418162, "end_loss": 0.027690932229619377, "val_score": 1.6797563083705749, "best_score": 1.6797563083705749, "new_best_model": true, "precision": 0.6389632553167847, "recall": 0.7321614328155798, "f1": 0.6809418612091477, "span_recall": 0.9988144471614261}, "9": {"lr": [1.3435661446562005e-05, 0.0003275997400965494], "train_loss": 0.058165181428194046, "total": 0.05816518187589523, "span_loss": 0.01012853725853414, "start_loss": 0.02376622284771411, "end_loss": 0.02427045162194531, "val_score": 1.6784999166762997, "best_score": 1.6797563083705749, "new_best_model": false, "precision": 0.640373542279751, "recall": 0.7277955480802685, "f1": 0.6798958680058531, "span_recall": 0.9986040486704476}, "10": {"lr": [1.1986127417882198e-05, 0.00028953039902753766], "train_loss": 0.05131537839770317, "total": 0.05131538011562631, "span_loss": 0.008984313589557714, "start_loss": 0.02099797231248799, "end_loss": 0.021333100610501678, "val_score": 1.678005947112328, "best_score": 1.6797563083705749, "new_best_model": false, "precision": 0.6422789063635552, "recall": 0.724766248005694, "f1": 0.6796310237655661, "span_recall": 0.9983749233467604}, "11": {"lr": [1.0500000000000003e-05, 0.0002505], "train_loss": 0.04478883370757103, "total": 0.04478883610016944, "span_loss": 0.007872595875006005, "start_loss": 0.01841730935537595, "end_loss": 0.018498934068248016, "val_score": 1.675686950342589, "best_score": 1.6797563083705749, "new_best_model": false, "precision": 0.6410831542487602, "recall": 0.7216001458881784, "f1": 0.6775633254545722, "span_recall": 0.9981236248880141}, "12": {"lr": [9.013872582117811e-06, 0.00021146960097246246], "train_loss": 0.039677880704402924, "total": 0.039677879542462186, "span_loss": 0.007003872670428989, "start_loss": 0.016325341315826535, "end_loss": 0.01634862930698725, "val_score": 1.6722811620991804, "best_score": 1.6797563083705749, "new_best_model": false, "precision": 0.6376183871458626, "recall": 0.7186833436626776, "f1": 0.67428818842995, "span_recall": 0.9979929736692309}, "13": {"lr": [7.564338553438001e-06, 0.00017340025990345064], "train_loss": 0.03519109636545181, "total": 0.03519109829369039, "span_loss": 0.006238062598973163, "start_loss": 0.014561909547126646, "end_loss": 0.01439108296837335, "val_score": 1.6707377344718177, "best_score": 1.6797563083705749, "new_best_model": false, "precision": 0.6382015844899864, "recall": 0.7150771458591428, "f1": 0.6730260372268573, "span_recall": 0.9977116972449595}, "14": {"lr": [6.1870902524743065e-06, 0.00013722937031498307], "train_loss": 0.031682197004556656, "total": 0.03168219731065933, "span_loss": 0.005610978823257199, "start_loss": 0.0131491473961836, "end_loss": 0.01292211533658927, "val_score": 1.6708828005388574, "best_score": 1.6797563083705749, "new_best_model": false, "precision": 0.6404085971966438, "recall": 0.7125181065572205, "f1": 0.6730599675942953, "span_recall": 0.9978228329445623}, "15": {"lr": [4.916040103221507e-06, 0.00010384757955302797], "train_loss": 0.02878335677087307, "total": 0.028783357896373016, "span_loss": 0.0051759087619600245, "start_loss": 0.01197102750860292, "end_loss": 0.011636452544261917, "val_score": 1.6717142791847495, "best_score": 1.6797563083705749, "new_best_model": false, "precision": 0.6432702606739119, "recall": 0.71059642436734, "f1": 0.6738150072539258, "span_recall": 0.9978992719308228}, "16": {"lr": [3.7824855787278e-06, 7.40768580939564e-05], "train_loss": 0.026410341262817383, "total": 0.026410341129548195, "span_loss": 0.004753220474473453, "start_loss": 0.01099412383947911, "end_loss": 0.010663008543284263, "val_score": 1.6701016233292525, "best_score": 1.6797563083705749, "new_best_model": false, "precision": 0.6431975736389699, "recall": 0.7074979200823861, "f1": 0.6723566187149261, "span_recall": 0.9977450046143247}, "17": {"lr": [2.814338553438001e-06, 4.865025990345063e-05], "train_loss": 0.024362513795495033, "total": 0.024362513977699004, "span_loss": 0.004425265523826296, "start_loss": 0.01006239096234803, "end_loss": 0.009874859890370078, "val_score": 1.6711249504723225, "best_score": 1.6797563083705749, "new_best_model": false, "precision": 0.6462378939908662, "recall": 0.7063522559316601, "f1": 0.6735009558004027, "span_recall": 0.997623994671919}, "18": {"lr": [2.0354380202105066e-06, 2.8193872215002235e-05], "train_loss": 0.022970767691731453, "total": 0.02297076784478279, "span_loss": 0.0041869684862250916, "start_loss": 0.009607393958836445, "end_loss": 0.00917639500472451, "val_score": 1.671219111969874, "best_score": 1.6797563083705749, "new_best_model": false, "precision": 0.6472923232247003, "recall": 0.705533895262806, "f1": 0.6736513573095361, "span_recall": 0.9975677546603362}}
20_sampled_instead_all_27/r1s/20_sampled_instead_all_27_s26092004_f0_r1_vs1.67976_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef88932e3abe3e67ae5ec06ac83edef395e6e6ad54cbae54b62f799047a9a718
3
+ size 554302217
20_sampled_instead_all_27/results/20_sampled_instead_all_27_error_analyze_result_2.json ADDED
The diff for this file is too large to render. See raw diff
 
20_sampled_instead_all_27/results/20_sampled_instead_all_27_pred_test_2.json ADDED
The diff for this file is too large to render. See raw diff
 
20_sampled_instead_all_27/results/20_sampled_instead_all_27_test_2.json ADDED
@@ -0,0 +1,1066 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "model": "Best model",
4
+ "levels": [
5
+ 0,
6
+ 0.0
7
+ ],
8
+ "metrics": {
9
+ "Ent-I": {
10
+ "precision": 0.5999190665673434,
11
+ "recall": 0.8267496979265482,
12
+ "f1": 0.6953021134718212
13
+ },
14
+ "Ent-C": {
15
+ "precision": 0.5286581254210865,
16
+ "recall": 0.7280156003336168,
17
+ "f1": 0.6125239218412405
18
+ }
19
+ }
20
+ },
21
+ {
22
+ "model": "Best model",
23
+ "levels": [
24
+ 1,
25
+ 0.0
26
+ ],
27
+ "metrics": {
28
+ "Ent-I": {
29
+ "precision": 0.5996629592176611,
30
+ "recall": 0.8268426433675742,
31
+ "f1": 0.6951629239377095
32
+ },
33
+ "Ent-C": {
34
+ "precision": 0.5283730961042402,
35
+ "recall": 0.7280156003336168,
36
+ "f1": 0.6123325604399427
37
+ }
38
+ }
39
+ },
40
+ {
41
+ "model": "Best model",
42
+ "levels": [
43
+ 2,
44
+ 0.0
45
+ ],
46
+ "metrics": {
47
+ "Ent-I": {
48
+ "precision": 0.5991379310340792,
49
+ "recall": 0.8268426433675742,
50
+ "f1": 0.6948100080140517
51
+ },
52
+ "Ent-C": {
53
+ "precision": 0.5279105784118726,
54
+ "recall": 0.7280156003336168,
55
+ "f1": 0.6120218530499476
56
+ }
57
+ }
58
+ },
59
+ {
60
+ "model": "Best model",
61
+ "levels": [
62
+ 3,
63
+ 0.0
64
+ ],
65
+ "metrics": {
66
+ "Ent-I": {
67
+ "precision": 0.5988019921923551,
68
+ "recall": 0.8269355888086002,
69
+ "f1": 0.6946168511215417
70
+ },
71
+ "Ent-C": {
72
+ "precision": 0.5276226364305715,
73
+ "recall": 0.7281084594663124,
74
+ "f1": 0.6118610954000913
75
+ }
76
+ }
77
+ },
78
+ {
79
+ "model": "Best model",
80
+ "levels": [
81
+ 0,
82
+ 0.2
83
+ ],
84
+ "metrics": {
85
+ "Ent-I": {
86
+ "precision": 0.6170962614880677,
87
+ "recall": 0.8300027883624592,
88
+ "f1": 0.7078874307002183
89
+ },
90
+ "Ent-C": {
91
+ "precision": 0.5459821737023796,
92
+ "recall": 0.7337728665607449,
93
+ "f1": 0.6260993533196694
94
+ }
95
+ }
96
+ },
97
+ {
98
+ "model": "Best model",
99
+ "levels": [
100
+ 1,
101
+ 0.2
102
+ ],
103
+ "metrics": {
104
+ "Ent-I": {
105
+ "precision": 0.6170962614880677,
106
+ "recall": 0.8300027883624592,
107
+ "f1": 0.7078874307002183
108
+ },
109
+ "Ent-C": {
110
+ "precision": 0.5459821737023796,
111
+ "recall": 0.7337728665607449,
112
+ "f1": 0.6260993533196694
113
+ }
114
+ }
115
+ },
116
+ {
117
+ "model": "Best model",
118
+ "levels": [
119
+ 2,
120
+ 0.2
121
+ ],
122
+ "metrics": {
123
+ "Ent-I": {
124
+ "precision": 0.617010985973456,
125
+ "recall": 0.8300027883624592,
126
+ "f1": 0.7078313204089742
127
+ },
128
+ "Ent-C": {
129
+ "precision": 0.5459067357509182,
130
+ "recall": 0.7337728665607449,
131
+ "f1": 0.6260497495043503
132
+ }
133
+ }
134
+ },
135
+ {
136
+ "model": "Best model",
137
+ "levels": [
138
+ 3,
139
+ 0.2
140
+ ],
141
+ "metrics": {
142
+ "Ent-I": {
143
+ "precision": 0.6168243663232151,
144
+ "recall": 0.8300957338034853,
145
+ "f1": 0.707742288475213
146
+ },
147
+ "Ent-C": {
148
+ "precision": 0.5457496029275977,
149
+ "recall": 0.7338657256934406,
150
+ "f1": 0.6259801931273657
151
+ }
152
+ }
153
+ },
154
+ {
155
+ "model": "Best model",
156
+ "levels": [
157
+ 0,
158
+ 0.4
159
+ ],
160
+ "metrics": {
161
+ "Ent-I": {
162
+ "precision": 0.6200124904582471,
163
+ "recall": 0.8304675155675895,
164
+ "f1": 0.709972184218721
165
+ },
166
+ "Ent-C": {
167
+ "precision": 0.5490250503084109,
168
+ "recall": 0.734701457887701,
169
+ "f1": 0.6284352611882962
170
+ }
171
+ }
172
+ },
173
+ {
174
+ "model": "Best model",
175
+ "levels": [
176
+ 1,
177
+ 0.4
178
+ ],
179
+ "metrics": {
180
+ "Ent-I": {
181
+ "precision": 0.6200124904582471,
182
+ "recall": 0.8304675155675895,
183
+ "f1": 0.709972184218721
184
+ },
185
+ "Ent-C": {
186
+ "precision": 0.5490250503084109,
187
+ "recall": 0.734701457887701,
188
+ "f1": 0.6284352611882962
189
+ }
190
+ }
191
+ },
192
+ {
193
+ "model": "Best model",
194
+ "levels": [
195
+ 2,
196
+ 0.4
197
+ ],
198
+ "metrics": {
199
+ "Ent-I": {
200
+ "precision": 0.6199694698857757,
201
+ "recall": 0.8304675155675895,
202
+ "f1": 0.709943978259964
203
+ },
204
+ "Ent-C": {
205
+ "precision": 0.5489869553146343,
206
+ "recall": 0.734701457887701,
207
+ "f1": 0.6284103044643836
208
+ }
209
+ }
210
+ },
211
+ {
212
+ "model": "Best model",
213
+ "levels": [
214
+ 3,
215
+ 0.4
216
+ ],
217
+ "metrics": {
218
+ "Ent-I": {
219
+ "precision": 0.6197974472803691,
220
+ "recall": 0.8304675155675895,
221
+ "f1": 0.7098311768328478
222
+ },
223
+ "Ent-C": {
224
+ "precision": 0.5488346281905182,
225
+ "recall": 0.734701457887701,
226
+ "f1": 0.6283104973874534
227
+ }
228
+ }
229
+ },
230
+ {
231
+ "model": "Best model",
232
+ "levels": [
233
+ 0,
234
+ 0.5
235
+ ],
236
+ "metrics": {
237
+ "Ent-I": {
238
+ "precision": 0.619295325287405,
239
+ "recall": 0.8299098429214332,
240
+ "f1": 0.7092981640687789
241
+ },
242
+ "Ent-C": {
243
+ "precision": 0.5486197808291381,
244
+ "recall": 0.7345157396223098,
245
+ "f1": 0.6281017936513165
246
+ }
247
+ }
248
+ },
249
+ {
250
+ "model": "Best model",
251
+ "levels": [
252
+ 1,
253
+ 0.5
254
+ ],
255
+ "metrics": {
256
+ "Ent-I": {
257
+ "precision": 0.619295325287405,
258
+ "recall": 0.8299098429214332,
259
+ "f1": 0.7092981640687789
260
+ },
261
+ "Ent-C": {
262
+ "precision": 0.5486197808291381,
263
+ "recall": 0.7345157396223098,
264
+ "f1": 0.6281017936513165
265
+ }
266
+ }
267
+ },
268
+ {
269
+ "model": "Best model",
270
+ "levels": [
271
+ 2,
272
+ 0.5
273
+ ],
274
+ "metrics": {
275
+ "Ent-I": {
276
+ "precision": 0.6192523753376661,
277
+ "recall": 0.8299098429214332,
278
+ "f1": 0.7092699927220587
279
+ },
280
+ "Ent-C": {
281
+ "precision": 0.5485817324359882,
282
+ "recall": 0.7345157396223098,
283
+ "f1": 0.6280768571022729
284
+ }
285
+ }
286
+ },
287
+ {
288
+ "model": "Best model",
289
+ "levels": [
290
+ 3,
291
+ 0.5
292
+ ],
293
+ "metrics": {
294
+ "Ent-I": {
295
+ "precision": 0.6192094313449242,
296
+ "recall": 0.8299098429214332,
297
+ "f1": 0.7092418236130245
298
+ },
299
+ "Ent-C": {
300
+ "precision": 0.548543689320008,
301
+ "recall": 0.7345157396223098,
302
+ "f1": 0.628051922533185
303
+ }
304
+ }
305
+ },
306
+ {
307
+ "model": "Best model",
308
+ "levels": [
309
+ 0,
310
+ 0.6
311
+ ],
312
+ "metrics": {
313
+ "Ent-I": {
314
+ "precision": 0.6153528399307295,
315
+ "recall": 0.8307463518906675,
316
+ "f1": 0.7070083798596167
317
+ },
318
+ "Ent-C": {
319
+ "precision": 0.5447160068843065,
320
+ "recall": 0.734701457887701,
321
+ "f1": 0.625602904890733
322
+ }
323
+ }
324
+ },
325
+ {
326
+ "model": "Best model",
327
+ "levels": [
328
+ 1,
329
+ 0.6
330
+ ],
331
+ "metrics": {
332
+ "Ent-I": {
333
+ "precision": 0.6153528399307295,
334
+ "recall": 0.8307463518906675,
335
+ "f1": 0.7070083798596167
336
+ },
337
+ "Ent-C": {
338
+ "precision": 0.5447160068843065,
339
+ "recall": 0.734701457887701,
340
+ "f1": 0.625602904890733
341
+ }
342
+ }
343
+ },
344
+ {
345
+ "model": "Best model",
346
+ "levels": [
347
+ 2,
348
+ 0.6
349
+ ],
350
+ "metrics": {
351
+ "Ent-I": {
352
+ "precision": 0.6153528399307295,
353
+ "recall": 0.8307463518906675,
354
+ "f1": 0.7070083798596167
355
+ },
356
+ "Ent-C": {
357
+ "precision": 0.5447160068843065,
358
+ "recall": 0.734701457887701,
359
+ "f1": 0.625602904890733
360
+ }
361
+ }
362
+ },
363
+ {
364
+ "model": "Best model",
365
+ "levels": [
366
+ 3,
367
+ 0.6
368
+ ],
369
+ "metrics": {
370
+ "Ent-I": {
371
+ "precision": 0.6153528399307295,
372
+ "recall": 0.8307463518906675,
373
+ "f1": 0.7070083798596167
374
+ },
375
+ "Ent-C": {
376
+ "precision": 0.5447160068843065,
377
+ "recall": 0.734701457887701,
378
+ "f1": 0.625602904890733
379
+ }
380
+ }
381
+ },
382
+ {
383
+ "model": "Best model",
384
+ "levels": [
385
+ 0,
386
+ 0.8
387
+ ],
388
+ "metrics": {
389
+ "Ent-I": {
390
+ "precision": 0.6078164363038008,
391
+ "recall": 0.8297239520393812,
392
+ "f1": 0.7016426894516907
393
+ },
394
+ "Ent-C": {
395
+ "precision": 0.538094913869042,
396
+ "recall": 0.7338657256934406,
397
+ "f1": 0.6209145142882909
398
+ }
399
+ }
400
+ },
401
+ {
402
+ "model": "Best model",
403
+ "levels": [
404
+ 1,
405
+ 0.8
406
+ ],
407
+ "metrics": {
408
+ "Ent-I": {
409
+ "precision": 0.6078164363038008,
410
+ "recall": 0.8297239520393812,
411
+ "f1": 0.7016426894516907
412
+ },
413
+ "Ent-C": {
414
+ "precision": 0.538094913869042,
415
+ "recall": 0.7338657256934406,
416
+ "f1": 0.6209145142882909
417
+ }
418
+ }
419
+ },
420
+ {
421
+ "model": "Best model",
422
+ "levels": [
423
+ 2,
424
+ 0.8
425
+ ],
426
+ "metrics": {
427
+ "Ent-I": {
428
+ "precision": 0.6078164363038008,
429
+ "recall": 0.8297239520393812,
430
+ "f1": 0.7016426894516907
431
+ },
432
+ "Ent-C": {
433
+ "precision": 0.538094913869042,
434
+ "recall": 0.7338657256934406,
435
+ "f1": 0.6209145142882909
436
+ }
437
+ }
438
+ },
439
+ {
440
+ "model": "Best model",
441
+ "levels": [
442
+ 3,
443
+ 0.8
444
+ ],
445
+ "metrics": {
446
+ "Ent-I": {
447
+ "precision": 0.6078164363038008,
448
+ "recall": 0.8297239520393812,
449
+ "f1": 0.7016426894516907
450
+ },
451
+ "Ent-C": {
452
+ "precision": 0.538094913869042,
453
+ "recall": 0.7338657256934406,
454
+ "f1": 0.6209145142882909
455
+ }
456
+ }
457
+ },
458
+ {
459
+ "model": "Best model",
460
+ "levels": [
461
+ 0,
462
+ 1.0
463
+ ],
464
+ "metrics": {
465
+ "Ent-I": {
466
+ "precision": 0.5954463510712455,
467
+ "recall": 0.828887443070147,
468
+ "f1": 0.6930369861191593
469
+ },
470
+ "Ent-C": {
471
+ "precision": 0.5274086933294202,
472
+ "recall": 0.733494289162658,
473
+ "f1": 0.6136098762796772
474
+ }
475
+ }
476
+ },
477
+ {
478
+ "model": "Best model",
479
+ "levels": [
480
+ 1,
481
+ 1.0
482
+ ],
483
+ "metrics": {
484
+ "Ent-I": {
485
+ "precision": 0.5954463510712455,
486
+ "recall": 0.828887443070147,
487
+ "f1": 0.6930369861191593
488
+ },
489
+ "Ent-C": {
490
+ "precision": 0.5274086933294202,
491
+ "recall": 0.733494289162658,
492
+ "f1": 0.6136098762796772
493
+ }
494
+ }
495
+ },
496
+ {
497
+ "model": "Best model",
498
+ "levels": [
499
+ 2,
500
+ 1.0
501
+ ],
502
+ "metrics": {
503
+ "Ent-I": {
504
+ "precision": 0.5954463510712455,
505
+ "recall": 0.828887443070147,
506
+ "f1": 0.6930369861191593
507
+ },
508
+ "Ent-C": {
509
+ "precision": 0.5274086933294202,
510
+ "recall": 0.733494289162658,
511
+ "f1": 0.6136098762796772
512
+ }
513
+ }
514
+ },
515
+ {
516
+ "model": "Best model",
517
+ "levels": [
518
+ 3,
519
+ 1.0
520
+ ],
521
+ "metrics": {
522
+ "Ent-I": {
523
+ "precision": 0.5954463510712455,
524
+ "recall": 0.828887443070147,
525
+ "f1": 0.6930369861191593
526
+ },
527
+ "Ent-C": {
528
+ "precision": 0.5274086933294202,
529
+ "recall": 0.733494289162658,
530
+ "f1": 0.6136098762796772
531
+ }
532
+ }
533
+ },
534
+ {
535
+ "model": "Last model",
536
+ "levels": [
537
+ 0,
538
+ 0.0
539
+ ],
540
+ "metrics": {
541
+ "Ent-I": {
542
+ "precision": 0.6682224507549496,
543
+ "recall": 0.7851101403468862,
544
+ "f1": 0.7219658069975378
545
+ },
546
+ "Ent-C": {
547
+ "precision": 0.5878025628851543,
548
+ "recall": 0.6900362150611105,
549
+ "f1": 0.6348297759037013
550
+ }
551
+ }
552
+ },
553
+ {
554
+ "model": "Last model",
555
+ "levels": [
556
+ 1,
557
+ 0.0
558
+ ],
559
+ "metrics": {
560
+ "Ent-I": {
561
+ "precision": 0.6680110715692621,
562
+ "recall": 0.7851101403468862,
563
+ "f1": 0.7218424151309808
564
+ },
565
+ "Ent-C": {
566
+ "precision": 0.5876166376715264,
567
+ "recall": 0.6900362150611105,
568
+ "f1": 0.6347213275107678
569
+ }
570
+ }
571
+ },
572
+ {
573
+ "model": "Last model",
574
+ "levels": [
575
+ 2,
576
+ 0.0
577
+ ],
578
+ "metrics": {
579
+ "Ent-I": {
580
+ "precision": 0.6679313888224899,
581
+ "recall": 0.7853889766699642,
582
+ "f1": 0.7219137071208935
583
+ },
584
+ "Ent-C": {
585
+ "precision": 0.5875750869423114,
586
+ "recall": 0.6903147924591974,
587
+ "f1": 0.6348149047282035
588
+ }
589
+ }
590
+ },
591
+ {
592
+ "model": "Last model",
593
+ "levels": [
594
+ 3,
595
+ 0.0
596
+ ],
597
+ "metrics": {
598
+ "Ent-I": {
599
+ "precision": 0.6676410175377882,
600
+ "recall": 0.7854819221109903,
601
+ "f1": 0.7217833148426597
602
+ },
603
+ "Ent-C": {
604
+ "precision": 0.5873291729199879,
605
+ "recall": 0.690407651591893,
606
+ "f1": 0.6347105977296253
607
+ }
608
+ }
609
+ },
610
+ {
611
+ "model": "Last model",
612
+ "levels": [
613
+ 0,
614
+ 0.2
615
+ ],
616
+ "metrics": {
617
+ "Ent-I": {
618
+ "precision": 0.6629535081607001,
619
+ "recall": 0.796542429593088,
620
+ "f1": 0.7236342093450867
621
+ },
622
+ "Ent-C": {
623
+ "precision": 0.5849319306926168,
624
+ "recall": 0.702200761444236,
625
+ "f1": 0.6382242428360448
626
+ }
627
+ }
628
+ },
629
+ {
630
+ "model": "Last model",
631
+ "levels": [
632
+ 1,
633
+ 0.2
634
+ ],
635
+ "metrics": {
636
+ "Ent-I": {
637
+ "precision": 0.6629022277222595,
638
+ "recall": 0.796542429593088,
639
+ "f1": 0.7236036594986108
640
+ },
641
+ "Ent-C": {
642
+ "precision": 0.5848866888385916,
643
+ "recall": 0.702200761444236,
644
+ "f1": 0.638197311270218
645
+ }
646
+ }
647
+ },
648
+ {
649
+ "model": "Last model",
650
+ "levels": [
651
+ 2,
652
+ 0.2
653
+ ],
654
+ "metrics": {
655
+ "Ent-I": {
656
+ "precision": 0.6629031010744235,
657
+ "recall": 0.7967283204751401,
658
+ "f1": 0.7236808730490173
659
+ },
660
+ "Ent-C": {
661
+ "precision": 0.5849056603769062,
662
+ "recall": 0.7023864797096272,
663
+ "f1": 0.6382852994586402
664
+ }
665
+ }
666
+ },
667
+ {
668
+ "model": "Last model",
669
+ "levels": [
670
+ 3,
671
+ 0.2
672
+ ],
673
+ "metrics": {
674
+ "Ent-I": {
675
+ "precision": 0.6628005876434989,
676
+ "recall": 0.7967283204751401,
677
+ "f1": 0.723619782311454
678
+ },
679
+ "Ent-C": {
680
+ "precision": 0.5848152157100782,
681
+ "recall": 0.7023864797096272,
682
+ "f1": 0.6382314425372728
683
+ }
684
+ }
685
+ },
686
+ {
687
+ "model": "Last model",
688
+ "levels": [
689
+ 0,
690
+ 0.4
691
+ ],
692
+ "metrics": {
693
+ "Ent-I": {
694
+ "precision": 0.6478767380679084,
695
+ "recall": 0.8011897016443896,
696
+ "f1": 0.7164228673957997
697
+ },
698
+ "Ent-C": {
699
+ "precision": 0.5704945137527653,
700
+ "recall": 0.7048936762924088,
701
+ "f1": 0.6306126637985097
702
+ }
703
+ }
704
+ },
705
+ {
706
+ "model": "Last model",
707
+ "levels": [
708
+ 1,
709
+ 0.4
710
+ ],
711
+ "metrics": {
712
+ "Ent-I": {
713
+ "precision": 0.6478767380679084,
714
+ "recall": 0.8011897016443896,
715
+ "f1": 0.7164228673957997
716
+ },
717
+ "Ent-C": {
718
+ "precision": 0.5704945137527653,
719
+ "recall": 0.7048936762924088,
720
+ "f1": 0.6306126637985097
721
+ }
722
+ }
723
+ },
724
+ {
725
+ "model": "Last model",
726
+ "levels": [
727
+ 2,
728
+ 0.4
729
+ ],
730
+ "metrics": {
731
+ "Ent-I": {
732
+ "precision": 0.6478545126620215,
733
+ "recall": 0.8012826470854156,
734
+ "f1": 0.7164464340149808
735
+ },
736
+ "Ent-C": {
737
+ "precision": 0.5704839194465204,
738
+ "recall": 0.7049865354251045,
739
+ "f1": 0.6306433476322265
740
+ }
741
+ }
742
+ },
743
+ {
744
+ "model": "Last model",
745
+ "levels": [
746
+ 3,
747
+ 0.4
748
+ ],
749
+ "metrics": {
750
+ "Ent-I": {
751
+ "precision": 0.6478545126620215,
752
+ "recall": 0.8012826470854156,
753
+ "f1": 0.7164464340149808
754
+ },
755
+ "Ent-C": {
756
+ "precision": 0.5704839194465204,
757
+ "recall": 0.7049865354251045,
758
+ "f1": 0.6306433476322265
759
+ }
760
+ }
761
+ },
762
+ {
763
+ "model": "Last model",
764
+ "levels": [
765
+ 0,
766
+ 0.5
767
+ ],
768
+ "metrics": {
769
+ "Ent-I": {
770
+ "precision": 0.6429740994338768,
771
+ "recall": 0.8029556650238842,
772
+ "f1": 0.7141144815247642
773
+ },
774
+ "Ent-C": {
775
+ "precision": 0.5662722333850069,
776
+ "recall": 0.7065651406809299,
777
+ "f1": 0.6286870974315363
778
+ }
779
+ }
780
+ },
781
+ {
782
+ "model": "Last model",
783
+ "levels": [
784
+ 1,
785
+ 0.5
786
+ ],
787
+ "metrics": {
788
+ "Ent-I": {
789
+ "precision": 0.6429740994338768,
790
+ "recall": 0.8029556650238842,
791
+ "f1": 0.7141144815247642
792
+ },
793
+ "Ent-C": {
794
+ "precision": 0.5662722333850069,
795
+ "recall": 0.7065651406809299,
796
+ "f1": 0.6286870974315363
797
+ }
798
+ }
799
+ },
800
+ {
801
+ "model": "Last model",
802
+ "levels": [
803
+ 2,
804
+ 0.5
805
+ ],
806
+ "metrics": {
807
+ "Ent-I": {
808
+ "precision": 0.6429740994338768,
809
+ "recall": 0.8029556650238842,
810
+ "f1": 0.7141144815247642
811
+ },
812
+ "Ent-C": {
813
+ "precision": 0.5662722333850069,
814
+ "recall": 0.7065651406809299,
815
+ "f1": 0.6286870974315363
816
+ }
817
+ }
818
+ },
819
+ {
820
+ "model": "Last model",
821
+ "levels": [
822
+ 3,
823
+ 0.5
824
+ ],
825
+ "metrics": {
826
+ "Ent-I": {
827
+ "precision": 0.6429740994338768,
828
+ "recall": 0.8029556650238842,
829
+ "f1": 0.7141144815247642
830
+ },
831
+ "Ent-C": {
832
+ "precision": 0.5662722333850069,
833
+ "recall": 0.7065651406809299,
834
+ "f1": 0.6286870974315363
835
+ }
836
+ }
837
+ },
838
+ {
839
+ "model": "Last model",
840
+ "levels": [
841
+ 0,
842
+ 0.6
843
+ ],
844
+ "metrics": {
845
+ "Ent-I": {
846
+ "precision": 0.6362900257632416,
847
+ "recall": 0.8034203922290143,
848
+ "f1": 0.710154447909386
849
+ },
850
+ "Ent-C": {
851
+ "precision": 0.5601354335341086,
852
+ "recall": 0.7066579998136255,
853
+ "f1": 0.6249230088212537
854
+ }
855
+ }
856
+ },
857
+ {
858
+ "model": "Last model",
859
+ "levels": [
860
+ 1,
861
+ 0.6
862
+ ],
863
+ "metrics": {
864
+ "Ent-I": {
865
+ "precision": 0.6362900257632416,
866
+ "recall": 0.8034203922290143,
867
+ "f1": 0.710154447909386
868
+ },
869
+ "Ent-C": {
870
+ "precision": 0.5601354335341086,
871
+ "recall": 0.7066579998136255,
872
+ "f1": 0.6249230088212537
873
+ }
874
+ }
875
+ },
876
+ {
877
+ "model": "Last model",
878
+ "levels": [
879
+ 2,
880
+ 0.6
881
+ ],
882
+ "metrics": {
883
+ "Ent-I": {
884
+ "precision": 0.6362900257632416,
885
+ "recall": 0.8034203922290143,
886
+ "f1": 0.710154447909386
887
+ },
888
+ "Ent-C": {
889
+ "precision": 0.5601354335341086,
890
+ "recall": 0.7066579998136255,
891
+ "f1": 0.6249230088212537
892
+ }
893
+ }
894
+ },
895
+ {
896
+ "model": "Last model",
897
+ "levels": [
898
+ 3,
899
+ 0.6
900
+ ],
901
+ "metrics": {
902
+ "Ent-I": {
903
+ "precision": 0.6362900257632416,
904
+ "recall": 0.8034203922290143,
905
+ "f1": 0.710154447909386
906
+ },
907
+ "Ent-C": {
908
+ "precision": 0.5601354335341086,
909
+ "recall": 0.7066579998136255,
910
+ "f1": 0.6249230088212537
911
+ }
912
+ }
913
+ },
914
+ {
915
+ "model": "Last model",
916
+ "levels": [
917
+ 0,
918
+ 0.8
919
+ ],
920
+ "metrics": {
921
+ "Ent-I": {
922
+ "precision": 0.6151713351339292,
923
+ "recall": 0.8042569011982487,
924
+ "f1": 0.697119833960271
925
+ },
926
+ "Ent-C": {
927
+ "precision": 0.5411957062625,
928
+ "recall": 0.7069365772117123,
929
+ "f1": 0.6130616797389864
930
+ }
931
+ }
932
+ },
933
+ {
934
+ "model": "Last model",
935
+ "levels": [
936
+ 1,
937
+ 0.8
938
+ ],
939
+ "metrics": {
940
+ "Ent-I": {
941
+ "precision": 0.6151713351339292,
942
+ "recall": 0.8042569011982487,
943
+ "f1": 0.697119833960271
944
+ },
945
+ "Ent-C": {
946
+ "precision": 0.5411957062625,
947
+ "recall": 0.7069365772117123,
948
+ "f1": 0.6130616797389864
949
+ }
950
+ }
951
+ },
952
+ {
953
+ "model": "Last model",
954
+ "levels": [
955
+ 2,
956
+ 0.8
957
+ ],
958
+ "metrics": {
959
+ "Ent-I": {
960
+ "precision": 0.6151713351339292,
961
+ "recall": 0.8042569011982487,
962
+ "f1": 0.697119833960271
963
+ },
964
+ "Ent-C": {
965
+ "precision": 0.5411957062625,
966
+ "recall": 0.7069365772117123,
967
+ "f1": 0.6130616797389864
968
+ }
969
+ }
970
+ },
971
+ {
972
+ "model": "Last model",
973
+ "levels": [
974
+ 3,
975
+ 0.8
976
+ ],
977
+ "metrics": {
978
+ "Ent-I": {
979
+ "precision": 0.6151713351339292,
980
+ "recall": 0.8042569011982487,
981
+ "f1": 0.697119833960271
982
+ },
983
+ "Ent-C": {
984
+ "precision": 0.5411957062625,
985
+ "recall": 0.7069365772117123,
986
+ "f1": 0.6130616797389864
987
+ }
988
+ }
989
+ },
990
+ {
991
+ "model": "Last model",
992
+ "levels": [
993
+ 0,
994
+ 1.0
995
+ ],
996
+ "metrics": {
997
+ "Ent-I": {
998
+ "precision": 0.5958734525442945,
999
+ "recall": 0.8052793010495349,
1000
+ "f1": 0.6849282531450533
1001
+ },
1002
+ "Ent-C": {
1003
+ "precision": 0.5238291726837743,
1004
+ "recall": 0.7073080137424947,
1005
+ "f1": 0.601896478713896
1006
+ }
1007
+ }
1008
+ },
1009
+ {
1010
+ "model": "Last model",
1011
+ "levels": [
1012
+ 1,
1013
+ 1.0
1014
+ ],
1015
+ "metrics": {
1016
+ "Ent-I": {
1017
+ "precision": 0.5958734525442945,
1018
+ "recall": 0.8052793010495349,
1019
+ "f1": 0.6849282531450533
1020
+ },
1021
+ "Ent-C": {
1022
+ "precision": 0.5238291726837743,
1023
+ "recall": 0.7073080137424947,
1024
+ "f1": 0.601896478713896
1025
+ }
1026
+ }
1027
+ },
1028
+ {
1029
+ "model": "Last model",
1030
+ "levels": [
1031
+ 2,
1032
+ 1.0
1033
+ ],
1034
+ "metrics": {
1035
+ "Ent-I": {
1036
+ "precision": 0.5958734525442945,
1037
+ "recall": 0.8052793010495349,
1038
+ "f1": 0.6849282531450533
1039
+ },
1040
+ "Ent-C": {
1041
+ "precision": 0.5238291726837743,
1042
+ "recall": 0.7073080137424947,
1043
+ "f1": 0.601896478713896
1044
+ }
1045
+ }
1046
+ },
1047
+ {
1048
+ "model": "Last model",
1049
+ "levels": [
1050
+ 3,
1051
+ 1.0
1052
+ ],
1053
+ "metrics": {
1054
+ "Ent-I": {
1055
+ "precision": 0.5958734525442945,
1056
+ "recall": 0.8052793010495349,
1057
+ "f1": 0.6849282531450533
1058
+ },
1059
+ "Ent-C": {
1060
+ "precision": 0.5238291726837743,
1061
+ "recall": 0.7073080137424947,
1062
+ "f1": 0.601896478713896
1063
+ }
1064
+ }
1065
+ }
1066
+ ]
20_sampled_instead_all_27/results/20_sampled_instead_all_27_test_df_.xlsx ADDED
Binary file (8.54 kB). View file