Upload 0_token_base_1's state dict
Browse files- .gitattributes +1 -0
- 0_token_base_1/0_token_base_1.py +1584 -0
- 0_token_base_1/lasts/0_token_base_1_s26092004_f0_last_ema.pth +3 -0
- 0_token_base_1/logs/0_token_base_1_log_plot.jpg +3 -0
- 0_token_base_1/logs/0_token_base_1_s26092004_f0_logging.json +1 -0
- 0_token_base_1/r1s/0_token_base_1_s26092004_f0_r1_vs0.61733_ema.pth +3 -0
- 0_token_base_1/results/0_token_base_1_error_analyze_result.json +0 -0
- 0_token_base_1/results/0_token_base_1_pred_test.json +0 -0
- 0_token_base_1/results/0_token_base_1_test.json +26 -0
- 0_token_base_1/results/0_token_base_1_test_df.xlsx +0 -0
- 0_token_base_1/results/0_token_base_1_test_df_best.xlsx +0 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
0_token_base_1/logs/0_token_base_1_log_plot.jpg filter=lfs diff=lfs merge=lfs -text
|
0_token_base_1/0_token_base_1.py
ADDED
|
@@ -0,0 +1,1584 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# %% [code]
|
| 2 |
+
get_ipython().system('pip install evaluate seqeval underthesea positional-encodings[pytorch]')
|
| 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 |
+
|
| 19 |
+
from sklearn.metrics import f1_score
|
| 20 |
+
from sklearn.preprocessing import MinMaxScaler, StandardScaler
|
| 21 |
+
from scipy.spatial.transform import Rotation as R
|
| 22 |
+
from sklearn.model_selection import KFold, StratifiedGroupKFold, GroupKFold, StratifiedKFold
|
| 23 |
+
from sklearn.metrics import precision_recall_fscore_support
|
| 24 |
+
from timm.utils import ModelEmaV3
|
| 25 |
+
import timm
|
| 26 |
+
|
| 27 |
+
import os
|
| 28 |
+
import gc
|
| 29 |
+
import json
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
import pickle
|
| 32 |
+
from tqdm.auto import tqdm
|
| 33 |
+
import copy
|
| 34 |
+
import numpy as np
|
| 35 |
+
import pandas as pd
|
| 36 |
+
import polars as pl
|
| 37 |
+
from PIL import Image
|
| 38 |
+
import time
|
| 39 |
+
from tqdm import tqdm
|
| 40 |
+
from matplotlib import pyplot as plt
|
| 41 |
+
import seaborn as sns
|
| 42 |
+
from multiprocessing import Manager as MemoryManager
|
| 43 |
+
from functools import lru_cache
|
| 44 |
+
import shutil
|
| 45 |
+
import glob
|
| 46 |
+
import cv2
|
| 47 |
+
import random
|
| 48 |
+
import re
|
| 49 |
+
import joblib
|
| 50 |
+
import math
|
| 51 |
+
from huggingface_hub import HfApi, snapshot_download
|
| 52 |
+
import evaluate
|
| 53 |
+
from underthesea import word_tokenize as vi_tokenize_tool
|
| 54 |
+
import spacy
|
| 55 |
+
en_tokenize_tool = spacy.load("en_core_web_sm")
|
| 56 |
+
from collections import defaultdict, Counter
|
| 57 |
+
|
| 58 |
+
# %% [code]
|
| 59 |
+
# Global config
|
| 60 |
+
SEEDS = [26092004]
|
| 61 |
+
topk = 1
|
| 62 |
+
nfolds = 5
|
| 63 |
+
only_fold_idx = 0
|
| 64 |
+
test_only = 0
|
| 65 |
+
debug_only = 0
|
| 66 |
+
|
| 67 |
+
# Config thư mục
|
| 68 |
+
dataset = 'kltn/only_entities' # conll003, ontonotes, phoner, vietbio, vietmed, vimed, kltn/only_entities, kltn/raw
|
| 69 |
+
root_dir = f'/kaggle/input/notebooks/sambui22022517/kltn-data/{dataset}' ## Thư mục chứa file train, val, test
|
| 70 |
+
train_dir = f'{root_dir}'
|
| 71 |
+
# val_dir = f'{root_dir}/val'
|
| 72 |
+
test_dir = f'{root_dir}'
|
| 73 |
+
|
| 74 |
+
# Config checkpoints
|
| 75 |
+
|
| 76 |
+
# Config training
|
| 77 |
+
epochs = 18 if not debug_only else 2
|
| 78 |
+
batch_size = 16
|
| 79 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 80 |
+
# # Thêm biến toàn cục nào đó vào đây
|
| 81 |
+
repo_name = 'SS3M/kltn-experiments'
|
| 82 |
+
state_dict_save_name = "0_token_base_1"
|
| 83 |
+
checkpoints_dir = state_dict_save_name
|
| 84 |
+
pretrained_dir = "/kaggle/working"
|
| 85 |
+
os.makedirs(f'{checkpoints_dir}', exist_ok=True)
|
| 86 |
+
|
| 87 |
+
backbone_model_name = "bert-base-uncased" if dataset in ["conll003", "ontonotes"] else "vinai/phobert-base"
|
| 88 |
+
word_tokenize = lambda text: [token.text for token in en_tokenize_tool(text)] if dataset == dataset in ["conll003", "ontonotes"] else vi_tokenize_tool(text)
|
| 89 |
+
max_len_dict = {
|
| 90 |
+
'kltn/raw': 256,
|
| 91 |
+
'kltn/only_entities': 68,
|
| 92 |
+
'conll003': 46,
|
| 93 |
+
'ontonotes': 61,
|
| 94 |
+
'phoner': 68,
|
| 95 |
+
'vietbio': 125,
|
| 96 |
+
'vietmed': 36,
|
| 97 |
+
'vimed': 100,
|
| 98 |
+
}
|
| 99 |
+
zero_entities_rate_dict = {
|
| 100 |
+
'kltn/raw': 1000,
|
| 101 |
+
'kltn/only_entities': 0.2,
|
| 102 |
+
'conll003': 1000, # mean keep all zero-entities samples
|
| 103 |
+
'ontonotes': 1000,
|
| 104 |
+
'phoner': 1000,
|
| 105 |
+
'vietbio': 1000,
|
| 106 |
+
'vietmed': 1000,
|
| 107 |
+
'vimed': 1000,
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
max_len = max_len_dict[dataset]
|
| 111 |
+
max_n_parts = 1
|
| 112 |
+
max_span_len = 10
|
| 113 |
+
zero_entities_rate = zero_entities_rate_dict[dataset]
|
| 114 |
+
|
| 115 |
+
# Trainer
|
| 116 |
+
trainer_params = {
|
| 117 |
+
"training_time": "00:11:30:00",
|
| 118 |
+
"eval_mode": "max",
|
| 119 |
+
"topk": topk,
|
| 120 |
+
"save_name": state_dict_save_name,
|
| 121 |
+
"save_best": True,
|
| 122 |
+
"save_last": True,
|
| 123 |
+
"device": device,
|
| 124 |
+
"logging": True,
|
| 125 |
+
"logging_file": True,
|
| 126 |
+
"checkpoints_dir": checkpoints_dir,
|
| 127 |
+
"early_stopping": 30,
|
| 128 |
+
"eval_from_ratio": 0.4,
|
| 129 |
+
"eval_every": 1,
|
| 130 |
+
"schedule_in_step": False,
|
| 131 |
+
"use_ema": True,
|
| 132 |
+
"ema_from_ratio": 0.3,
|
| 133 |
+
"ema_decay": 0.9995,
|
| 134 |
+
"max_grad_norm": 200.0,
|
| 135 |
+
"return_best": True,
|
| 136 |
+
"return_last": True,
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
# Memory
|
| 140 |
+
train_memory_params = {
|
| 141 |
+
'max_len': max_len,
|
| 142 |
+
'max_n_parts': max_n_parts,
|
| 143 |
+
}
|
| 144 |
+
val_memory_params = {
|
| 145 |
+
'max_len': max_len,
|
| 146 |
+
'max_n_parts': max_n_parts,
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
# Data Loader
|
| 150 |
+
def seed_worker(worker_id):
|
| 151 |
+
worker_seed = torch.initial_seed() % 2**32
|
| 152 |
+
np.random.seed(worker_seed)
|
| 153 |
+
random.seed(worker_seed)
|
| 154 |
+
|
| 155 |
+
train_loader_params = {
|
| 156 |
+
'batch_size': batch_size,
|
| 157 |
+
'shuffle': True,
|
| 158 |
+
'pin_memory':True,
|
| 159 |
+
'num_workers': 2,
|
| 160 |
+
'drop_last': False,
|
| 161 |
+
'worker_init_fn': seed_worker,
|
| 162 |
+
'persistent_workers': False,
|
| 163 |
+
}
|
| 164 |
+
val_loader_params = {
|
| 165 |
+
'batch_size': batch_size,
|
| 166 |
+
'shuffle': False,
|
| 167 |
+
'pin_memory':True,
|
| 168 |
+
'num_workers': 1,
|
| 169 |
+
'drop_last': False,
|
| 170 |
+
'worker_init_fn': seed_worker,
|
| 171 |
+
'persistent_workers': False,
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
# Model
|
| 175 |
+
model_params = {
|
| 176 |
+
'backbone_model_name': backbone_model_name,
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
# Loss Func
|
| 180 |
+
loss_func_params = {
|
| 181 |
+
'lambda_ce': 1.0,
|
| 182 |
+
}
|
| 183 |
+
eval_func_params = {}
|
| 184 |
+
|
| 185 |
+
# Optim
|
| 186 |
+
optim_params = {
|
| 187 |
+
'name': 'AdamW',
|
| 188 |
+
'lr': 1e-4,
|
| 189 |
+
'weight_decay': 1e-4,
|
| 190 |
+
}
|
| 191 |
+
scheduler_params = {
|
| 192 |
+
'name': 'CosineAnnealingLR',
|
| 193 |
+
'T_max': 20, # Số epoch để hoàn thành một chu kỳ giảm LR
|
| 194 |
+
'eta_min': 1e-6 # Learning rate nhỏ nhất trong chu kỳ
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
# %% [code]
|
| 198 |
+
def set_seed(seed=42):
|
| 199 |
+
random.seed(seed)
|
| 200 |
+
np.random.seed(seed)
|
| 201 |
+
torch.manual_seed(seed)
|
| 202 |
+
torch.cuda.manual_seed(seed)
|
| 203 |
+
torch.cuda.manual_seed_all(seed) # if using multi-GPU
|
| 204 |
+
torch.use_deterministic_algorithms(False)
|
| 205 |
+
torch.backends.cudnn.deterministic = True
|
| 206 |
+
torch.backends.cudnn.benchmark = False
|
| 207 |
+
os.environ['PYTHONHASHSEED'] = str(seed)
|
| 208 |
+
|
| 209 |
+
# %% [code]
|
| 210 |
+
class CustomLoss(nn.Module):
|
| 211 |
+
def __init__(self, lambda_ce=1.0):
|
| 212 |
+
super().__init__()
|
| 213 |
+
self.lambda_ce = lambda_ce
|
| 214 |
+
self.ce = nn.CrossEntropyLoss(ignore_index=-100)
|
| 215 |
+
|
| 216 |
+
def forward(
|
| 217 |
+
self,
|
| 218 |
+
logits, labels,
|
| 219 |
+
):
|
| 220 |
+
device = logits.device
|
| 221 |
+
|
| 222 |
+
# ===== TRG CE =====
|
| 223 |
+
B, L, C = logits.shape
|
| 224 |
+
logits_flat = logits.view(B * L, C)
|
| 225 |
+
labels_flat = labels.view(-1)
|
| 226 |
+
|
| 227 |
+
loss = self.ce(logits_flat, labels_flat) # (B*N,)
|
| 228 |
+
|
| 229 |
+
return {
|
| 230 |
+
"total": loss,
|
| 231 |
+
"ce_loss": loss,
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
# %% [code]
|
| 235 |
+
## Viết eval_fn vào đây
|
| 236 |
+
|
| 237 |
+
# Bỏ hết eval_fn và trọng số vào đây
|
| 238 |
+
class CustomEvalFn(nn.Module):
|
| 239 |
+
def __init__(self):
|
| 240 |
+
super().__init__()
|
| 241 |
+
|
| 242 |
+
def compute_f1(self, tp, fp, fn):
|
| 243 |
+
precision = tp / (tp + fp + 1e-8)
|
| 244 |
+
recall = tp / (tp + fn + 1e-8)
|
| 245 |
+
f1 = 2 * precision * recall / (precision + recall + 1e-8)
|
| 246 |
+
return precision, recall, f1
|
| 247 |
+
|
| 248 |
+
def forward(self, pred, gold):
|
| 249 |
+
pred_set = set(pred)
|
| 250 |
+
gold_set = set(gold)
|
| 251 |
+
|
| 252 |
+
tp = len(pred_set & gold_set)
|
| 253 |
+
fp = len(pred_set - gold_set)
|
| 254 |
+
fn = len(gold_set - pred_set)
|
| 255 |
+
|
| 256 |
+
precision, recall, f1 = self.compute_f1(tp, fp, fn)
|
| 257 |
+
|
| 258 |
+
return {
|
| 259 |
+
f"precision": precision,
|
| 260 |
+
f"recall": recall,
|
| 261 |
+
f"f1": f1,
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
class SpanErrorAnalyzer:
|
| 265 |
+
def __init__(self, pad_token_id=0):
|
| 266 |
+
self.pad_token_id = pad_token_id
|
| 267 |
+
|
| 268 |
+
# ===== helper =====
|
| 269 |
+
def _to_set(self, data):
|
| 270 |
+
"""
|
| 271 |
+
data: list of (b, tuple(ids))
|
| 272 |
+
-> dict[b] = set(tuple(ids))
|
| 273 |
+
"""
|
| 274 |
+
res = defaultdict(set)
|
| 275 |
+
for b, ids in data:
|
| 276 |
+
ids = tuple([i for i in ids if i != self.pad_token_id])
|
| 277 |
+
if len(ids) > 0:
|
| 278 |
+
res[b].add(ids)
|
| 279 |
+
return res
|
| 280 |
+
|
| 281 |
+
def _iou(self, a, b):
|
| 282 |
+
"""
|
| 283 |
+
a, b: tuple(ids)
|
| 284 |
+
"""
|
| 285 |
+
set_a, set_b = set(a), set(b)
|
| 286 |
+
inter = len(set_a & set_b)
|
| 287 |
+
union = len(set_a | set_b)
|
| 288 |
+
if union == 0:
|
| 289 |
+
return 0.0
|
| 290 |
+
return inter / union
|
| 291 |
+
|
| 292 |
+
def _boundary_error(self, pred, gold):
|
| 293 |
+
"""
|
| 294 |
+
đo lệch boundary dựa trên overlap prefix/suffix
|
| 295 |
+
"""
|
| 296 |
+
# left match
|
| 297 |
+
left = 0
|
| 298 |
+
for i in range(min(len(pred), len(gold))):
|
| 299 |
+
if pred[i] == gold[i]:
|
| 300 |
+
left += 1
|
| 301 |
+
else:
|
| 302 |
+
break
|
| 303 |
+
|
| 304 |
+
# right match
|
| 305 |
+
right = 0
|
| 306 |
+
for i in range(1, min(len(pred), len(gold)) + 1):
|
| 307 |
+
if pred[-i] == gold[-i]:
|
| 308 |
+
right += 1
|
| 309 |
+
else:
|
| 310 |
+
break
|
| 311 |
+
|
| 312 |
+
return {
|
| 313 |
+
"left_match": left,
|
| 314 |
+
"right_match": right,
|
| 315 |
+
"pred_len": len(pred),
|
| 316 |
+
"gold_len": len(gold),
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
# ===== main =====
|
| 320 |
+
def analyze(self, preds, golds):
|
| 321 |
+
pred_map = self._to_set(preds)
|
| 322 |
+
gold_map = self._to_set(golds)
|
| 323 |
+
|
| 324 |
+
all_batches = set(pred_map.keys()) | set(gold_map.keys())
|
| 325 |
+
|
| 326 |
+
stats = Counter()
|
| 327 |
+
|
| 328 |
+
detailed_errors = []
|
| 329 |
+
|
| 330 |
+
for b in all_batches:
|
| 331 |
+
pset = pred_map.get(b, set())
|
| 332 |
+
gset = gold_map.get(b, set())
|
| 333 |
+
|
| 334 |
+
matched_gold = set()
|
| 335 |
+
|
| 336 |
+
# ===== check predictions =====
|
| 337 |
+
for p in pset:
|
| 338 |
+
if p in gset:
|
| 339 |
+
stats["exact_match"] += 1
|
| 340 |
+
matched_gold.add(p)
|
| 341 |
+
else:
|
| 342 |
+
# tìm gold gần nhất
|
| 343 |
+
best_iou = 0
|
| 344 |
+
best_g = None
|
| 345 |
+
|
| 346 |
+
for g in gset:
|
| 347 |
+
iou = self._iou(p, g)
|
| 348 |
+
if iou > best_iou:
|
| 349 |
+
best_iou = iou
|
| 350 |
+
best_g = g
|
| 351 |
+
|
| 352 |
+
if best_iou > 0:
|
| 353 |
+
stats["partial_match"] += 1
|
| 354 |
+
|
| 355 |
+
boundary = self._boundary_error(p, best_g)
|
| 356 |
+
|
| 357 |
+
detailed_errors.append({
|
| 358 |
+
"type": "boundary_error",
|
| 359 |
+
"batch": b,
|
| 360 |
+
"pred": p,
|
| 361 |
+
"gold": best_g,
|
| 362 |
+
"iou": best_iou,
|
| 363 |
+
**boundary
|
| 364 |
+
})
|
| 365 |
+
else:
|
| 366 |
+
if b not in gold_map:
|
| 367 |
+
stats["no_event_sample"] += 1
|
| 368 |
+
err_type = "no_event_sample"
|
| 369 |
+
else:
|
| 370 |
+
stats["completely_wrong"] += 1
|
| 371 |
+
err_type = "completely_wrong"
|
| 372 |
+
|
| 373 |
+
detailed_errors.append({
|
| 374 |
+
"type": err_type,
|
| 375 |
+
"batch": b,
|
| 376 |
+
"pred": p
|
| 377 |
+
})
|
| 378 |
+
|
| 379 |
+
# ===== check missing =====
|
| 380 |
+
for g in gset:
|
| 381 |
+
if g not in matched_gold:
|
| 382 |
+
# check if any pred overlaps
|
| 383 |
+
overlap = any(self._iou(p, g) > 0 for p in pset)
|
| 384 |
+
|
| 385 |
+
if overlap:
|
| 386 |
+
stats["miss_with_overlap"] += 1
|
| 387 |
+
else:
|
| 388 |
+
stats["miss"] += 1
|
| 389 |
+
|
| 390 |
+
detailed_errors.append({
|
| 391 |
+
"type": "miss",
|
| 392 |
+
"batch": b,
|
| 393 |
+
"gold": g
|
| 394 |
+
})
|
| 395 |
+
|
| 396 |
+
return {
|
| 397 |
+
"summary": {
|
| 398 |
+
"exact_match": (stats["exact_match"], stats["exact_match"] / len(preds)),
|
| 399 |
+
"partial_match": (stats["partial_match"], stats["partial_match"] / len(preds)),
|
| 400 |
+
"no_event_sample": (stats["no_event_sample"], stats["no_event_sample"] / len(preds)),
|
| 401 |
+
"completely_wrong": (stats["completely_wrong"], stats["completely_wrong"] / len(preds)),
|
| 402 |
+
"miss": (stats["miss"], stats["miss"] / len(golds)),
|
| 403 |
+
"miss_with_overlap": (stats["miss_with_overlap"], stats["miss_with_overlap"] / len(golds)),
|
| 404 |
+
},
|
| 405 |
+
"details": detailed_errors
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
# %% [code]
|
| 409 |
+
## Viết cấu trúc model vào đây
|
| 410 |
+
class MLP(nn.Module):
|
| 411 |
+
def __init__(self, in_size, hid_size, out_size):
|
| 412 |
+
super().__init__()
|
| 413 |
+
self.mlp = nn.Sequential(
|
| 414 |
+
nn.Linear(in_size, hid_size),
|
| 415 |
+
nn.ReLU(),
|
| 416 |
+
nn.Linear(hid_size, out_size)
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
def forward(self, x):
|
| 420 |
+
return self.mlp(x)
|
| 421 |
+
|
| 422 |
+
class IEModel(nn.Module):
|
| 423 |
+
def __init__(self, backbone_model_name, num_labels):
|
| 424 |
+
super().__init__()
|
| 425 |
+
self.encoder = AutoModel.from_pretrained(backbone_model_name)
|
| 426 |
+
hidden_size = self.encoder.config.hidden_size
|
| 427 |
+
|
| 428 |
+
self.token_classifier = MLP(hidden_size, hidden_size, num_labels)
|
| 429 |
+
|
| 430 |
+
def encode(self, input_ids, attention_mask):
|
| 431 |
+
B, n_parts, L = input_ids.shape
|
| 432 |
+
input_ids = input_ids.view(-1, L)
|
| 433 |
+
attention_mask = attention_mask.view(-1, L)
|
| 434 |
+
|
| 435 |
+
outputs = self.encoder(input_ids=input_ids, attention_mask=attention_mask)
|
| 436 |
+
hidden_states = outputs.last_hidden_state # B * n_parts, L, H
|
| 437 |
+
|
| 438 |
+
hidden_states = hidden_states.view(B, n_parts, L, -1).reshape(B, n_parts*L, -1) # B, L, H
|
| 439 |
+
return hidden_states
|
| 440 |
+
|
| 441 |
+
def get_logits(self, hidden_states):
|
| 442 |
+
logits = self.token_classifier(hidden_states) # B, N, classes
|
| 443 |
+
return logits
|
| 444 |
+
|
| 445 |
+
def forward(self, input_ids, attention_mask):
|
| 446 |
+
hidden_states = self.encode(input_ids, attention_mask)
|
| 447 |
+
logits = self.get_logits(hidden_states)
|
| 448 |
+
|
| 449 |
+
return logits
|
| 450 |
+
|
| 451 |
+
def test():
|
| 452 |
+
model = nn.DataParallel(IEModel(backbone_model_name, 7)).to(device)
|
| 453 |
+
model.eval()
|
| 454 |
+
total_params = sum(p.numel() for p in model.parameters())
|
| 455 |
+
print(f"Total params: {total_params:,}")
|
| 456 |
+
|
| 457 |
+
vocab_size = model.module.encoder.config.vocab_size
|
| 458 |
+
max_len = model.module.encoder.config.max_position_embeddings
|
| 459 |
+
|
| 460 |
+
bz = 32
|
| 461 |
+
i = torch.randint(0, vocab_size, (bz, 5, 10)).to(device)
|
| 462 |
+
a = torch.ones(bz, 5, 10).to(device)
|
| 463 |
+
g = torch.ones(bz, 3, 2, dtype=torch.long).to(device)
|
| 464 |
+
|
| 465 |
+
with torch.no_grad():
|
| 466 |
+
r = model(i, a)
|
| 467 |
+
|
| 468 |
+
if type(r) == tuple:
|
| 469 |
+
print([r[i].shape for i in range(len(r))])
|
| 470 |
+
else:
|
| 471 |
+
print(r.shape)
|
| 472 |
+
|
| 473 |
+
test()
|
| 474 |
+
|
| 475 |
+
# %% [code]
|
| 476 |
+
def configure_optimizers(network, optim_params, scheduler_params):
|
| 477 |
+
try:
|
| 478 |
+
optim_params = copy.copy(optim_params)
|
| 479 |
+
scheduler_params = copy.copy(scheduler_params)
|
| 480 |
+
|
| 481 |
+
optim_name = optim_params.pop('name')
|
| 482 |
+
scheduler_name = scheduler_params.pop('name')
|
| 483 |
+
|
| 484 |
+
optimizer_cls = globals().get(optim_name) or getattr(optim, optim_name, None)
|
| 485 |
+
scheduler_cls = globals().get(scheduler_name) or getattr(optim.lr_scheduler, scheduler_name, None)
|
| 486 |
+
|
| 487 |
+
if optimizer_cls is None:
|
| 488 |
+
raise ValueError(f"Optimizer '{optim_name}' is not available!")
|
| 489 |
+
|
| 490 |
+
optimizer = optimizer_cls(network.parameters(), **optim_params)
|
| 491 |
+
|
| 492 |
+
scheduler = None
|
| 493 |
+
if scheduler_params and scheduler_cls: # Chỉ tạo scheduler nếu có tham số
|
| 494 |
+
scheduler = scheduler_cls(optimizer, **scheduler_params)
|
| 495 |
+
|
| 496 |
+
return optimizer, scheduler
|
| 497 |
+
|
| 498 |
+
except KeyError as e:
|
| 499 |
+
raise ValueError(f"Missing {e} in config!!")
|
| 500 |
+
|
| 501 |
+
def freeze(self, model):
|
| 502 |
+
model.eval()
|
| 503 |
+
for param in model.parameters():
|
| 504 |
+
param.requires_grad = False
|
| 505 |
+
|
| 506 |
+
def unfreeze(self, model):
|
| 507 |
+
model.train()
|
| 508 |
+
for param in model.parameters():
|
| 509 |
+
param.requires_grad = True
|
| 510 |
+
|
| 511 |
+
def reduce_batch_size(loader, ratio=0.5):
|
| 512 |
+
new_bs = max(1, int(loader.batch_size * ratio))
|
| 513 |
+
|
| 514 |
+
shuffle = isinstance(loader.sampler, RandomSampler)
|
| 515 |
+
|
| 516 |
+
new_loader = DataLoader(
|
| 517 |
+
dataset=loader.dataset,
|
| 518 |
+
batch_size=new_bs,
|
| 519 |
+
shuffle=shuffle,
|
| 520 |
+
sampler=None if shuffle else loader.sampler,
|
| 521 |
+
num_workers=loader.num_workers,
|
| 522 |
+
collate_fn=loader.collate_fn,
|
| 523 |
+
pin_memory=loader.pin_memory,
|
| 524 |
+
drop_last=loader.drop_last,
|
| 525 |
+
timeout=loader.timeout,
|
| 526 |
+
worker_init_fn=loader.worker_init_fn,
|
| 527 |
+
multiprocessing_context=loader.multiprocessing_context,
|
| 528 |
+
generator=loader.generator,
|
| 529 |
+
prefetch_factor=loader.prefetch_factor if loader.num_workers > 0 else None,
|
| 530 |
+
persistent_workers=loader.persistent_workers,
|
| 531 |
+
pin_memory_device=loader.pin_memory_device
|
| 532 |
+
)
|
| 533 |
+
|
| 534 |
+
return new_loader
|
| 535 |
+
|
| 536 |
+
def list_to_tuple(x):
|
| 537 |
+
if isinstance(x, (list, tuple)):
|
| 538 |
+
return tuple(list_to_tuple(i) for i in x)
|
| 539 |
+
return x
|
| 540 |
+
|
| 541 |
+
def fmt(x):
|
| 542 |
+
if isinstance(x, float):
|
| 543 |
+
return round(x, 5)
|
| 544 |
+
if isinstance(x, dict):
|
| 545 |
+
return {k: fmt(v) for k, v in x.items()}
|
| 546 |
+
if isinstance(x, list):
|
| 547 |
+
return [fmt(v) for v in x]
|
| 548 |
+
return x
|
| 549 |
+
|
| 550 |
+
class ModelEmaV3Proxy(ModelEmaV3):
|
| 551 |
+
def __getattr__(self, name):
|
| 552 |
+
try:
|
| 553 |
+
return super().__getattr__(name)
|
| 554 |
+
except AttributeError:
|
| 555 |
+
return getattr(self.module, name)
|
| 556 |
+
|
| 557 |
+
class DataParallelProxy(nn.DataParallel):
|
| 558 |
+
def __getattr__(self, name):
|
| 559 |
+
try:
|
| 560 |
+
return super().__getattr__(name)
|
| 561 |
+
except AttributeError:
|
| 562 |
+
attr = getattr(self.module, name)
|
| 563 |
+
|
| 564 |
+
if callable(attr):
|
| 565 |
+
def wrapper(*args, **kwargs):
|
| 566 |
+
return self._parallel_apply_method(name, *args, **kwargs)
|
| 567 |
+
return wrapper
|
| 568 |
+
|
| 569 |
+
return attr
|
| 570 |
+
|
| 571 |
+
def _parallel_apply_method(self, method_name, *inputs, **kwargs):
|
| 572 |
+
if not self.device_ids:
|
| 573 |
+
return getattr(self.module, method_name)(*inputs, **kwargs)
|
| 574 |
+
|
| 575 |
+
inputs_scattered, kwargs_scattered = self.scatter(inputs, kwargs, self.device_ids)
|
| 576 |
+
|
| 577 |
+
replicas = self.replicate(self.module, self.device_ids)
|
| 578 |
+
|
| 579 |
+
outputs = self.parallel_apply(
|
| 580 |
+
[getattr(replica, method_name) for replica in replicas],
|
| 581 |
+
inputs_scattered,
|
| 582 |
+
kwargs_scattered
|
| 583 |
+
)
|
| 584 |
+
|
| 585 |
+
return self.gather(outputs, self.output_device)
|
| 586 |
+
|
| 587 |
+
def fix_bio(tags):
|
| 588 |
+
fixed = []
|
| 589 |
+
|
| 590 |
+
for i, tag in enumerate(tags):
|
| 591 |
+
if tag.startswith('I-'):
|
| 592 |
+
if i == 0 or fixed[i-1] == 'O':
|
| 593 |
+
tag = 'B-' + tag[2:]
|
| 594 |
+
else:
|
| 595 |
+
prev_type = fixed[i-1][2:]
|
| 596 |
+
curr_type = tag[2:]
|
| 597 |
+
if prev_type != curr_type:
|
| 598 |
+
tag = 'B-' + curr_type
|
| 599 |
+
fixed.append(tag)
|
| 600 |
+
|
| 601 |
+
return fixed
|
| 602 |
+
|
| 603 |
+
def extract_entities(input_ids, pred_labels):
|
| 604 |
+
results = []
|
| 605 |
+
|
| 606 |
+
for bidx, (ids_seq, label_seq) in enumerate(zip(input_ids, pred_labels)):
|
| 607 |
+
i = 0
|
| 608 |
+
L = len(label_seq)
|
| 609 |
+
|
| 610 |
+
while i < L:
|
| 611 |
+
tag = label_seq[i]
|
| 612 |
+
|
| 613 |
+
if tag.startswith('B-'):
|
| 614 |
+
ent_type = tag[2:]
|
| 615 |
+
start = i
|
| 616 |
+
end = i
|
| 617 |
+
|
| 618 |
+
i += 1
|
| 619 |
+
# kéo dài span nếu là I- cùng type
|
| 620 |
+
while i < L and label_seq[i] == f'I-{ent_type}':
|
| 621 |
+
end = i
|
| 622 |
+
i += 1
|
| 623 |
+
|
| 624 |
+
# lấy span input_ids
|
| 625 |
+
span_ids = ids_seq[start:end+1].tolist()
|
| 626 |
+
results.append((bidx, (span_ids, ent_type)))
|
| 627 |
+
|
| 628 |
+
else:
|
| 629 |
+
i += 1
|
| 630 |
+
|
| 631 |
+
return results
|
| 632 |
+
|
| 633 |
+
class Trainer:
|
| 634 |
+
def __init__(
|
| 635 |
+
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,
|
| 636 |
+
logging=0, logging_file=False, checkpoints_dir="", early_stopping=False, eval_from_ratio=-1, eval_every=1, device='cpu',
|
| 637 |
+
schedule_in_step=True, use_ema=True, ema_from_ratio=-1, ema_decay=0.999, return_best=True, return_last=True
|
| 638 |
+
):
|
| 639 |
+
self.ema_net = None
|
| 640 |
+
|
| 641 |
+
self.training_time = self._time_str_to_seconds(training_time)
|
| 642 |
+
self.mode = eval_mode
|
| 643 |
+
self.topk = topk
|
| 644 |
+
self.device = device
|
| 645 |
+
self.logging = logging if logging < epochs else 1
|
| 646 |
+
self.logging_file = logging_file
|
| 647 |
+
self.checkpoints_dir = checkpoints_dir
|
| 648 |
+
self.early_stopping = early_stopping
|
| 649 |
+
self.eval_from_ratio = eval_from_ratio
|
| 650 |
+
self.eval_every = eval_every
|
| 651 |
+
self.save_name = save_name
|
| 652 |
+
self.save_best = save_best
|
| 653 |
+
self.save_last = save_last
|
| 654 |
+
self.return_best = return_best
|
| 655 |
+
self.return_last = return_last
|
| 656 |
+
self.max_grad_norm = max_grad_norm
|
| 657 |
+
self.schedule_in_step = schedule_in_step
|
| 658 |
+
self.use_ema = use_ema
|
| 659 |
+
self.ema_from_ratio = ema_from_ratio
|
| 660 |
+
self.ema_decay = ema_decay
|
| 661 |
+
|
| 662 |
+
self.best_stage = [[float('-inf') if self.mode == 'max' else float('inf'), None, None]]
|
| 663 |
+
self.grad_scaler = torch.amp.GradScaler(self.device, init_scale=1024.0)
|
| 664 |
+
|
| 665 |
+
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):
|
| 666 |
+
if eval_fn is None:
|
| 667 |
+
if self.mode == "max":
|
| 668 |
+
eval_fn = lambda *x: -loss_fn(*x)
|
| 669 |
+
else:
|
| 670 |
+
eval_fn = lambda *x: loss_fn(*x)
|
| 671 |
+
|
| 672 |
+
if torch.cuda.device_count() > 1:
|
| 673 |
+
network = DataParallelProxy(network)
|
| 674 |
+
network = network.to(self.device)
|
| 675 |
+
|
| 676 |
+
if not start_training_time:
|
| 677 |
+
start_training_time = time.time()
|
| 678 |
+
|
| 679 |
+
start_ema = int(epochs * self.ema_from_ratio)
|
| 680 |
+
start_eval = int(epochs * self.eval_from_ratio)
|
| 681 |
+
|
| 682 |
+
if val_loader is None:
|
| 683 |
+
print(f'[Trainer CallBack] 📢 Không có Val Set, không thể đánh giá và Early Stopping!')
|
| 684 |
+
else:
|
| 685 |
+
model_to_use_str = 'mô hình EMA' if self.use_ema else 'mô hình gốc'
|
| 686 |
+
start_model_update_str = f'Bắt đầu cập nhật EMA từ epoch {start_epoch + start_ema}!' if self.use_ema else ''
|
| 687 |
+
print(f'[Trainer CallBack] 📢 Đánh giá bằng {model_to_use_str} từ epoch {start_epoch + start_eval}!', start_model_update_str)
|
| 688 |
+
|
| 689 |
+
training_log = {}
|
| 690 |
+
for epoch in range(start_epoch, epochs+start_epoch):
|
| 691 |
+
if self.use_ema and self.ema_net is None and epoch - start_epoch >= start_ema:
|
| 692 |
+
self.ema_net = ModelEmaV3Proxy(network, self.ema_decay, device=self.device)
|
| 693 |
+
|
| 694 |
+
try:
|
| 695 |
+
train_loss_epoch, train_loss_epoch_dict = self._train_epoch(network, train_loader, optimizer, scheduler, loss_fn)
|
| 696 |
+
logging_dict = {'lr': [group['lr'] for group in optimizer.param_groups], 'train_loss': train_loss_epoch}
|
| 697 |
+
logging_dict.update(train_loss_epoch_dict)
|
| 698 |
+
|
| 699 |
+
if val_loader is not None and epoch - start_epoch >= start_eval and (epoch - start_epoch - start_eval) % self.eval_every == 0:
|
| 700 |
+
eval_net = self.ema_net.module if (self.use_ema and self.ema_net is not None) else network
|
| 701 |
+
|
| 702 |
+
val_score, val_score_dict, _ = self._eval_epoch(eval_net, val_loader, eval_fn, id2label)
|
| 703 |
+
update = self._update_best_network(eval_net, val_score, epoch)
|
| 704 |
+
logging_dict.update({'val_score': val_score, 'best_score': self.best_stage[0][0], 'new_best_model': update})
|
| 705 |
+
logging_dict.update(val_score_dict)
|
| 706 |
+
if not self.schedule_in_step and scheduler:
|
| 707 |
+
scheduler.step()
|
| 708 |
+
|
| 709 |
+
except RuntimeError as e:
|
| 710 |
+
if "out of memory" in str(e).lower():
|
| 711 |
+
print(f"[Trainer CallBack] ⚠️ Epoch {epoch}/{epochs}: CUDA Out of Memory! Clearing GPU cache...")
|
| 712 |
+
torch.cuda.empty_cache()
|
| 713 |
+
gc.collect()
|
| 714 |
+
if torch.cuda.is_available():
|
| 715 |
+
torch.cuda.synchronize()
|
| 716 |
+
print(f"[Trainer CallBack] ✅ Epoch {epoch}/{epochs}: GPU memory cleared")
|
| 717 |
+
|
| 718 |
+
train_loader = reduce_batch_size(train_loader, ratio=0.5)
|
| 719 |
+
if val_loader is not None:
|
| 720 |
+
val_loader = reduce_batch_size(val_loader, ratio=0.5)
|
| 721 |
+
|
| 722 |
+
logging_dict = {'lr': [group['lr'] for group in optimizer.param_groups], 'train_loss': float('inf')}
|
| 723 |
+
else:
|
| 724 |
+
raise
|
| 725 |
+
|
| 726 |
+
training_log[epoch] = logging_dict
|
| 727 |
+
if self.is_early_stopping(epoch):
|
| 728 |
+
print(f'[Trainer CallBack] 📢 Epoch {epoch}/{epochs}: Detect Overfitting! Breaking Training Process...')
|
| 729 |
+
break
|
| 730 |
+
if self.logging:
|
| 731 |
+
if epoch % self.logging == 0:
|
| 732 |
+
print(f'[Trainer CallBack] 📢 Epoch {epoch}/{epochs}:', fmt(logging_dict))
|
| 733 |
+
else:
|
| 734 |
+
print(f'{epoch}...', end=' ')
|
| 735 |
+
|
| 736 |
+
if self._at_time_limit(start_training_time):
|
| 737 |
+
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}')
|
| 738 |
+
break
|
| 739 |
+
|
| 740 |
+
if self.logging_file:
|
| 741 |
+
os.makedirs(f'{self.checkpoints_dir}/logs', exist_ok=True)
|
| 742 |
+
with open(f"{self.checkpoints_dir}/logs/{self.save_name}_logging.json", "a", encoding="utf-8") as f:
|
| 743 |
+
f.write(json.dumps(training_log))
|
| 744 |
+
|
| 745 |
+
if self.use_ema and self.ema_net is not None:
|
| 746 |
+
self._save_state_dict(self.ema_net.module)
|
| 747 |
+
else:
|
| 748 |
+
self._save_state_dict(network)
|
| 749 |
+
print(f'[Trainer CallBack] 📢 Kết thúc training.\n')
|
| 750 |
+
|
| 751 |
+
best_model, last_model = None, None
|
| 752 |
+
eval_net = self.ema_net.module if (self.use_ema and self.ema_net is not None) else network
|
| 753 |
+
if self.return_best :
|
| 754 |
+
best_model = self.best_stage[0][2] if self.best_stage[0][2] is not None else eval_net.state_dict()
|
| 755 |
+
best_model = {k.replace("module.", ""): v.detach().cpu().clone() for k, v in best_model.items()}
|
| 756 |
+
if self.return_last:
|
| 757 |
+
last_model = eval_net.state_dict()
|
| 758 |
+
last_model = {k.replace("module.", ""): v.detach().cpu().clone() for k, v in last_model.items()}
|
| 759 |
+
|
| 760 |
+
del network
|
| 761 |
+
torch.cuda.empty_cache()
|
| 762 |
+
gc.collect()
|
| 763 |
+
return training_log, best_model, last_model
|
| 764 |
+
|
| 765 |
+
def _time_str_to_seconds(self, time_str):
|
| 766 |
+
days, hours, minutes, seconds = map(int, time_str.split(":"))
|
| 767 |
+
return days * 86400 + hours * 3600 + minutes * 60 + seconds
|
| 768 |
+
|
| 769 |
+
def _update_best_network(self, network, val_score, epoch):
|
| 770 |
+
topk = max(1, self.topk)
|
| 771 |
+
self.best_stage.append([val_score, epoch, {k: v.detach().cpu().clone() for k, v in network.state_dict().items()}])
|
| 772 |
+
self.best_stage = sorted(self.best_stage, reverse=(self.mode == 'max'), key=lambda x: x[0])[:topk]
|
| 773 |
+
if val_score in [x[0] for x in self.best_stage]:
|
| 774 |
+
return True
|
| 775 |
+
return False
|
| 776 |
+
|
| 777 |
+
def is_early_stopping(self, epoch):
|
| 778 |
+
if self.best_stage[0][1] is None:
|
| 779 |
+
return False
|
| 780 |
+
if not self.early_stopping:
|
| 781 |
+
return False
|
| 782 |
+
return epoch - self.best_stage[0][1] >= self.early_stopping
|
| 783 |
+
|
| 784 |
+
def _at_time_limit(self, start_training_time):
|
| 785 |
+
return time.time() - start_training_time >= self.training_time
|
| 786 |
+
|
| 787 |
+
def _save_state_dict(self, network):
|
| 788 |
+
if self.topk <= 0:
|
| 789 |
+
return
|
| 790 |
+
|
| 791 |
+
if self.save_best:
|
| 792 |
+
for r in range(self.topk):
|
| 793 |
+
os.makedirs(f'{self.checkpoints_dir}/r{r+1}s', exist_ok=True)
|
| 794 |
+
|
| 795 |
+
for rank, (score, epoch, state_dict) in enumerate(self.best_stage):
|
| 796 |
+
if state_dict is None:
|
| 797 |
+
continue
|
| 798 |
+
state_dict = {k.replace("module.", ""): v.detach().cpu().clone() for k, v in state_dict.items()}
|
| 799 |
+
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')
|
| 800 |
+
if self.save_last:
|
| 801 |
+
os.makedirs(f'{self.checkpoints_dir}/lasts', exist_ok=True)
|
| 802 |
+
state_dict = {k.replace("module.", ""): v.detach().cpu().clone() for k, v in network.state_dict().items()}
|
| 803 |
+
torch.save(state_dict, f'{self.checkpoints_dir}/lasts/{self.save_name}_last_{"ema" if self.ema_net is not None else ""}.pth')
|
| 804 |
+
|
| 805 |
+
def _train_epoch(self, network, train_loader, optimizer, scheduler, loss_fn):
|
| 806 |
+
network.train()
|
| 807 |
+
total_loss = 0
|
| 808 |
+
total_loss_dict = {}
|
| 809 |
+
for batch_idx, batch in enumerate(train_loader):
|
| 810 |
+
optimizer.zero_grad()
|
| 811 |
+
with torch.autocast(device_type=self.device, dtype=torch.float16):
|
| 812 |
+
loss, loss_dict = self._cal_loss(network, batch, batch_idx, loss_fn)
|
| 813 |
+
|
| 814 |
+
for k, v in loss_dict.items():
|
| 815 |
+
t = total_loss_dict.get(k, 0)
|
| 816 |
+
total_loss_dict[k] = t + v
|
| 817 |
+
self.grad_scaler.scale(loss).backward()
|
| 818 |
+
self.grad_scaler.unscale_(optimizer)
|
| 819 |
+
grad_norm = nn.utils.clip_grad_norm_(network.parameters(), self.max_grad_norm)
|
| 820 |
+
# print(grad_norm) # Bỏ cmt dòng này để biết nên chọn max_grad_norm bằng bao nhiêu...
|
| 821 |
+
self.grad_scaler.step(optimizer)
|
| 822 |
+
self.grad_scaler.update()
|
| 823 |
+
if self.schedule_in_step and scheduler:
|
| 824 |
+
scheduler.step()
|
| 825 |
+
if self.use_ema and self.ema_net is not None:
|
| 826 |
+
self.ema_net.update(network)
|
| 827 |
+
total_loss += loss
|
| 828 |
+
return (total_loss / len(train_loader)).item(), {k: v.item() / len(train_loader) for k, v in total_loss_dict.items()}
|
| 829 |
+
|
| 830 |
+
def _eval_epoch(self, network, val_loader, eval_fn, id2label):
|
| 831 |
+
network.eval()
|
| 832 |
+
total_score = 0.0
|
| 833 |
+
total_score_dict = {}
|
| 834 |
+
object_lists = None # sẽ init sau
|
| 835 |
+
|
| 836 |
+
with torch.no_grad():
|
| 837 |
+
for batch_idx, batch in enumerate(val_loader):
|
| 838 |
+
score, score_dict, objects = self._cal_val_score(network, batch, batch_idx, eval_fn, id2label)
|
| 839 |
+
total_score += score
|
| 840 |
+
|
| 841 |
+
for k, v in score_dict.items():
|
| 842 |
+
t = total_score_dict.get(k, 0)
|
| 843 |
+
total_score_dict[k] = t + v
|
| 844 |
+
|
| 845 |
+
if objects:
|
| 846 |
+
if object_lists is None:
|
| 847 |
+
object_lists = [[] for _ in range(len(objects))]
|
| 848 |
+
|
| 849 |
+
for i, obj in enumerate(objects):
|
| 850 |
+
object_lists[i].append(obj.detach())
|
| 851 |
+
|
| 852 |
+
if object_lists is not None:
|
| 853 |
+
object_arrays = [
|
| 854 |
+
torch.concat(obj_list, dim=0).cpu().numpy()
|
| 855 |
+
for obj_list in object_lists
|
| 856 |
+
]
|
| 857 |
+
else:
|
| 858 |
+
object_arrays = []
|
| 859 |
+
|
| 860 |
+
return total_score / len(val_loader), {k: v / len(val_loader) for k, v in total_score_dict.items()}, object_arrays
|
| 861 |
+
|
| 862 |
+
def _cal_loss(self, network, batch, batch_idx, loss_fn):
|
| 863 |
+
# Bạn cần override _cal_loss để tính loss
|
| 864 |
+
input_ids = batch['input_ids'].to(self.device)
|
| 865 |
+
attention_mask = batch['attention_mask'].to(self.device)
|
| 866 |
+
token_labels = batch['token_labels'].to(self.device)
|
| 867 |
+
|
| 868 |
+
token_logits = network(input_ids, attention_mask)
|
| 869 |
+
|
| 870 |
+
loss_dict = loss_fn(
|
| 871 |
+
token_logits, token_labels,
|
| 872 |
+
)
|
| 873 |
+
return loss_dict['total'], loss_dict
|
| 874 |
+
|
| 875 |
+
def _cal_val_score(self, network, batch, batch_idx, eval_fn, id2label):
|
| 876 |
+
# 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)
|
| 877 |
+
input_ids = batch['input_ids'].to(self.device)
|
| 878 |
+
attention_mask = batch['attention_mask'].to(self.device)
|
| 879 |
+
gold_entities = batch['gold_entities']
|
| 880 |
+
|
| 881 |
+
B, _, _ = input_ids.shape
|
| 882 |
+
|
| 883 |
+
token_logits = network(input_ids, attention_mask)
|
| 884 |
+
pred_labels = torch.argmax(token_logits, dim=-1) # (B, L)
|
| 885 |
+
pred_labels = [[id2label[i.item()] for i in seq] for seq in pred_labels]
|
| 886 |
+
pred_labels = [fix_bio(seq) for seq in pred_labels]
|
| 887 |
+
|
| 888 |
+
pred_ids = extract_entities(input_ids.reshape(B, -1), pred_labels)
|
| 889 |
+
pred_ids = list_to_tuple(pred_ids)
|
| 890 |
+
|
| 891 |
+
gold_ids = list_to_tuple(gold_entities)
|
| 892 |
+
|
| 893 |
+
score_dict = eval_fn(pred_ids, gold_ids)
|
| 894 |
+
return score_dict['f1'], score_dict, []
|
| 895 |
+
|
| 896 |
+
# %% [code]
|
| 897 |
+
class PhoBERTSpanAligner:
|
| 898 |
+
def __init__(self, tokenizer, max_len):
|
| 899 |
+
self.tokenizer = tokenizer
|
| 900 |
+
self.max_len = max_len
|
| 901 |
+
|
| 902 |
+
# ===== 1. Extract discontinuous spans =====
|
| 903 |
+
def extract_spans(self, sample):
|
| 904 |
+
entity_spans = []
|
| 905 |
+
|
| 906 |
+
for event in sample["entities"]:
|
| 907 |
+
entity_type = event["label"]
|
| 908 |
+
spans = [tuple(event["offset"])]
|
| 909 |
+
entity_spans.append({
|
| 910 |
+
"spans": spans,
|
| 911 |
+
"label": entity_type
|
| 912 |
+
})
|
| 913 |
+
|
| 914 |
+
return entity_spans
|
| 915 |
+
|
| 916 |
+
# ===== 2. Word offsets =====
|
| 917 |
+
def build_word_offsets(self, text, words):
|
| 918 |
+
offsets = []
|
| 919 |
+
pointer = 0
|
| 920 |
+
|
| 921 |
+
for word in words:
|
| 922 |
+
start = text.find(word, pointer)
|
| 923 |
+
end = start + len(word)
|
| 924 |
+
offsets.append((start, end))
|
| 925 |
+
pointer = end
|
| 926 |
+
|
| 927 |
+
return offsets
|
| 928 |
+
|
| 929 |
+
# ===== 3. Char → word =====
|
| 930 |
+
def char_span_to_word_span(self, word_offsets, start, end):
|
| 931 |
+
start_word = None
|
| 932 |
+
end_word = None
|
| 933 |
+
|
| 934 |
+
for i, (w_start, w_end) in enumerate(word_offsets):
|
| 935 |
+
if w_start <= start < w_end:
|
| 936 |
+
start_word = i
|
| 937 |
+
if w_start < end <= w_end:
|
| 938 |
+
end_word = i
|
| 939 |
+
|
| 940 |
+
return start_word, end_word
|
| 941 |
+
|
| 942 |
+
# ===== 4. Word → subword =====
|
| 943 |
+
def word_to_subword_map(self, words):
|
| 944 |
+
mapping = []
|
| 945 |
+
subword_index = 1 # <s>
|
| 946 |
+
|
| 947 |
+
for word in words:
|
| 948 |
+
sub_tokens = self.tokenizer.tokenize(word)
|
| 949 |
+
start = subword_index
|
| 950 |
+
end = subword_index + len(sub_tokens) - 1
|
| 951 |
+
mapping.append((start, end))
|
| 952 |
+
subword_index += len(sub_tokens)
|
| 953 |
+
|
| 954 |
+
return mapping
|
| 955 |
+
|
| 956 |
+
# ===== 5. Span → subword =====
|
| 957 |
+
def span_to_subword(self, word_offsets, word_subword_map, spans):
|
| 958 |
+
sub_spans = []
|
| 959 |
+
|
| 960 |
+
for span_start, span_end in spans:
|
| 961 |
+
w_start, w_end = self.char_span_to_word_span(
|
| 962 |
+
word_offsets, span_start, span_end
|
| 963 |
+
)
|
| 964 |
+
if w_start is None or w_end is None:
|
| 965 |
+
continue
|
| 966 |
+
|
| 967 |
+
sub_start = word_subword_map[w_start][0]
|
| 968 |
+
sub_end = word_subword_map[w_end][1]
|
| 969 |
+
sub_spans.append((sub_start, sub_end))
|
| 970 |
+
|
| 971 |
+
return sub_spans
|
| 972 |
+
|
| 973 |
+
def extract_valid_spans(self, sub_spans):
|
| 974 |
+
valid_spans = []
|
| 975 |
+
for s, e in sub_spans:
|
| 976 |
+
if s < 0 or e < 0 or s >= self.max_len or e >= self.max_len or s > e:
|
| 977 |
+
continue
|
| 978 |
+
valid_spans.append((s, e))
|
| 979 |
+
return valid_spans
|
| 980 |
+
|
| 981 |
+
def encode(self, sample):
|
| 982 |
+
text = sample["text"]
|
| 983 |
+
entities = self.extract_spans(sample)
|
| 984 |
+
|
| 985 |
+
# ===== 1. Word tokenize =====
|
| 986 |
+
words = word_tokenize(text)
|
| 987 |
+
sentence = " ".join(words)
|
| 988 |
+
|
| 989 |
+
# ===== 2. Mapping =====
|
| 990 |
+
word_offsets = self.build_word_offsets(text, words)
|
| 991 |
+
word_subword_map = self.word_to_subword_map(words)
|
| 992 |
+
|
| 993 |
+
# ===== 3. Tokenize FULL =====
|
| 994 |
+
encoding = self.tokenizer(
|
| 995 |
+
sentence,
|
| 996 |
+
max_length=self.max_len,
|
| 997 |
+
truncation=True,
|
| 998 |
+
padding="max_length",
|
| 999 |
+
return_tensors="pt"
|
| 1000 |
+
)
|
| 1001 |
+
input_ids = encoding["input_ids"][0]
|
| 1002 |
+
attention_mask = encoding["attention_mask"][0]
|
| 1003 |
+
|
| 1004 |
+
# ===== 5. Convert spans =====
|
| 1005 |
+
entities_gold_spans = []
|
| 1006 |
+
|
| 1007 |
+
for ent in entities:
|
| 1008 |
+
label = ent["label"]
|
| 1009 |
+
|
| 1010 |
+
sub_spans = self.span_to_subword(
|
| 1011 |
+
word_offsets,
|
| 1012 |
+
word_subword_map,
|
| 1013 |
+
ent["spans"]
|
| 1014 |
+
)
|
| 1015 |
+
valid_spans = self.extract_valid_spans(sub_spans)
|
| 1016 |
+
if len(valid_spans) == 0:
|
| 1017 |
+
continue
|
| 1018 |
+
entities_gold_spans.append((tuple(valid_spans), label))
|
| 1019 |
+
|
| 1020 |
+
return {
|
| 1021 |
+
"input_ids": input_ids,
|
| 1022 |
+
"attention_mask": attention_mask,
|
| 1023 |
+
"entities_gold_spans": entities_gold_spans,
|
| 1024 |
+
}
|
| 1025 |
+
|
| 1026 |
+
def generate_candidate_spans(seq_len, max_span_len):
|
| 1027 |
+
spans = []
|
| 1028 |
+
for i in range(1, seq_len+1):
|
| 1029 |
+
for j in range(i, min(i+max_span_len, seq_len+1)):
|
| 1030 |
+
spans.append((i, j))
|
| 1031 |
+
return spans
|
| 1032 |
+
|
| 1033 |
+
class KLTNDataset(Dataset):
|
| 1034 |
+
def __init__(self, all_data, using_idxes, label2id, tokenizer, max_len, max_n_parts):
|
| 1035 |
+
super().__init__()
|
| 1036 |
+
self.tokenizer = tokenizer
|
| 1037 |
+
self.aligner = PhoBERTSpanAligner(tokenizer, max_len*max_n_parts)
|
| 1038 |
+
self.all_data = all_data
|
| 1039 |
+
self.using_idxes = using_idxes
|
| 1040 |
+
self.label2id = label2id
|
| 1041 |
+
self.max_len = max_len
|
| 1042 |
+
self.max_n_parts = max_n_parts
|
| 1043 |
+
|
| 1044 |
+
def __len__(self):
|
| 1045 |
+
return len(self.using_idxes)
|
| 1046 |
+
|
| 1047 |
+
def __getitem__(self, idx):
|
| 1048 |
+
ridx = self.using_idxes[idx]
|
| 1049 |
+
sample = self.all_data[ridx]
|
| 1050 |
+
result = self.aligner.encode(sample)
|
| 1051 |
+
|
| 1052 |
+
input_ids = result["input_ids"].squeeze(0)
|
| 1053 |
+
attention_mask = result["attention_mask"].squeeze(0)
|
| 1054 |
+
entities_gold_spans = result["entities_gold_spans"]
|
| 1055 |
+
|
| 1056 |
+
# Get label
|
| 1057 |
+
gold_entities = []
|
| 1058 |
+
token_labels = torch.ones_like(input_ids) * (1-attention_mask) * (-100)
|
| 1059 |
+
for spans, label in entities_gold_spans:
|
| 1060 |
+
s, e = spans[0]
|
| 1061 |
+
|
| 1062 |
+
token_labels[s] = self.label2id[f'B-{label}']
|
| 1063 |
+
token_labels[s+1:e+1] = self.label2id[f'I-{label}']
|
| 1064 |
+
|
| 1065 |
+
gold_entities.append((tuple(input_ids[s:e+1].tolist()), label))
|
| 1066 |
+
|
| 1067 |
+
input_ids = input_ids.reshape(self.max_n_parts, self.max_len)
|
| 1068 |
+
attention_mask = attention_mask.reshape(self.max_n_parts, self.max_len)
|
| 1069 |
+
|
| 1070 |
+
n_valid_parts = math.ceil(attention_mask.sum().item() / self.max_len)
|
| 1071 |
+
input_ids = input_ids[:n_valid_parts]
|
| 1072 |
+
attention_mask = attention_mask[:n_valid_parts]
|
| 1073 |
+
token_labels = token_labels[:n_valid_parts*self.max_len]
|
| 1074 |
+
|
| 1075 |
+
return {
|
| 1076 |
+
"input_ids": input_ids,
|
| 1077 |
+
"attention_mask": attention_mask,
|
| 1078 |
+
"token_labels": token_labels,
|
| 1079 |
+
"gold_entities": gold_entities,
|
| 1080 |
+
}
|
| 1081 |
+
|
| 1082 |
+
def _pad_batch(tensor_list, pad_value=0):
|
| 1083 |
+
"""
|
| 1084 |
+
tensor_list: list of tensors
|
| 1085 |
+
mỗi tensor shape: (Nk, n_parts_i, max_len_i)
|
| 1086 |
+
|
| 1087 |
+
return:
|
| 1088 |
+
padded tensor shape: (B, max_Nk, max_n_parts, max_len)
|
| 1089 |
+
"""
|
| 1090 |
+
|
| 1091 |
+
# lấy max toàn batch
|
| 1092 |
+
max_Nk = max(t.size(0) for t in tensor_list)
|
| 1093 |
+
max_n_parts = max(t.size(1) for t in tensor_list)
|
| 1094 |
+
max_len = max(t.size(2) for t in tensor_list)
|
| 1095 |
+
|
| 1096 |
+
padded = []
|
| 1097 |
+
|
| 1098 |
+
for t in tensor_list:
|
| 1099 |
+
Nk, n_parts_i, max_len_i = t.shape
|
| 1100 |
+
|
| 1101 |
+
# pad chiều n_parts và max_len trước
|
| 1102 |
+
if n_parts_i < max_n_parts or max_len_i < max_len:
|
| 1103 |
+
new_t = t.new_full(
|
| 1104 |
+
(Nk, max_n_parts, max_len),
|
| 1105 |
+
pad_value
|
| 1106 |
+
)
|
| 1107 |
+
new_t[:, :n_parts_i, :max_len_i] = t
|
| 1108 |
+
t = new_t
|
| 1109 |
+
|
| 1110 |
+
# pad chiều Nk
|
| 1111 |
+
if Nk < max_Nk:
|
| 1112 |
+
pad_tensor = t.new_full(
|
| 1113 |
+
(max_Nk - Nk, max_n_parts, max_len),
|
| 1114 |
+
pad_value
|
| 1115 |
+
)
|
| 1116 |
+
t = torch.cat([t, pad_tensor], dim=0)
|
| 1117 |
+
|
| 1118 |
+
padded.append(t)
|
| 1119 |
+
|
| 1120 |
+
return torch.stack(padded) # (B, max_Nk, max_n_parts, max_len)
|
| 1121 |
+
|
| 1122 |
+
def collate_fn(batch):
|
| 1123 |
+
gold_entities = []
|
| 1124 |
+
for bidx, b in enumerate(batch):
|
| 1125 |
+
for entity in b['gold_entities']:
|
| 1126 |
+
gold_entities.append([bidx, entity])
|
| 1127 |
+
|
| 1128 |
+
input_ids = [b["input_ids"].unsqueeze(-1) for b in batch]
|
| 1129 |
+
attention_mask = [b["attention_mask"].unsqueeze(-1) for b in batch]
|
| 1130 |
+
token_labels = [b["token_labels"].unsqueeze(-1).unsqueeze(-1) for b in batch]
|
| 1131 |
+
|
| 1132 |
+
# pad theo Nk
|
| 1133 |
+
input_ids = _pad_batch(input_ids, pad_value=1).squeeze(-1)
|
| 1134 |
+
attention_mask = _pad_batch(attention_mask, pad_value=0).squeeze(-1)
|
| 1135 |
+
token_labels = _pad_batch(token_labels, pad_value=-100).squeeze(-1).squeeze(-1)
|
| 1136 |
+
|
| 1137 |
+
return {
|
| 1138 |
+
"input_ids": input_ids,
|
| 1139 |
+
"attention_mask": attention_mask,
|
| 1140 |
+
"token_labels": token_labels,
|
| 1141 |
+
"gold_entities": gold_entities,
|
| 1142 |
+
}
|
| 1143 |
+
|
| 1144 |
+
# %% [code]
|
| 1145 |
+
def shift_bidx(spans, batch_idx):
|
| 1146 |
+
shifted = []
|
| 1147 |
+
for bidx, ent in spans:
|
| 1148 |
+
new_bidx = bidx + batch_idx * batch_size
|
| 1149 |
+
shifted.append((new_bidx, ent))
|
| 1150 |
+
return shifted
|
| 1151 |
+
|
| 1152 |
+
def refactor_entities(entities, save_dict):
|
| 1153 |
+
i, c = [], []
|
| 1154 |
+
for bidx, (ids, lb) in entities:
|
| 1155 |
+
if (bidx, ids) not in i:
|
| 1156 |
+
i.append((bidx, ids))
|
| 1157 |
+
|
| 1158 |
+
if (bidx, (ids, lb)) not in c:
|
| 1159 |
+
c.append((bidx, (ids, lb)))
|
| 1160 |
+
|
| 1161 |
+
save_dict['Ent-I'].extend(i)
|
| 1162 |
+
save_dict['Ent-C'].extend(c)
|
| 1163 |
+
|
| 1164 |
+
def test(network, state_dicts, test_loader, eval_fn, analyzer, device, id2label, tokenizer):
|
| 1165 |
+
if torch.cuda.device_count() > 1:
|
| 1166 |
+
network = DataParallelProxy(network)
|
| 1167 |
+
network = network.to(device)
|
| 1168 |
+
network.eval()
|
| 1169 |
+
|
| 1170 |
+
eval_types = ['Ent-I', 'Ent-C']
|
| 1171 |
+
|
| 1172 |
+
all_pred = {eval_type: [] for eval_type in eval_types}
|
| 1173 |
+
all_gold = {eval_type: [] for eval_type in eval_types}
|
| 1174 |
+
|
| 1175 |
+
list_input_ids = []
|
| 1176 |
+
|
| 1177 |
+
with torch.no_grad():
|
| 1178 |
+
for batch_idx, batch in enumerate(test_loader):
|
| 1179 |
+
input_ids = batch['input_ids'].to(device)
|
| 1180 |
+
attention_mask = batch['attention_mask'].to(device)
|
| 1181 |
+
gold_entities = batch['gold_entities']
|
| 1182 |
+
|
| 1183 |
+
B, _, _ = input_ids.shape
|
| 1184 |
+
list_input_ids.extend(input_ids.reshape(B, -1).tolist())
|
| 1185 |
+
|
| 1186 |
+
list_logits = []
|
| 1187 |
+
for sd in state_dicts:
|
| 1188 |
+
if torch.cuda.device_count() > 1:
|
| 1189 |
+
network.module.load_state_dict(sd)
|
| 1190 |
+
else:
|
| 1191 |
+
network.load_state_dict(sd)
|
| 1192 |
+
|
| 1193 |
+
token_logits = network(input_ids, attention_mask)
|
| 1194 |
+
list_logits.append(token_logits)
|
| 1195 |
+
|
| 1196 |
+
ensemble_logits = torch.stack(list_logits, dim=0).mean(dim=0)
|
| 1197 |
+
ensemble_labels = torch.argmax(ensemble_logits, dim=-1) # (B, L)
|
| 1198 |
+
ensemble_labels = [[id2label[i.item()] for i in seq] for seq in ensemble_labels]
|
| 1199 |
+
ensemble_labels = [fix_bio(seq) for seq in ensemble_labels]
|
| 1200 |
+
|
| 1201 |
+
pred_entities = extract_entities(input_ids.reshape(B, -1), ensemble_labels)
|
| 1202 |
+
pred_entities = shift_bidx(pred_entities, batch_idx)
|
| 1203 |
+
refactor_entities(pred_entities, all_pred)
|
| 1204 |
+
|
| 1205 |
+
gold_entities = shift_bidx(gold_entities, batch_idx)
|
| 1206 |
+
refactor_entities(gold_entities, all_gold)
|
| 1207 |
+
|
| 1208 |
+
# ===== GLOBAL EVAL =====
|
| 1209 |
+
final_score = {}
|
| 1210 |
+
for eval_type in eval_types:
|
| 1211 |
+
score = eval_fn(list_to_tuple(all_pred[eval_type]), list_to_tuple(all_gold[eval_type]))
|
| 1212 |
+
final_score[eval_type] = score
|
| 1213 |
+
|
| 1214 |
+
analyze_result = analyzer.analyze(list_to_tuple(all_pred['Ent-I']), list_to_tuple(all_gold['Ent-I']))
|
| 1215 |
+
|
| 1216 |
+
# ===== PREDICT =====
|
| 1217 |
+
predictions = []
|
| 1218 |
+
for input_ids in list_input_ids:
|
| 1219 |
+
predictions.append([tokenizer.decode(input_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)])
|
| 1220 |
+
for bidx, (ids, lb) in all_pred['Ent-C']:
|
| 1221 |
+
predictions[bidx].append((tokenizer.decode(ids, skip_special_tokens=True, clean_up_tokenization_spaces=True), lb))
|
| 1222 |
+
|
| 1223 |
+
return final_score, analyze_result, predictions
|
| 1224 |
+
|
| 1225 |
+
# %% [code]
|
| 1226 |
+
with open(f'{train_dir}/train.json', "r", encoding="utf-8") as f:
|
| 1227 |
+
data_train = json.load(f)
|
| 1228 |
+
|
| 1229 |
+
with open(f'{test_dir}/test.json', "r", encoding="utf-8") as f:
|
| 1230 |
+
data_test = json.load(f)
|
| 1231 |
+
|
| 1232 |
+
print('Train:', len(data_train))
|
| 1233 |
+
print('Test:', len(data_test))
|
| 1234 |
+
|
| 1235 |
+
# %% [code]
|
| 1236 |
+
entity_types = sorted(list(set([e['label'] for d in data_train + data_test for e in d['entities']])))
|
| 1237 |
+
bio_entity_type = ['O'] + [f'{prefix}-{ent}' for ent in entity_types for prefix in ['B', 'I']]
|
| 1238 |
+
label2id = {l: i for i, l in enumerate(bio_entity_type)}
|
| 1239 |
+
id2label = {i: l for l, i in label2id.items()}
|
| 1240 |
+
|
| 1241 |
+
# %% [code]
|
| 1242 |
+
zero_entities_idxes = []
|
| 1243 |
+
for idx, d in enumerate(data_train):
|
| 1244 |
+
if len(d['entities']) == 0:
|
| 1245 |
+
zero_entities_idxes.append(idx)
|
| 1246 |
+
|
| 1247 |
+
n_zero_entities_samples = len(zero_entities_idxes)
|
| 1248 |
+
n_has_entities_samples = len(data_train) - n_zero_entities_samples
|
| 1249 |
+
|
| 1250 |
+
random.seed(42)
|
| 1251 |
+
k = min(int(n_has_entities_samples * zero_entities_rate), len(zero_entities_idxes))
|
| 1252 |
+
sampled_zero_entities_idxes = random.sample(zero_entities_idxes, k)
|
| 1253 |
+
|
| 1254 |
+
new_data_train = []
|
| 1255 |
+
for idx, d in enumerate(data_train):
|
| 1256 |
+
if len(d['entities']) == 0:
|
| 1257 |
+
if idx in sampled_zero_entities_idxes:
|
| 1258 |
+
new_data_train.append(d)
|
| 1259 |
+
else:
|
| 1260 |
+
new_data_train.append(d)
|
| 1261 |
+
data_train = new_data_train
|
| 1262 |
+
|
| 1263 |
+
print('Train:', len(data_train))
|
| 1264 |
+
|
| 1265 |
+
# %% [code]
|
| 1266 |
+
if debug_only:
|
| 1267 |
+
data_train = data_train[:10]
|
| 1268 |
+
data_test = data_test[:10]
|
| 1269 |
+
|
| 1270 |
+
print('Train:', len(data_train))
|
| 1271 |
+
print('Test:', len(data_test))
|
| 1272 |
+
|
| 1273 |
+
# %% [code]
|
| 1274 |
+
tokenizer = AutoTokenizer.from_pretrained(backbone_model_name)
|
| 1275 |
+
|
| 1276 |
+
# %% [code]
|
| 1277 |
+
print('Experiment name:', state_dict_save_name)
|
| 1278 |
+
|
| 1279 |
+
# %% [code]
|
| 1280 |
+
if not test_only:
|
| 1281 |
+
full_idxes = np.array(range(len(data_train)))
|
| 1282 |
+
training_logs, best_models, last_models = [], [], []
|
| 1283 |
+
start_training_time = time.time()
|
| 1284 |
+
for seed in SEEDS:
|
| 1285 |
+
kf = KFold(n_splits=nfolds, shuffle=True, random_state=seed)
|
| 1286 |
+
for fold_idx, (tr_idx, va_idx) in enumerate(kf.split(full_idxes)):
|
| 1287 |
+
if only_fold_idx is not None and only_fold_idx >= 0 and only_fold_idx != fold_idx:
|
| 1288 |
+
continue
|
| 1289 |
+
set_seed(seed)
|
| 1290 |
+
|
| 1291 |
+
train_idxes, val_idxes = full_idxes[tr_idx], full_idxes[va_idx]
|
| 1292 |
+
|
| 1293 |
+
trainset = KLTNDataset(data_train, train_idxes, label2id, tokenizer, **train_memory_params)
|
| 1294 |
+
valset = KLTNDataset(data_train, val_idxes, label2id, tokenizer, **val_memory_params)
|
| 1295 |
+
|
| 1296 |
+
generator = torch.Generator()
|
| 1297 |
+
generator.manual_seed(seed)
|
| 1298 |
+
train_loader = DataLoader(trainset, generator=generator, collate_fn=collate_fn, **train_loader_params)
|
| 1299 |
+
val_loader = DataLoader(valset, generator=generator, collate_fn=collate_fn, **val_loader_params)
|
| 1300 |
+
|
| 1301 |
+
my_model = IEModel(
|
| 1302 |
+
num_labels=len(label2id),
|
| 1303 |
+
**model_params
|
| 1304 |
+
)
|
| 1305 |
+
total_params = sum(p.numel() for p in my_model.parameters())
|
| 1306 |
+
print(f"Total params: {total_params:,}")
|
| 1307 |
+
|
| 1308 |
+
# optimizer, scheduler = configure_optimizers(my_model, optim_params, scheduler_params)
|
| 1309 |
+
encoder_params = set(map(id, my_model.encoder.parameters()))
|
| 1310 |
+
other_params = [
|
| 1311 |
+
p for p in my_model.parameters()
|
| 1312 |
+
if id(p) not in encoder_params
|
| 1313 |
+
]
|
| 1314 |
+
optimizer = optim.AdamW([
|
| 1315 |
+
{"params": my_model.encoder.parameters(), "lr": 2e-5},
|
| 1316 |
+
{"params": other_params}
|
| 1317 |
+
], lr=5e-4)
|
| 1318 |
+
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=20, eta_min=1e-6)
|
| 1319 |
+
|
| 1320 |
+
loss_fn = CustomLoss(
|
| 1321 |
+
**loss_func_params
|
| 1322 |
+
)
|
| 1323 |
+
eval_fn = CustomEvalFn(**eval_func_params)
|
| 1324 |
+
trainer_params['save_name'] = f'{state_dict_save_name}_s{seed}_f{fold_idx}'
|
| 1325 |
+
trainer = Trainer(**trainer_params)
|
| 1326 |
+
|
| 1327 |
+
print(f'Start Training Fold {fold_idx}...')
|
| 1328 |
+
training_log, best_model, last_model = trainer.fit(
|
| 1329 |
+
my_model, optimizer, scheduler, loss_fn, epochs, train_loader, val_loader, eval_fn,
|
| 1330 |
+
start_epoch=1, start_training_time=start_training_time, id2label=id2label
|
| 1331 |
+
)
|
| 1332 |
+
|
| 1333 |
+
training_logs.append(training_log)
|
| 1334 |
+
best_models.append(best_model)
|
| 1335 |
+
last_models.append(last_model)
|
| 1336 |
+
|
| 1337 |
+
# %% [code]
|
| 1338 |
+
def load_all_state_dicts(folder):
|
| 1339 |
+
files = []
|
| 1340 |
+
|
| 1341 |
+
for file in os.listdir(folder):
|
| 1342 |
+
if file.endswith(".pt") or file.endswith(".pth"):
|
| 1343 |
+
m = re.search(r"f(\d+)", file) # tìm f<số>
|
| 1344 |
+
if m:
|
| 1345 |
+
fold = int(m.group(1))
|
| 1346 |
+
files.append((fold, file))
|
| 1347 |
+
|
| 1348 |
+
# sort theo fold
|
| 1349 |
+
files.sort(key=lambda x: x[0])
|
| 1350 |
+
|
| 1351 |
+
state_dicts = []
|
| 1352 |
+
for fold, file in files:
|
| 1353 |
+
path = os.path.join(folder, file)
|
| 1354 |
+
print(f"Loading fold {fold}: {file}")
|
| 1355 |
+
state_dict = torch.load(path, map_location="cpu")
|
| 1356 |
+
state_dicts.append(state_dict)
|
| 1357 |
+
|
| 1358 |
+
return state_dicts
|
| 1359 |
+
|
| 1360 |
+
if test_only:
|
| 1361 |
+
snapshot_download(repo_id=repo_name, local_dir="", repo_type="model", allow_patterns=[f"{state_dict_save_name}/**"])
|
| 1362 |
+
get_ipython().system('rm -rf .cache .gitattributes')
|
| 1363 |
+
|
| 1364 |
+
best_models = load_all_state_dicts(f"{state_dict_save_name}/r1s")
|
| 1365 |
+
last_models = load_all_state_dicts(f"{state_dict_save_name}/lasts")
|
| 1366 |
+
|
| 1367 |
+
# %% [code]
|
| 1368 |
+
os.makedirs(f'{checkpoints_dir}/results', exist_ok=True)
|
| 1369 |
+
testset = KLTNDataset(data_test, range(len(data_test)), label2id, tokenizer, **val_memory_params)
|
| 1370 |
+
generator = torch.Generator()
|
| 1371 |
+
test_loader = DataLoader(testset, generator=generator, collate_fn=collate_fn, **val_loader_params)
|
| 1372 |
+
eval_fn = CustomEvalFn(**eval_func_params)
|
| 1373 |
+
analyzer = SpanErrorAnalyzer()
|
| 1374 |
+
my_model = IEModel(
|
| 1375 |
+
num_labels=len(label2id),
|
| 1376 |
+
**model_params
|
| 1377 |
+
)
|
| 1378 |
+
total_params = sum(p.numel() for p in my_model.parameters())
|
| 1379 |
+
print(f"Total params: {total_params:,}")
|
| 1380 |
+
|
| 1381 |
+
# %% [code]
|
| 1382 |
+
start_time = time.time()
|
| 1383 |
+
result_test = None
|
| 1384 |
+
analyze_result = None
|
| 1385 |
+
|
| 1386 |
+
best_score, best_analyze_result, best_pred_test = test(my_model, best_models, test_loader, eval_fn, analyzer, device, id2label, tokenizer)
|
| 1387 |
+
last_score, last_analyze_result, last_pred_test = test(my_model, last_models, test_loader, eval_fn, analyzer, device, id2label, tokenizer)
|
| 1388 |
+
|
| 1389 |
+
result_test = {"Best model": best_score, "Last model": last_score}
|
| 1390 |
+
analyze_result = {"Best model": best_analyze_result, "Last model": last_analyze_result}
|
| 1391 |
+
analyze_result_sumary = {"Best model": best_analyze_result['summary'], "Last model": last_analyze_result['summary']}
|
| 1392 |
+
pred_test = {"Best model": best_pred_test, "Last model": last_pred_test}
|
| 1393 |
+
|
| 1394 |
+
with open(f"{checkpoints_dir}/results/{state_dict_save_name}_test.json", "w", encoding="utf-8") as f:
|
| 1395 |
+
json.dump(result_test, f, ensure_ascii=False, indent=2)
|
| 1396 |
+
|
| 1397 |
+
with open(f"{checkpoints_dir}/results/{state_dict_save_name}_error_analyze_result.json", "w", encoding="utf-8") as f:
|
| 1398 |
+
json.dump(analyze_result, f, ensure_ascii=False, indent=2)
|
| 1399 |
+
|
| 1400 |
+
with open(f"{checkpoints_dir}/results/{state_dict_save_name}_pred_test.json", "w", encoding="utf-8") as f:
|
| 1401 |
+
json.dump(pred_test, f, ensure_ascii=False, indent=2)
|
| 1402 |
+
|
| 1403 |
+
print('Test:', time.time() - start_time, 's --> Done!')
|
| 1404 |
+
print(json.dumps(analyze_result_sumary, ensure_ascii=False, indent=4))
|
| 1405 |
+
|
| 1406 |
+
# %% [code]
|
| 1407 |
+
best_pred_test[:10]
|
| 1408 |
+
|
| 1409 |
+
# %% [code]
|
| 1410 |
+
last_pred_test[:10]
|
| 1411 |
+
|
| 1412 |
+
# %% [code]
|
| 1413 |
+
def dict_to_df(data):
|
| 1414 |
+
row_tuples = []
|
| 1415 |
+
row_values = []
|
| 1416 |
+
|
| 1417 |
+
metrics = ["precision", "recall", "f1"]
|
| 1418 |
+
|
| 1419 |
+
# Lấy model đầu tiên
|
| 1420 |
+
first_model = next(iter(data.values()))
|
| 1421 |
+
|
| 1422 |
+
# eval_keys
|
| 1423 |
+
eval_keys = list(first_model.keys())
|
| 1424 |
+
|
| 1425 |
+
for eval_key in eval_keys:
|
| 1426 |
+
row_tuples.append(eval_key)
|
| 1427 |
+
row = {}
|
| 1428 |
+
|
| 1429 |
+
for model_name, model_data in data.items():
|
| 1430 |
+
for metric in metrics:
|
| 1431 |
+
row[(model_name, metric)] = model_data[eval_key][metric]
|
| 1432 |
+
|
| 1433 |
+
row_values.append(row)
|
| 1434 |
+
|
| 1435 |
+
# ===== DataFrame =====
|
| 1436 |
+
df = pd.DataFrame(row_values)
|
| 1437 |
+
|
| 1438 |
+
# MultiIndex columns
|
| 1439 |
+
df.columns = pd.MultiIndex.from_tuples(df.columns)
|
| 1440 |
+
|
| 1441 |
+
# Index
|
| 1442 |
+
df.index = pd.Index(row_tuples, name="evaluation")
|
| 1443 |
+
|
| 1444 |
+
# ===== Sort =====
|
| 1445 |
+
sort_keys = []
|
| 1446 |
+
if ("Best model", "f1") in df.columns:
|
| 1447 |
+
sort_keys.append(("Best model", "f1"))
|
| 1448 |
+
if ("Last model", "f1") in df.columns:
|
| 1449 |
+
sort_keys.append(("Last model", "f1"))
|
| 1450 |
+
|
| 1451 |
+
if sort_keys:
|
| 1452 |
+
df = df.sort_values(by=sort_keys, ascending=False)
|
| 1453 |
+
|
| 1454 |
+
return df
|
| 1455 |
+
|
| 1456 |
+
result_test_df = dict_to_df(result_test)
|
| 1457 |
+
result_test_df.to_excel(f"{checkpoints_dir}/results/{state_dict_save_name}_test_df.xlsx")
|
| 1458 |
+
result_test_df
|
| 1459 |
+
|
| 1460 |
+
# %% [code]
|
| 1461 |
+
key = ("Best model", "f1")
|
| 1462 |
+
result_test_df_best = result_test_df.sort_values(by=key, ascending=False).groupby(level="evaluation").head(1)
|
| 1463 |
+
result_test_df_best.to_excel(f"{checkpoints_dir}/results/{state_dict_save_name}_test_df_best.xlsx")
|
| 1464 |
+
result_test_df_best
|
| 1465 |
+
|
| 1466 |
+
# %% [code]
|
| 1467 |
+
def get_avg_best_score(logs):
|
| 1468 |
+
return float(np.mean([list(log.values())[-1]['best_score'] for log in logs]))
|
| 1469 |
+
|
| 1470 |
+
def get_avg_log(logs, epochs):
|
| 1471 |
+
avg_log = {}
|
| 1472 |
+
|
| 1473 |
+
for epoch in range(1, epochs + 1):
|
| 1474 |
+
val_score = 0.0
|
| 1475 |
+
train_loss = 0.0
|
| 1476 |
+
n_eval = 0
|
| 1477 |
+
|
| 1478 |
+
for idx in range(len(logs)):
|
| 1479 |
+
log = logs[idx].get(epoch, logs[idx].get(str(epoch)))
|
| 1480 |
+
if log is None:
|
| 1481 |
+
continue
|
| 1482 |
+
|
| 1483 |
+
val_score += log.get('val_score', 0.0)
|
| 1484 |
+
train_loss += log.get('train_loss', 0.0)
|
| 1485 |
+
n_eval += 1
|
| 1486 |
+
|
| 1487 |
+
if n_eval == 0:
|
| 1488 |
+
continue
|
| 1489 |
+
|
| 1490 |
+
avg_log[epoch] = {
|
| 1491 |
+
'train_loss': train_loss / n_eval,
|
| 1492 |
+
'val_score': val_score / n_eval if val_score != 0 else float('inf')
|
| 1493 |
+
}
|
| 1494 |
+
|
| 1495 |
+
return avg_log
|
| 1496 |
+
|
| 1497 |
+
def parse_label_key(label: str):
|
| 1498 |
+
try:
|
| 1499 |
+
first = float(label.split('_', 1)[0]) # số đầu: trước dấu _
|
| 1500 |
+
last = float(re.findall(r'_(\d+(?:\.\d+)?)$', label)[0])
|
| 1501 |
+
return first, last
|
| 1502 |
+
except:
|
| 1503 |
+
return (0, 0)
|
| 1504 |
+
|
| 1505 |
+
def plot_training_logs(logs_dict, save_path=None, figsize=(24, 10)):
|
| 1506 |
+
fig, axes = plt.subplots(1, 2, figsize=figsize)
|
| 1507 |
+
|
| 1508 |
+
# ===== Plot Train Loss =====
|
| 1509 |
+
for name, log in logs_dict.items():
|
| 1510 |
+
epochs = sorted(log.keys())
|
| 1511 |
+
train_loss = [log[e]['train_loss'] for e in epochs]
|
| 1512 |
+
axes[0].plot(epochs, train_loss, label=name)
|
| 1513 |
+
|
| 1514 |
+
axes[0].set_xlabel('Epoch')
|
| 1515 |
+
axes[0].set_ylabel('Train Loss')
|
| 1516 |
+
axes[0].set_title('Training Loss')
|
| 1517 |
+
axes[0].grid(True)
|
| 1518 |
+
|
| 1519 |
+
# ===== Plot Validation Score =====
|
| 1520 |
+
for name, log in logs_dict.items():
|
| 1521 |
+
epochs = sorted(log.keys())
|
| 1522 |
+
val_score = [log[e]['val_score'] for e in epochs]
|
| 1523 |
+
axes[1].plot(epochs, val_score, label=name)
|
| 1524 |
+
|
| 1525 |
+
axes[1].set_xlabel('Epoch')
|
| 1526 |
+
axes[1].set_ylabel('Validation Score')
|
| 1527 |
+
axes[1].set_title('Validation Score')
|
| 1528 |
+
axes[1].grid(True)
|
| 1529 |
+
|
| 1530 |
+
# ===== Shared Legend =====
|
| 1531 |
+
handles, labels = axes[0].get_legend_handles_labels()
|
| 1532 |
+
pairs = list(zip(handles, labels))
|
| 1533 |
+
pairs_sorted = sorted(
|
| 1534 |
+
pairs,
|
| 1535 |
+
key=lambda x: parse_label_key(x[1])
|
| 1536 |
+
)
|
| 1537 |
+
handles_sorted, labels_sorted = zip(*pairs_sorted)
|
| 1538 |
+
|
| 1539 |
+
axes[0].legend(
|
| 1540 |
+
handles_sorted,
|
| 1541 |
+
labels_sorted,
|
| 1542 |
+
loc='center left',
|
| 1543 |
+
bbox_to_anchor=(1.01, 0.5),
|
| 1544 |
+
borderaxespad=0.
|
| 1545 |
+
)
|
| 1546 |
+
|
| 1547 |
+
plt.tight_layout(rect=[0, 0, 1, 1])
|
| 1548 |
+
|
| 1549 |
+
if save_path is not None:
|
| 1550 |
+
os.makedirs(os.path.dirname(save_path), exist_ok=True) if os.path.dirname(save_path) else None
|
| 1551 |
+
plt.savefig(save_path, dpi=300, bbox_inches='tight')
|
| 1552 |
+
|
| 1553 |
+
plt.show()
|
| 1554 |
+
|
| 1555 |
+
# %% [code]
|
| 1556 |
+
if not test_only:
|
| 1557 |
+
snapshot_download(repo_id=repo_name, local_dir="", repo_type="model", allow_patterns=["**/*.json"], ignore_patterns=["5_score_span_base_12/**"])
|
| 1558 |
+
get_ipython().system('rm -rf .cache .gitattributes')
|
| 1559 |
+
|
| 1560 |
+
# %% [code]
|
| 1561 |
+
if not test_only:
|
| 1562 |
+
experiments = {}
|
| 1563 |
+
for experiment in os.listdir(pretrained_dir):
|
| 1564 |
+
experiment_logs = []
|
| 1565 |
+
try:
|
| 1566 |
+
for seed in SEEDS:
|
| 1567 |
+
for fold_idx in range(nfolds):
|
| 1568 |
+
with open(f"{pretrained_dir}/{experiment}/logs/{experiment}_s{seed}_f{fold_idx}_logging.json", "r", encoding="utf-8") as f:
|
| 1569 |
+
experiment_log = json.load(f)
|
| 1570 |
+
experiment_logs.append(experiment_log)
|
| 1571 |
+
except:
|
| 1572 |
+
pass
|
| 1573 |
+
experiments[experiment] = get_avg_log(experiment_logs, 1000)
|
| 1574 |
+
experiments[state_dict_save_name] = get_avg_log(training_logs, 1000)
|
| 1575 |
+
|
| 1576 |
+
# %% [code]
|
| 1577 |
+
if not test_only:
|
| 1578 |
+
score = get_avg_best_score(training_logs)
|
| 1579 |
+
state_dict_save_name, score
|
| 1580 |
+
|
| 1581 |
+
# %% [code]
|
| 1582 |
+
if not test_only:
|
| 1583 |
+
plot_training_logs(experiments, save_path=f'{checkpoints_dir}/logs/{state_dict_save_name}_log_plot.jpg', figsize=(18, 7.5))
|
| 1584 |
+
|
0_token_base_1/lasts/0_token_base_1_s26092004_f0_last_ema.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f6b4f3e9c11edda601075e938d31ba1127499c02fdf2f14be32e82e44e126a27
|
| 3 |
+
size 542468054
|
0_token_base_1/logs/0_token_base_1_log_plot.jpg
ADDED
|
Git LFS Details
|
0_token_base_1/logs/0_token_base_1_s26092004_f0_logging.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"1": {"lr": [2e-05, 0.0005], "train_loss": 0.2877526581287384, "total": 0.2877526585869793, "ce_loss": 0.2877526585869793}, "2": {"lr": [1.988303923565381e-05, 0.0004969282409784868], "train_loss": 0.22474944591522217, "total": 0.22474944701500035, "ce_loss": 0.22474944701500035}, "3": {"lr": [1.9535036904803962e-05, 0.0004877886008156408], "train_loss": 0.20345450937747955, "total": 0.20345450794026942, "ce_loss": 0.20345450794026942}, "4": {"lr": [1.8964561979789496e-05, 0.00047280612778499774], "train_loss": 0.18108795583248138, "total": 0.1810879471384016, "ce_loss": 0.1810879471384016}, "5": {"lr": [1.8185661446562005e-05, 0.00045234974009654937], "train_loss": 0.16032394766807556, "total": 0.1603239473764677, "ce_loss": 0.1603239473764677}, "6": {"lr": [1.7217514421272206e-05, 0.00042692314190604356], "train_loss": 0.1369016468524933, "total": 0.13690165071004856, "ce_loss": 0.13690165071004856}, "7": {"lr": [1.60839598967785e-05, 0.00039715242044697206], "train_loss": 0.11945560574531555, "total": 0.11945560360408077, "ce_loss": 0.11945560360408077}, "8": {"lr": [1.4812909747525698e-05, 0.00036377062968501693], "train_loss": 0.10287890583276749, "total": 0.10287890222307887, "ce_loss": 0.10287890222307887, "val_score": 0.6173268584910394, "best_score": 0.6173268584910394, "new_best_model": true, "precision": 0.5641288881617769, "recall": 0.6881571321269238, "f1": 0.6173268584910394}, "9": {"lr": [1.3435661446562005e-05, 0.0003275997400965494], "train_loss": 0.08786451071500778, "total": 0.08786450973395565, "ce_loss": 0.08786450973395565, "val_score": 0.61592991284283, "best_score": 0.6173268584910394, "new_best_model": false, "precision": 0.5623741657552976, "recall": 0.6872018892852987, "f1": 0.61592991284283}, "10": {"lr": [1.1986127417882198e-05, 0.00028953039902753766], "train_loss": 0.07498892396688461, "total": 0.07498892426057538, "ce_loss": 0.07498892426057538, "val_score": 0.6020835850884332, "best_score": 0.6173268584910394, "new_best_model": false, "precision": 0.5404392968223765, "recall": 0.6862193054434863, "f1": 0.6020835850884332}, "11": {"lr": [1.0500000000000003e-05, 0.0002505], "train_loss": 0.06471537053585052, "total": 0.06471536544104478, "ce_loss": 0.06471536544104478, "val_score": 0.604033936146747, "best_score": 0.6173268584910394, "new_best_model": false, "precision": 0.5457055753524663, "recall": 0.6830324171553736, "f1": 0.604033936146747}, "12": {"lr": [9.013872582117811e-06, 0.00021146960097246246], "train_loss": 0.0551924966275692, "total": 0.055192494679003876, "ce_loss": 0.055192494679003876, "val_score": 0.6085737961105119, "best_score": 0.6173268584910394, "new_best_model": false, "precision": 0.5532009703337809, "recall": 0.6827077537782777, "f1": 0.6085737961105119}, "13": {"lr": [7.564338553438001e-06, 0.00017340025990345064], "train_loss": 0.04856348782777786, "total": 0.04856348717582602, "ce_loss": 0.04856348717582602, "val_score": 0.597655643574234, "best_score": 0.6173268584910394, "new_best_model": false, "precision": 0.5358696300290579, "recall": 0.6818684366372572, "f1": 0.597655643574234}, "14": {"lr": [6.1870902524743065e-06, 0.00013722937031498307], "train_loss": 0.04176052287220955, "total": 0.041760520092561856, "ce_loss": 0.041760520092561856, "val_score": 0.5910164918654537, "best_score": 0.6173268584910394, "new_best_model": false, "precision": 0.5261490425955163, "recall": 0.6807002604968033, "f1": 0.5910164918654537}, "15": {"lr": [4.916040103221507e-06, 0.00010384757955302797], "train_loss": 0.03716704621911049, "total": 0.03716704443509532, "ce_loss": 0.03716704443509532, "val_score": 0.5937218527391015, "best_score": 0.6173268584910394, "new_best_model": false, "precision": 0.5303045959132107, "recall": 0.6810958089377324, "f1": 0.5937218527391015}, "16": {"lr": [3.7824855787278e-06, 7.40768580939564e-05], "train_loss": 0.033100537955760956, "total": 0.03310053875768255, "ce_loss": 0.03310053875768255, "val_score": 0.5950873769827215, "best_score": 0.6173268584910394, "new_best_model": false, "precision": 0.5333717067725937, "recall": 0.6791756927969689, "f1": 0.5950873769827215}, "17": {"lr": [2.814338553438001e-06, 4.865025990345063e-05], "train_loss": 0.030147330835461617, "total": 0.03014732960185626, "ce_loss": 0.03014732960185626, "val_score": 0.6007965273711894, "best_score": 0.6173268584910394, "new_best_model": false, "precision": 0.5436904783246468, "recall": 0.6778941141353022, "f1": 0.6007965273711894}, "18": {"lr": [2.0354380202105066e-06, 2.8193872215002235e-05], "train_loss": 0.027554500848054886, "total": 0.02755450002634562, "ce_loss": 0.02755450002634562, "val_score": 0.6028197421071835, "best_score": 0.6173268584910394, "new_best_model": false, "precision": 0.5475455566169432, "recall": 0.6768142100578927, "f1": 0.6028197421071835}}
|
0_token_base_1/r1s/0_token_base_1_s26092004_f0_r1_vs0.61733_ema.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c02202997f34612c9a2679990be20ce06236cb63b2948d2fbc1028fe9df646d0
|
| 3 |
+
size 542469726
|
0_token_base_1/results/0_token_base_1_error_analyze_result.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
0_token_base_1/results/0_token_base_1_pred_test.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
0_token_base_1/results/0_token_base_1_test.json
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"Best model": {
|
| 3 |
+
"Ent-I": {
|
| 4 |
+
"precision": 0.539593134980757,
|
| 5 |
+
"recall": 0.7568547262749726,
|
| 6 |
+
"f1": 0.6300193374996995
|
| 7 |
+
},
|
| 8 |
+
"Ent-C": {
|
| 9 |
+
"precision": 0.4887696283041882,
|
| 10 |
+
"recall": 0.6850218218955473,
|
| 11 |
+
"f1": 0.57048951644472
|
| 12 |
+
}
|
| 13 |
+
},
|
| 14 |
+
"Last model": {
|
| 15 |
+
"Ent-I": {
|
| 16 |
+
"precision": 0.5180575261185876,
|
| 17 |
+
"recall": 0.7466307277621093,
|
| 18 |
+
"f1": 0.6116885540815726
|
| 19 |
+
},
|
| 20 |
+
"Ent-C": {
|
| 21 |
+
"precision": 0.4657940550645007,
|
| 22 |
+
"recall": 0.6708143745931183,
|
| 23 |
+
"f1": 0.54981352739455
|
| 24 |
+
}
|
| 25 |
+
}
|
| 26 |
+
}
|
0_token_base_1/results/0_token_base_1_test_df.xlsx
ADDED
|
Binary file (5.29 kB). View file
|
|
|
0_token_base_1/results/0_token_base_1_test_df_best.xlsx
ADDED
|
Binary file (5.29 kB). View file
|
|
|