SS3M commited on
Commit
bebba7c
·
verified ·
1 Parent(s): 99cc327

Upload 0_entities_phoner_1's state dict

Browse files
.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_entities_phoner_1/logs/0_entities_phoner_1_log_plot.jpg filter=lfs diff=lfs merge=lfs -text
0_entities_phoner_1/0_entities_phoner_1.py ADDED
@@ -0,0 +1,1901 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = 'phoner' # 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 = 32
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-ie-experiments'
82
+ state_dict_save_name = "0_entities_phoner_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 = 3 if dataset in ['kltn/raw'] else 1
112
+ max_span_len = 14
113
+ zero_entities_rate = zero_entities_rate_dict[dataset]
114
+ n_negs = 50
115
+
116
+ # Trainer
117
+ trainer_params = {
118
+ "training_time": "00:11:30:00",
119
+ "eval_mode": "max",
120
+ "topk": topk,
121
+ "save_name": state_dict_save_name,
122
+ "save_best": True,
123
+ "save_last": True,
124
+ "device": device,
125
+ "logging": True,
126
+ "logging_file": True,
127
+ "checkpoints_dir": checkpoints_dir,
128
+ "early_stopping": 30,
129
+ "eval_from_ratio": 0.4,
130
+ "eval_every": 1,
131
+ "schedule_in_step": False,
132
+ "use_ema": True,
133
+ "ema_from_ratio": 0.3,
134
+ "ema_decay": 0.9995,
135
+ "max_grad_norm": 200.0,
136
+ "return_best": True,
137
+ "return_last": True,
138
+ }
139
+
140
+ # Memory
141
+ train_memory_params = {
142
+ 'max_len': max_len,
143
+ 'max_n_parts': max_n_parts,
144
+ 'max_span_len': max_span_len,
145
+ 'n_negs': n_negs,
146
+ 'weight_sampling': True,
147
+ }
148
+ val_memory_params = {
149
+ 'max_len': max_len,
150
+ 'max_n_parts': max_n_parts,
151
+ 'max_span_len': max_span_len,
152
+ 'n_negs': n_negs,
153
+ 'weight_sampling': True,
154
+ }
155
+
156
+ # Data Loader
157
+ def seed_worker(worker_id):
158
+ worker_seed = torch.initial_seed() % 2**32
159
+ np.random.seed(worker_seed)
160
+ random.seed(worker_seed)
161
+
162
+ train_loader_params = {
163
+ 'batch_size': batch_size,
164
+ 'shuffle': True,
165
+ 'pin_memory':True,
166
+ 'num_workers': 2,
167
+ 'drop_last': False,
168
+ 'worker_init_fn': seed_worker,
169
+ 'persistent_workers': False,
170
+ }
171
+ val_loader_params = {
172
+ 'batch_size': batch_size,
173
+ 'shuffle': False,
174
+ 'pin_memory':True,
175
+ 'num_workers': 1,
176
+ 'drop_last': False,
177
+ 'worker_init_fn': seed_worker,
178
+ 'persistent_workers': False,
179
+ }
180
+
181
+ # Model
182
+ model_params = {
183
+ 'backbone_model_name': backbone_model_name,
184
+ 'keep_neighbor': 0,
185
+ }
186
+
187
+ # Loss Func
188
+ loss_func_params = {
189
+ 'pos_weight': 1.0,
190
+ }
191
+ eval_func_params = {}
192
+
193
+ # Optim
194
+ optim_params = {
195
+ 'name': 'AdamW',
196
+ 'lr': 1e-4,
197
+ 'weight_decay': 1e-4,
198
+ }
199
+ scheduler_params = {
200
+ 'name': 'CosineAnnealingLR',
201
+ 'T_max': 20, # Số epoch để hoàn thành một chu kỳ giảm LR
202
+ 'eta_min': 1e-6 # Learning rate nhỏ nhất trong chu kỳ
203
+ }
204
+
205
+ # %% [code]
206
+ def set_seed(seed=42):
207
+ random.seed(seed)
208
+ np.random.seed(seed)
209
+ torch.manual_seed(seed)
210
+ torch.cuda.manual_seed(seed)
211
+ torch.cuda.manual_seed_all(seed) # if using multi-GPU
212
+ torch.use_deterministic_algorithms(False)
213
+ torch.backends.cudnn.deterministic = True
214
+ torch.backends.cudnn.benchmark = False
215
+ os.environ['PYTHONHASHSEED'] = str(seed)
216
+
217
+ # %% [code]
218
+ class CustomLoss(nn.Module):
219
+ def __init__(
220
+ self,
221
+ pos_weight=1.0,
222
+ ):
223
+ super().__init__()
224
+
225
+ self.pos_weight = pos_weight
226
+
227
+ def forward(
228
+ self,
229
+ logits,
230
+ labels,
231
+ ):
232
+ device = logits.device
233
+
234
+ B, N, C = logits.shape
235
+
236
+ flat_logits = logits.reshape(-1, C)
237
+ flat_labels = labels.reshape(-1)
238
+
239
+ if (flat_labels != -100).any():
240
+ weight = torch.ones(C, device=device)
241
+ weight[1:] = self.pos_weight
242
+
243
+ ce = nn.CrossEntropyLoss(
244
+ ignore_index=-100,
245
+ weight=weight
246
+ )
247
+
248
+ span_loss = ce(flat_logits, flat_labels)
249
+
250
+ else:
251
+ span_loss = logits.new_tensor(0.0)
252
+
253
+ total_loss = span_loss
254
+
255
+ return {
256
+ "total": total_loss,
257
+ "span_loss": span_loss,
258
+ }
259
+
260
+ # %% [code]
261
+ ## Viết eval_fn vào đây
262
+
263
+ # Bỏ hết eval_fn và trọng số vào đây
264
+ class CustomEvalFn(nn.Module):
265
+ def __init__(self):
266
+ super().__init__()
267
+
268
+ def compute_f1(self, tp, fp, fn):
269
+ precision = tp / (tp + fp + 1e-8)
270
+ recall = tp / (tp + fn + 1e-8)
271
+ f1 = 2 * precision * recall / (precision + recall + 1e-8)
272
+ return precision, recall, f1
273
+
274
+ def forward(self, pred, gold):
275
+ pred_set = set(pred)
276
+ gold_set = set(gold)
277
+
278
+ tp = len(pred_set & gold_set)
279
+ fp = len(pred_set - gold_set)
280
+ fn = len(gold_set - pred_set)
281
+
282
+ precision, recall, f1 = self.compute_f1(tp, fp, fn)
283
+
284
+ return {
285
+ f"precision": precision,
286
+ f"recall": recall,
287
+ f"f1": f1,
288
+ }
289
+
290
+ class SpanErrorAnalyzer:
291
+ def __init__(self, pad_token_id=0):
292
+ self.pad_token_id = pad_token_id
293
+
294
+ # ===== helper =====
295
+ def _to_set(self, data):
296
+ """
297
+ data: list of (b, tuple(ids))
298
+ -> dict[b] = set(tuple(ids))
299
+ """
300
+ res = defaultdict(set)
301
+ for b, ids in data:
302
+ ids = tuple([i for i in ids if i != self.pad_token_id])
303
+ if len(ids) > 0:
304
+ res[b].add(ids)
305
+ return res
306
+
307
+ def _iou(self, a, b):
308
+ """
309
+ a, b: tuple(ids)
310
+ """
311
+ set_a, set_b = set(a), set(b)
312
+ inter = len(set_a & set_b)
313
+ union = len(set_a | set_b)
314
+ if union == 0:
315
+ return 0.0
316
+ return inter / union
317
+
318
+ def _boundary_error(self, pred, gold):
319
+ """
320
+ đo lệch boundary dựa trên overlap prefix/suffix
321
+ """
322
+ # left match
323
+ left = 0
324
+ for i in range(min(len(pred), len(gold))):
325
+ if pred[i] == gold[i]:
326
+ left += 1
327
+ else:
328
+ break
329
+
330
+ # right match
331
+ right = 0
332
+ for i in range(1, min(len(pred), len(gold)) + 1):
333
+ if pred[-i] == gold[-i]:
334
+ right += 1
335
+ else:
336
+ break
337
+
338
+ return {
339
+ "left_match": left,
340
+ "right_match": right,
341
+ "pred_len": len(pred),
342
+ "gold_len": len(gold),
343
+ }
344
+
345
+ # ===== main =====
346
+ def analyze(self, preds, golds):
347
+ pred_map = self._to_set(preds)
348
+ gold_map = self._to_set(golds)
349
+
350
+ all_batches = set(pred_map.keys()) | set(gold_map.keys())
351
+
352
+ stats = Counter()
353
+
354
+ detailed_errors = []
355
+
356
+ for b in all_batches:
357
+ pset = pred_map.get(b, set())
358
+ gset = gold_map.get(b, set())
359
+
360
+ matched_gold = set()
361
+
362
+ # ===== check predictions =====
363
+ for p in pset:
364
+ if p in gset:
365
+ stats["exact_match"] += 1
366
+ matched_gold.add(p)
367
+ else:
368
+ # tìm gold gần nhất
369
+ best_iou = 0
370
+ best_g = None
371
+
372
+ for g in gset:
373
+ iou = self._iou(p, g)
374
+ if iou > best_iou:
375
+ best_iou = iou
376
+ best_g = g
377
+
378
+ if best_iou > 0:
379
+ stats["partial_match"] += 1
380
+
381
+ boundary = self._boundary_error(p, best_g)
382
+
383
+ detailed_errors.append({
384
+ "type": "boundary_error",
385
+ "batch": b,
386
+ "pred": p,
387
+ "gold": best_g,
388
+ "iou": best_iou,
389
+ **boundary
390
+ })
391
+ else:
392
+ if b not in gold_map:
393
+ stats["no_event_sample"] += 1
394
+ err_type = "no_event_sample"
395
+ else:
396
+ stats["completely_wrong"] += 1
397
+ err_type = "completely_wrong"
398
+
399
+ detailed_errors.append({
400
+ "type": err_type,
401
+ "batch": b,
402
+ "pred": p
403
+ })
404
+
405
+ # ===== check missing =====
406
+ for g in gset:
407
+ if g not in matched_gold:
408
+ # check if any pred overlaps
409
+ overlap = any(self._iou(p, g) > 0 for p in pset)
410
+
411
+ if overlap:
412
+ stats["miss_with_overlap"] += 1
413
+ else:
414
+ stats["miss"] += 1
415
+
416
+ detailed_errors.append({
417
+ "type": "miss",
418
+ "batch": b,
419
+ "gold": g
420
+ })
421
+
422
+ return {
423
+ "summary": {
424
+ "exact_match": (stats["exact_match"], stats["exact_match"] / len(preds)),
425
+ "partial_match": (stats["partial_match"], stats["partial_match"] / len(preds)),
426
+ "no_event_sample": (stats["no_event_sample"], stats["no_event_sample"] / len(preds)),
427
+ "completely_wrong": (stats["completely_wrong"], stats["completely_wrong"] / len(preds)),
428
+ "miss": (stats["miss"], stats["miss"] / len(golds)),
429
+ "miss_with_overlap": (stats["miss_with_overlap"], stats["miss_with_overlap"] / len(golds)),
430
+ },
431
+ "details": detailed_errors
432
+ }
433
+
434
+ # %% [code]
435
+ class DataParallelProxy(nn.DataParallel):
436
+ def __getattr__(self, name):
437
+ try:
438
+ return super().__getattr__(name)
439
+
440
+ except AttributeError:
441
+
442
+ attr = getattr(self.module, name)
443
+
444
+ if callable(attr):
445
+
446
+ def wrapper(*args, **kwargs):
447
+ return self._parallel_apply_method(
448
+ name,
449
+ *args,
450
+ **kwargs
451
+ )
452
+
453
+ return wrapper
454
+
455
+ return attr
456
+
457
+ def _parallel_apply_method(self, method_name, *inputs, **kwargs):
458
+ if not self.device_ids:
459
+ return getattr(self.module, method_name)(*inputs, **kwargs)
460
+
461
+ inputs_scattered, kwargs_scattered = self.scatter(
462
+ inputs,
463
+ kwargs,
464
+ self.device_ids
465
+ )
466
+
467
+ replicas = self.replicate(
468
+ self.module,
469
+ self.device_ids[:len(inputs_scattered)]
470
+ )
471
+
472
+ outputs = self.parallel_apply(
473
+ [getattr(replica, method_name) for replica in replicas],
474
+ inputs_scattered,
475
+ kwargs_scattered
476
+ )
477
+
478
+ return self._custom_gather(outputs, self.output_device)
479
+
480
+ def gather(self, outputs, output_device):
481
+ return self._custom_gather(outputs, output_device)
482
+
483
+ def _custom_gather(self, outputs, output_device):
484
+ first = outputs[0]
485
+
486
+ if torch.is_tensor(first):
487
+ return self._gather_tensor(outputs, output_device)
488
+
489
+ if isinstance(first, tuple):
490
+ return tuple(
491
+ self._custom_gather(
492
+ list(items),
493
+ output_device
494
+ )
495
+ for items in zip(*outputs)
496
+ )
497
+
498
+ if isinstance(first, list):
499
+ if len(first) > 0 and torch.is_tensor(first[0]):
500
+ return self._gather_tensor_list(outputs, output_device)
501
+
502
+ merged = []
503
+ for out in outputs:
504
+ merged.extend(out)
505
+ return merged
506
+
507
+ if isinstance(first, dict):
508
+ return {
509
+ k: self._custom_gather(
510
+ [o[k] for o in outputs],
511
+ output_device
512
+ )
513
+ for k in first.keys()
514
+ }
515
+ return outputs
516
+
517
+ def _gather_tensor(self, tensors, output_device):
518
+ tensors = [
519
+ t.to(output_device)
520
+ for t in tensors
521
+ ]
522
+
523
+ try:
524
+ return torch.cat(tensors, dim=0)
525
+ except RuntimeError:
526
+ pass
527
+
528
+ max_shape = list(tensors[0].shape)
529
+ for t in tensors[1:]:
530
+ for d in range(len(max_shape)):
531
+ max_shape[d] = max(max_shape[d], t.shape[d])
532
+
533
+ padded = []
534
+ for t in tensors:
535
+ pad = []
536
+
537
+ for d in reversed(range(len(max_shape))):
538
+ if d == 0:
539
+ pad.extend([0, 0])
540
+ continue
541
+
542
+ diff = max_shape[d] - t.shape[d]
543
+ pad.extend([0, diff])
544
+
545
+ t = F.pad(t, pad)
546
+ padded.append(t)
547
+ return torch.cat(padded, dim=0)
548
+
549
+ def _gather_tensor_list(self, outputs, output_device):
550
+ merged = []
551
+
552
+ for out in outputs:
553
+ merged.extend(out)
554
+
555
+ return self._gather_tensor(merged, output_device)
556
+
557
+ # %% [code]
558
+ class SpanExtractor(nn.Module):
559
+ def __init__(self, hidden_size):
560
+ super().__init__()
561
+
562
+ self.start_proj = MLP(hidden_size, hidden_size, hidden_size)
563
+ self.end_proj = MLP(hidden_size, hidden_size, hidden_size)
564
+
565
+ self.span_attn = nn.Sequential(
566
+ nn.Linear(hidden_size, hidden_size),
567
+ nn.GELU(),
568
+ nn.Linear(hidden_size, 1)
569
+ )
570
+
571
+ def forward(self, hidden_states, spans):
572
+ B, L, H = hidden_states.shape
573
+ N = spans.size(1)
574
+
575
+ start_hidden = self.start_proj(hidden_states)
576
+ end_hidden = self.end_proj(hidden_states)
577
+
578
+ batch_idx = torch.arange(B, device=hidden_states.device).unsqueeze(1)
579
+ start_idx = spans[..., 0]
580
+ end_idx = spans[..., 1]
581
+
582
+ start_h = start_hidden[batch_idx, start_idx]
583
+ end_h = end_hidden[batch_idx, end_idx]
584
+
585
+ token_idx = torch.arange(L, device=hidden_states.device).view(1, 1, L)
586
+ span_mask = (token_idx >= start_idx.unsqueeze(-1)) & (token_idx <= end_idx.unsqueeze(-1))
587
+
588
+ attn_scores = self.span_attn(hidden_states).squeeze(-1).unsqueeze(1).expand(-1, N, -1)
589
+ attn_scores = attn_scores.masked_fill(~span_mask, float('-inf'))
590
+ attn_weights = torch.softmax(attn_scores, dim=-1)
591
+ span_context = torch.einsum("bnl,blh->bnh", attn_weights, hidden_states)
592
+
593
+ span_repr = torch.cat([start_h, end_h, end_h - start_h, end_h * start_h, span_context], dim=-1)
594
+
595
+ return span_repr
596
+
597
+ class MLP(nn.Module):
598
+ def __init__(self, in_size, hid_size, out_size, dropout=0.1):
599
+ super().__init__()
600
+
601
+ self.input_proj = nn.Identity() if in_size == hid_size else nn.Linear(in_size, hid_size)
602
+
603
+ self.block = nn.Sequential(
604
+ nn.Linear(hid_size, hid_size),
605
+ nn.LayerNorm(hid_size),
606
+ nn.GELU(),
607
+ nn.Dropout(dropout),
608
+
609
+ nn.Linear(hid_size, hid_size),
610
+ nn.LayerNorm(hid_size),
611
+ nn.GELU(),
612
+ nn.Dropout(dropout),
613
+ )
614
+
615
+ self.out = nn.Linear(hid_size, out_size)
616
+
617
+ def forward(self, x):
618
+ x = self.input_proj(x)
619
+ x = x + self.block(x) # residual
620
+ return self.out(x)
621
+
622
+ class IEModel(nn.Module):
623
+ def __init__(self, backbone_model_name, num_labels, keep_neighbor):
624
+ super().__init__()
625
+
626
+ self.encoder = AutoModel.from_pretrained(backbone_model_name)
627
+ hidden_size = self.encoder.config.hidden_size
628
+
629
+ self.span_extractor = SpanExtractor(hidden_size)
630
+ self.spans_classifier = MLP(5 * hidden_size, hidden_size, num_labels)
631
+
632
+ def encode(self, input_ids, attention_mask):
633
+ B, n_parts, L = input_ids.shape
634
+
635
+ input_ids = input_ids.view(-1, L)
636
+ attention_mask = attention_mask.view(-1, L)
637
+
638
+ outputs = self.encoder(input_ids=input_ids, attention_mask=attention_mask)
639
+ hidden_states = outputs.last_hidden_state
640
+
641
+ hidden_states = hidden_states.view(B, n_parts, L, -1).reshape(B, n_parts * L, -1)
642
+ return hidden_states
643
+
644
+ def get_span_logits(self, span_reprs):
645
+ return self.spans_classifier(span_reprs)
646
+
647
+ def forward(self, input_ids, attention_mask, sampled_spans):
648
+ hidden_states = self.encode(input_ids, attention_mask)
649
+
650
+ span_reprs = self.span_extractor(hidden_states, sampled_spans)
651
+ span_logits = self.get_span_logits(span_reprs)
652
+ return span_logits
653
+
654
+ def test_model():
655
+ model = nn.DataParallel(IEModel(backbone_model_name, 17, 0)).to(device)
656
+ model.eval()
657
+ total_params = sum(p.numel() for p in model.parameters())
658
+ print(f"Total params: {total_params:,}")
659
+
660
+ vocab_size = model.module.encoder.config.vocab_size
661
+ max_len = model.module.encoder.config.max_position_embeddings
662
+
663
+ bz = 32
664
+ i = torch.randint(0, vocab_size, (bz, 5, 10)).to(device)
665
+ a = torch.ones(bz, 5, 10).to(device)
666
+ s = torch.ones(bz, 3, 2, dtype=torch.long).to(device)
667
+ gs = torch.ones(bz, 3, 2, dtype=torch.long).to(device)
668
+
669
+ with torch.no_grad():
670
+ r = model(i, a, s)
671
+
672
+ if type(r) == tuple:
673
+ print([r[i].shape if type(r[i]) == type(torch.Tensor()) else len(r[i]) for i in range(len(r))])
674
+ else:
675
+ print(r.shape)
676
+
677
+ test_model()
678
+
679
+ # %% [code]
680
+ def configure_optimizers(network, optim_params, scheduler_params):
681
+ try:
682
+ optim_params = copy.copy(optim_params)
683
+ scheduler_params = copy.copy(scheduler_params)
684
+
685
+ optim_name = optim_params.pop('name')
686
+ scheduler_name = scheduler_params.pop('name')
687
+
688
+ optimizer_cls = globals().get(optim_name) or getattr(optim, optim_name, None)
689
+ scheduler_cls = globals().get(scheduler_name) or getattr(optim.lr_scheduler, scheduler_name, None)
690
+
691
+ if optimizer_cls is None:
692
+ raise ValueError(f"Optimizer '{optim_name}' is not available!")
693
+
694
+ optimizer = optimizer_cls(network.parameters(), **optim_params)
695
+
696
+ scheduler = None
697
+ if scheduler_params and scheduler_cls: # Chỉ tạo scheduler nếu có tham số
698
+ scheduler = scheduler_cls(optimizer, **scheduler_params)
699
+
700
+ return optimizer, scheduler
701
+
702
+ except KeyError as e:
703
+ raise ValueError(f"Missing {e} in config!!")
704
+
705
+ def freeze(self, model):
706
+ model.eval()
707
+ for param in model.parameters():
708
+ param.requires_grad = False
709
+
710
+ def unfreeze(self, model):
711
+ model.train()
712
+ for param in model.parameters():
713
+ param.requires_grad = True
714
+
715
+ def reduce_batch_size(loader, ratio=0.5):
716
+ new_bs = max(1, int(loader.batch_size * ratio))
717
+
718
+ shuffle = isinstance(loader.sampler, RandomSampler)
719
+
720
+ new_loader = DataLoader(
721
+ dataset=loader.dataset,
722
+ batch_size=new_bs,
723
+ shuffle=shuffle,
724
+ sampler=None if shuffle else loader.sampler,
725
+ num_workers=loader.num_workers,
726
+ collate_fn=loader.collate_fn,
727
+ pin_memory=loader.pin_memory,
728
+ drop_last=loader.drop_last,
729
+ timeout=loader.timeout,
730
+ worker_init_fn=loader.worker_init_fn,
731
+ multiprocessing_context=loader.multiprocessing_context,
732
+ generator=loader.generator,
733
+ prefetch_factor=loader.prefetch_factor if loader.num_workers > 0 else None,
734
+ persistent_workers=loader.persistent_workers,
735
+ pin_memory_device=loader.pin_memory_device
736
+ )
737
+
738
+ return new_loader
739
+
740
+ def list_to_tuple(x):
741
+ if isinstance(x, (list, tuple)):
742
+ return tuple(list_to_tuple(i) for i in x)
743
+ return x
744
+
745
+ def fmt(x):
746
+ if isinstance(x, float):
747
+ return round(x, 5)
748
+ if isinstance(x, dict):
749
+ return {k: fmt(v) for k, v in x.items()}
750
+ if isinstance(x, list):
751
+ return [fmt(v) for v in x]
752
+ return x
753
+
754
+ class ModelEmaV3Proxy(ModelEmaV3):
755
+ def __getattr__(self, name):
756
+ try:
757
+ return super().__getattr__(name)
758
+ except AttributeError:
759
+ return getattr(self.module, name)
760
+
761
+ def extract_entities(
762
+ input_ids, # (B, L)
763
+ logits, # (B, N, C)
764
+ pred_spans, # (B, N, 2)
765
+ id2label
766
+ ):
767
+ """
768
+ Return: [(batch_idx, ([token_ids], label_name)),...]
769
+ """
770
+
771
+ # (B, N)
772
+ pred_labels = logits.softmax(dim=-1).argmax(dim=-1)
773
+ start_idx = pred_spans[..., 0] # (B, N)
774
+ end_idx = pred_spans[..., 1] # (B, N)
775
+ keep = ((pred_labels > 0) & (start_idx > 0) & (end_idx > 0))
776
+
777
+ results = []
778
+ B, N = pred_labels.shape
779
+ for bidx in range(B):
780
+ valid_idxes = keep[bidx].nonzero(as_tuple=False).squeeze(-1)
781
+
782
+ for idx in valid_idxes:
783
+ lb = pred_labels[bidx, idx]
784
+
785
+ s, e = pred_spans[bidx, idx].tolist()
786
+ token_ids = input_ids[bidx, s:e+1].tolist()
787
+
788
+ results.append((bidx, (token_ids, id2label[lb.item()])))
789
+
790
+ return results
791
+
792
+ class Trainer:
793
+ def __init__(
794
+ 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,
795
+ logging=0, logging_file=False, checkpoints_dir="", early_stopping=False, eval_from_ratio=-1, eval_every=1, device='cpu',
796
+ schedule_in_step=True, use_ema=True, ema_from_ratio=-1, ema_decay=0.999, return_best=True, return_last=True
797
+ ):
798
+ self.ema_net = None
799
+
800
+ self.training_time = self._time_str_to_seconds(training_time)
801
+ self.mode = eval_mode
802
+ self.topk = topk
803
+ self.device = device
804
+ self.logging = logging if logging < epochs else 1
805
+ self.logging_file = logging_file
806
+ self.checkpoints_dir = checkpoints_dir
807
+ self.early_stopping = early_stopping
808
+ self.eval_from_ratio = eval_from_ratio
809
+ self.eval_every = eval_every
810
+ self.save_name = save_name
811
+ self.save_best = save_best
812
+ self.save_last = save_last
813
+ self.return_best = return_best
814
+ self.return_last = return_last
815
+ self.max_grad_norm = max_grad_norm
816
+ self.schedule_in_step = schedule_in_step
817
+ self.use_ema = use_ema
818
+ self.ema_from_ratio = ema_from_ratio
819
+ self.ema_decay = ema_decay
820
+
821
+ self.best_stage = [[float('-inf') if self.mode == 'max' else float('inf'), None, None]]
822
+ self.grad_scaler = torch.amp.GradScaler(self.device, init_scale=1024.0)
823
+
824
+ 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):
825
+ if eval_fn is None:
826
+ if self.mode == "max":
827
+ eval_fn = lambda *x: -loss_fn(*x)
828
+ else:
829
+ eval_fn = lambda *x: loss_fn(*x)
830
+
831
+ if torch.cuda.device_count() > 1:
832
+ network = DataParallelProxy(network)
833
+ network = network.to(self.device)
834
+
835
+ if not start_training_time:
836
+ start_training_time = time.time()
837
+
838
+ start_ema = int(epochs * self.ema_from_ratio)
839
+ start_eval = int(epochs * self.eval_from_ratio)
840
+
841
+ if val_loader is None:
842
+ print(f'[Trainer CallBack] 📢 Không có Val Set, không thể đánh giá và Early Stopping!')
843
+ else:
844
+ model_to_use_str = 'mô hình EMA' if self.use_ema else 'mô hình gốc'
845
+ start_model_update_str = f'Bắt đầu cập nhật EMA từ epoch {start_epoch + start_ema}!' if self.use_ema else ''
846
+ print(f'[Trainer CallBack] 📢 Đánh giá bằng {model_to_use_str} từ epoch {start_epoch + start_eval}!', start_model_update_str)
847
+
848
+ training_log = {}
849
+ for epoch in range(start_epoch, epochs+start_epoch):
850
+ if self.use_ema and self.ema_net is None and epoch - start_epoch >= start_ema:
851
+ self.ema_net = ModelEmaV3Proxy(network, self.ema_decay, device=self.device)
852
+
853
+ try:
854
+ teaching_rate = math.cos(math.pi / 2 * epoch / epochs)
855
+ train_loss_epoch, train_loss_epoch_dict = self._train_epoch(network, train_loader, optimizer, scheduler, loss_fn, teaching_rate)
856
+ logging_dict = {'lr': [group['lr'] for group in optimizer.param_groups], 'train_loss': train_loss_epoch}
857
+ logging_dict.update(train_loss_epoch_dict)
858
+
859
+ if val_loader is not None and epoch - start_epoch >= start_eval and (epoch - start_epoch - start_eval) % self.eval_every == 0:
860
+ eval_net = self.ema_net.module if (self.use_ema and self.ema_net is not None) else network
861
+
862
+ val_score, val_score_dict, _ = self._eval_epoch(eval_net, val_loader, eval_fn, id2label)
863
+ update = self._update_best_network(eval_net, val_score, epoch)
864
+ logging_dict.update({'val_score': val_score, 'best_score': self.best_stage[0][0], 'new_best_model': update})
865
+ logging_dict.update(val_score_dict)
866
+ if not self.schedule_in_step and scheduler:
867
+ scheduler.step()
868
+
869
+ except RuntimeError as e:
870
+ if "out of memory" in str(e).lower():
871
+ print(f"[Trainer CallBack] ⚠️ Epoch {epoch}/{epochs}: CUDA Out of Memory! Clearing GPU cache...")
872
+ torch.cuda.empty_cache()
873
+ gc.collect()
874
+ if torch.cuda.is_available():
875
+ torch.cuda.synchronize()
876
+ print(f"[Trainer CallBack] ✅ Epoch {epoch}/{epochs}: GPU memory cleared")
877
+
878
+ train_loader = reduce_batch_size(train_loader, ratio=0.5)
879
+ if val_loader is not None:
880
+ val_loader = reduce_batch_size(val_loader, ratio=0.5)
881
+
882
+ logging_dict = {'lr': [group['lr'] for group in optimizer.param_groups], 'train_loss': float('inf')}
883
+ else:
884
+ raise
885
+
886
+ training_log[epoch] = logging_dict
887
+ if self.is_early_stopping(epoch):
888
+ print(f'[Trainer CallBack] 📢 Epoch {epoch}/{epochs}: Detect Overfitting! Breaking Training Process...')
889
+ break
890
+ if self.logging:
891
+ if epoch % self.logging == 0:
892
+ print(f'[Trainer CallBack] 📢 Epoch {epoch}/{epochs}:', fmt(logging_dict))
893
+ else:
894
+ print(f'{epoch}...', end=' ')
895
+
896
+ if self._at_time_limit(start_training_time):
897
+ 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}')
898
+ break
899
+
900
+ if self.logging_file:
901
+ os.makedirs(f'{self.checkpoints_dir}/logs', exist_ok=True)
902
+ with open(f"{self.checkpoints_dir}/logs/{self.save_name}_logging.json", "a", encoding="utf-8") as f:
903
+ f.write(json.dumps(training_log))
904
+
905
+ if self.use_ema and self.ema_net is not None:
906
+ self._save_state_dict(self.ema_net.module)
907
+ else:
908
+ self._save_state_dict(network)
909
+ print(f'[Trainer CallBack] 📢 Kết thúc training.\n')
910
+
911
+ best_model, last_model = None, None
912
+ eval_net = self.ema_net.module if (self.use_ema and self.ema_net is not None) else network
913
+ if self.return_best :
914
+ best_model = self.best_stage[0][2] if self.best_stage[0][2] is not None else eval_net.state_dict()
915
+ best_model = {k.replace("module.", ""): v.detach().cpu().clone() for k, v in best_model.items()}
916
+ if self.return_last:
917
+ last_model = eval_net.state_dict()
918
+ last_model = {k.replace("module.", ""): v.detach().cpu().clone() for k, v in last_model.items()}
919
+
920
+ del network
921
+ torch.cuda.empty_cache()
922
+ gc.collect()
923
+ return training_log, best_model, last_model
924
+
925
+ def _time_str_to_seconds(self, time_str):
926
+ days, hours, minutes, seconds = map(int, time_str.split(":"))
927
+ return days * 86400 + hours * 3600 + minutes * 60 + seconds
928
+
929
+ def _update_best_network(self, network, val_score, epoch):
930
+ topk = max(1, self.topk)
931
+ self.best_stage.append([val_score, epoch, {k: v.detach().cpu().clone() for k, v in network.state_dict().items()}])
932
+ self.best_stage = sorted(self.best_stage, reverse=(self.mode == 'max'), key=lambda x: x[0])[:topk]
933
+ if val_score in [x[0] for x in self.best_stage]:
934
+ return True
935
+ return False
936
+
937
+ def is_early_stopping(self, epoch):
938
+ if self.best_stage[0][1] is None:
939
+ return False
940
+ if not self.early_stopping:
941
+ return False
942
+ return epoch - self.best_stage[0][1] >= self.early_stopping
943
+
944
+ def _at_time_limit(self, start_training_time):
945
+ return time.time() - start_training_time >= self.training_time
946
+
947
+ def _save_state_dict(self, network):
948
+ if self.topk <= 0:
949
+ return
950
+
951
+ if self.save_best:
952
+ for r in range(self.topk):
953
+ os.makedirs(f'{self.checkpoints_dir}/r{r+1}s', exist_ok=True)
954
+
955
+ for rank, (score, epoch, state_dict) in enumerate(self.best_stage):
956
+ if state_dict is None:
957
+ continue
958
+ state_dict = {k.replace("module.", ""): v.detach().cpu().clone() for k, v in state_dict.items()}
959
+ 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')
960
+ if self.save_last:
961
+ os.makedirs(f'{self.checkpoints_dir}/lasts', exist_ok=True)
962
+ state_dict = {k.replace("module.", ""): v.detach().cpu().clone() for k, v in network.state_dict().items()}
963
+ torch.save(state_dict, f'{self.checkpoints_dir}/lasts/{self.save_name}_last_{"ema" if self.ema_net is not None else ""}.pth')
964
+
965
+ def _train_epoch(self, network, train_loader, optimizer, scheduler, loss_fn, teaching_rate):
966
+ network.train()
967
+ total_loss = 0
968
+ total_loss_dict = {}
969
+ for batch_idx, batch in enumerate(train_loader):
970
+ optimizer.zero_grad()
971
+ with torch.autocast(device_type=self.device, dtype=torch.float16):
972
+ loss, loss_dict = self._cal_loss(network, batch, batch_idx, loss_fn, teaching_rate)
973
+
974
+ for k, v in loss_dict.items():
975
+ t = total_loss_dict.get(k, 0)
976
+ total_loss_dict[k] = t + v
977
+ self.grad_scaler.scale(loss).backward()
978
+ self.grad_scaler.unscale_(optimizer)
979
+ grad_norm = nn.utils.clip_grad_norm_(network.parameters(), self.max_grad_norm)
980
+ # print(grad_norm) # Bỏ cmt dòng này để biết nên chọn max_grad_norm bằng bao nhiêu...
981
+ self.grad_scaler.step(optimizer)
982
+ self.grad_scaler.update()
983
+ if self.schedule_in_step and scheduler:
984
+ scheduler.step()
985
+ if self.use_ema and self.ema_net is not None:
986
+ self.ema_net.update(network)
987
+ total_loss += loss
988
+ return (total_loss / len(train_loader)).item(), {k: v.item() / len(train_loader) for k, v in total_loss_dict.items()}
989
+
990
+ def _eval_epoch(self, network, val_loader, eval_fn, id2label):
991
+ network.eval()
992
+ total_score = 0.0
993
+ total_score_dict = {}
994
+ object_lists = None # sẽ init sau
995
+
996
+ with torch.no_grad():
997
+ for batch_idx, batch in enumerate(val_loader):
998
+ score, score_dict, objects = self._cal_val_score(network, batch, batch_idx, eval_fn, id2label)
999
+ total_score += score
1000
+
1001
+ for k, v in score_dict.items():
1002
+ t = total_score_dict.get(k, 0)
1003
+ total_score_dict[k] = t + v
1004
+
1005
+ if objects:
1006
+ if object_lists is None:
1007
+ object_lists = [[] for _ in range(len(objects))]
1008
+
1009
+ for i, obj in enumerate(objects):
1010
+ object_lists[i].append(obj.detach())
1011
+
1012
+ if object_lists is not None:
1013
+ object_arrays = [
1014
+ torch.concat(obj_list, dim=0).cpu().numpy()
1015
+ for obj_list in object_lists
1016
+ ]
1017
+ else:
1018
+ object_arrays = []
1019
+
1020
+ return total_score / len(val_loader), {k: v / len(val_loader) for k, v in total_score_dict.items()}, object_arrays
1021
+
1022
+ def _cal_loss(self, network, batch, batch_idx, loss_fn, teaching_rate):
1023
+ # Bạn cần override _cal_loss để tính loss
1024
+ input_ids = batch['input_ids'].to(self.device)
1025
+ attention_mask = batch['attention_mask'].to(self.device)
1026
+
1027
+ sampled_spans = batch['sampled_spans'].to(self.device) # B, M, 2
1028
+ sampled_labels = batch['sampled_labels'].to(self.device) # B, M
1029
+
1030
+ span_logits = network(input_ids, attention_mask, sampled_spans)
1031
+
1032
+ loss_dict = loss_fn(
1033
+ span_logits, sampled_labels,
1034
+ )
1035
+ return loss_dict['total'], loss_dict
1036
+
1037
+ def _cal_val_score(self, network, batch, batch_idx, eval_fn, id2label):
1038
+ # 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)
1039
+ input_ids = batch['input_ids'].to(self.device)
1040
+ attention_mask = batch['attention_mask'].to(self.device)
1041
+ all_spans = batch['all_spans'].to(self.device) # B, N, 2
1042
+ gold_entities = batch['gold_entities']
1043
+
1044
+ B, _, _ = input_ids.shape
1045
+
1046
+ span_logits = network(input_ids, attention_mask, all_spans)
1047
+
1048
+ pred_ids = extract_entities(input_ids.reshape(B, -1), span_logits, all_spans, id2label)
1049
+ pred_ids = list_to_tuple(pred_ids)
1050
+
1051
+ gold_ids = list_to_tuple(gold_entities)
1052
+
1053
+ score_dict = eval_fn(pred_ids, gold_ids)
1054
+ return score_dict['f1'], score_dict, []
1055
+
1056
+ # %% [code]
1057
+ class PhoBERTSpanAligner:
1058
+ def __init__(self, tokenizer, max_len):
1059
+ self.tokenizer = tokenizer
1060
+ self.max_len = max_len
1061
+
1062
+ # ===== 1. Extract discontinuous spans =====
1063
+ def extract_spans(self, sample):
1064
+ entity_spans = []
1065
+
1066
+ for event in sample["entities"]:
1067
+ entity_type = event["label"]
1068
+ spans = [tuple(event["offset"])]
1069
+ entity_spans.append({
1070
+ "spans": spans,
1071
+ "label": entity_type
1072
+ })
1073
+
1074
+ return entity_spans
1075
+
1076
+ # ===== 2. Word offsets =====
1077
+ def build_word_offsets(self, text, words):
1078
+ offsets = []
1079
+ pointer = 0
1080
+
1081
+ for word in words:
1082
+ start = text.find(word, pointer)
1083
+ end = start + len(word)
1084
+ offsets.append((start, end))
1085
+ pointer = end
1086
+
1087
+ return offsets
1088
+
1089
+ # ===== 3. Char → word =====
1090
+ def char_span_to_word_span(self, word_offsets, start, end):
1091
+ start_word = None
1092
+ end_word = None
1093
+
1094
+ for i, (w_start, w_end) in enumerate(word_offsets):
1095
+ if w_start <= start < w_end:
1096
+ start_word = i
1097
+ if w_start < end <= w_end:
1098
+ end_word = i
1099
+
1100
+ return start_word, end_word
1101
+
1102
+ # ===== 4. Word → subword =====
1103
+ def word_to_subword_map(self, words):
1104
+ mapping = []
1105
+ subword_index = 1 # <s>
1106
+
1107
+ for word in words:
1108
+ sub_tokens = self.tokenizer.tokenize(word)
1109
+ start = subword_index
1110
+ end = subword_index + len(sub_tokens) - 1
1111
+ mapping.append((start, end))
1112
+ subword_index += len(sub_tokens)
1113
+
1114
+ return mapping
1115
+
1116
+ # ===== 5. Span → subword =====
1117
+ def span_to_subword(self, word_offsets, word_subword_map, spans):
1118
+ sub_spans = []
1119
+
1120
+ for span_start, span_end in spans:
1121
+ w_start, w_end = self.char_span_to_word_span(
1122
+ word_offsets, span_start, span_end
1123
+ )
1124
+ if w_start is None or w_end is None:
1125
+ continue
1126
+
1127
+ sub_start = word_subword_map[w_start][0]
1128
+ sub_end = word_subword_map[w_end][1]
1129
+ sub_spans.append((sub_start, sub_end))
1130
+
1131
+ return sub_spans
1132
+
1133
+ def extract_valid_spans(self, sub_spans):
1134
+ valid_spans = []
1135
+ for s, e in sub_spans:
1136
+ if s < 0 or e < 0 or s >= self.max_len or e >= self.max_len or s > e:
1137
+ continue
1138
+ valid_spans.append((s, e))
1139
+ return valid_spans
1140
+
1141
+ def encode(self, sample):
1142
+ text = sample["text"]
1143
+ entities = self.extract_spans(sample)
1144
+
1145
+ # ===== 1. Word tokenize =====
1146
+ words = word_tokenize(text)
1147
+ sentence = " ".join(words)
1148
+
1149
+ # ===== 2. Mapping =====
1150
+ word_offsets = self.build_word_offsets(text, words)
1151
+ word_subword_map = self.word_to_subword_map(words)
1152
+
1153
+ # ===== 3. Tokenize FULL =====
1154
+ encoding = self.tokenizer(
1155
+ sentence,
1156
+ max_length=self.max_len,
1157
+ truncation=True,
1158
+ padding="max_length",
1159
+ return_tensors="pt"
1160
+ )
1161
+ input_ids = encoding["input_ids"][0]
1162
+ attention_mask = encoding["attention_mask"][0]
1163
+
1164
+ # ===== 5. Convert spans =====
1165
+ entities_gold_spans = []
1166
+
1167
+ for ent in entities:
1168
+ label = ent["label"]
1169
+
1170
+ sub_spans = self.span_to_subword(
1171
+ word_offsets,
1172
+ word_subword_map,
1173
+ ent["spans"]
1174
+ )
1175
+ valid_spans = self.extract_valid_spans(sub_spans)
1176
+ if len(valid_spans) == 0:
1177
+ continue
1178
+ entities_gold_spans.append((tuple(valid_spans), label))
1179
+
1180
+ return {
1181
+ "input_ids": input_ids,
1182
+ "attention_mask": attention_mask,
1183
+ "entities_gold_spans": entities_gold_spans,
1184
+ }
1185
+
1186
+ def generate_spans(attention_mask, max_span_len):
1187
+ seq_len = attention_mask.sum().item() - 2
1188
+ spans = []
1189
+ for i in range(1, seq_len+1):
1190
+ for j in range(i, min(i+max_span_len, seq_len+1)):
1191
+ spans.append((i, j))
1192
+ return spans
1193
+
1194
+ def match_gold_labels(
1195
+ gold_spans, # (N, 2)
1196
+ gold_labels, # (N,)
1197
+ pred_spans, # (M, 2)
1198
+ default_label=-100
1199
+ ):
1200
+ """
1201
+ Return:
1202
+ pred_labels: (M,)
1203
+ """
1204
+
1205
+ pred_labels = torch.full(
1206
+ (pred_spans.size(0),),
1207
+ default_label,
1208
+ dtype=gold_labels.dtype,
1209
+ device=gold_labels.device
1210
+ )
1211
+ if gold_spans.size(0) == 0:
1212
+ return pred_labels
1213
+
1214
+ # (M, N)
1215
+ matched = (pred_spans[:, None, :] == gold_spans[None, :, :]).all(dim=-1)
1216
+ has_match = matched.any(dim=1)
1217
+
1218
+ # lấy index gold đầu tiên match
1219
+ gold_idx = matched.float().argmax(dim=1)
1220
+
1221
+ pred_labels[has_match] = gold_labels[gold_idx[has_match]]
1222
+
1223
+ return pred_labels
1224
+
1225
+ class KLTNDataset(Dataset):
1226
+ def __init__(self, all_data, using_idxes, label2id, tokenizer, max_len, max_n_parts, max_span_len, n_negs, weight_sampling=False):
1227
+ super().__init__()
1228
+
1229
+ self.tokenizer = tokenizer
1230
+ self.aligner = PhoBERTSpanAligner(tokenizer, max_len * max_n_parts)
1231
+
1232
+ self.all_data = all_data
1233
+ self.using_idxes = using_idxes
1234
+ self.label2id = label2id
1235
+
1236
+ self.max_len = max_len
1237
+ self.max_n_parts = max_n_parts
1238
+ self.max_span_len = max_span_len
1239
+
1240
+ self.n_negs = n_negs
1241
+ self.weight_sampling = weight_sampling
1242
+
1243
+ def __len__(self):
1244
+ return len(self.using_idxes)
1245
+
1246
+ def compute_iou(self, spans1, spans2):
1247
+ s1 = spans1[:, None, 0]
1248
+ e1 = spans1[:, None, 1]
1249
+
1250
+ s2 = spans2[None, :, 0]
1251
+ e2 = spans2[None, :, 1]
1252
+
1253
+ inter = (torch.minimum(e1, e2) - torch.maximum(s1, s2) + 1).clamp(min=0)
1254
+
1255
+ len1 = e1 - s1 + 1
1256
+ len2 = e2 - s2 + 1
1257
+
1258
+ union = len1 + len2 - inter
1259
+
1260
+ return inter.float() / union.float()
1261
+
1262
+ def sample_spans(self, all_spans, all_labels, gold_spans):
1263
+ pos_mask = all_labels != 0
1264
+ neg_mask = all_labels == 0
1265
+
1266
+ pos_indices = torch.nonzero(pos_mask, as_tuple=False).squeeze(-1)
1267
+ neg_indices = torch.nonzero(neg_mask, as_tuple=False).squeeze(-1)
1268
+
1269
+ n_negs = min(self.n_negs, len(neg_indices))
1270
+
1271
+ if n_negs > 0:
1272
+ if self.weight_sampling and len(gold_spans) > 0:
1273
+ neg_spans = all_spans[neg_indices]
1274
+
1275
+ ious = self.compute_iou(neg_spans, gold_spans)
1276
+
1277
+ weights = ious.max(dim=1).values
1278
+
1279
+ hard_k = int(n_negs * 0.7)
1280
+ rand_k = n_negs - hard_k
1281
+
1282
+ sampled_hard = torch.empty(0, dtype=torch.long)
1283
+
1284
+ if hard_k > 0 and weights.sum() > 0:
1285
+ sampled_hard = neg_indices[
1286
+ torch.multinomial(weights, min(hard_k, len(weights)), replacement=False)
1287
+ ]
1288
+
1289
+ remain_mask = torch.ones(len(neg_indices), dtype=torch.bool)
1290
+
1291
+ if len(sampled_hard) > 0:
1292
+ selected = torch.isin(neg_indices, sampled_hard)
1293
+ remain_mask[selected] = False
1294
+
1295
+ remain_neg_indices = neg_indices[remain_mask]
1296
+
1297
+ sampled_rand = torch.empty(0, dtype=torch.long)
1298
+
1299
+ if rand_k > 0 and len(remain_neg_indices) > 0:
1300
+ perm = torch.randperm(len(remain_neg_indices))[:rand_k]
1301
+ sampled_rand = remain_neg_indices[perm]
1302
+
1303
+ neg_indices = torch.cat([sampled_hard, sampled_rand], dim=0)
1304
+
1305
+ else:
1306
+ perm = torch.randperm(len(neg_indices))[:n_negs]
1307
+ neg_indices = neg_indices[perm]
1308
+
1309
+ sampled_indices = torch.cat([pos_indices, neg_indices], dim=0)
1310
+
1311
+ if len(sampled_indices) > 0:
1312
+ sampled_indices = sampled_indices[torch.randperm(len(sampled_indices))]
1313
+
1314
+ sampled_spans = all_spans[sampled_indices]
1315
+ sampled_labels = all_labels[sampled_indices]
1316
+
1317
+ return sampled_spans, sampled_labels
1318
+
1319
+ def __getitem__(self, idx):
1320
+ ridx = self.using_idxes[idx]
1321
+
1322
+ sample = self.all_data[ridx]
1323
+
1324
+ result = self.aligner.encode(sample)
1325
+
1326
+ input_ids = result["input_ids"].squeeze(0)
1327
+ attention_mask = result["attention_mask"].squeeze(0)
1328
+
1329
+ entities_gold_spans = result["entities_gold_spans"]
1330
+
1331
+ all_spans = torch.tensor(generate_spans(attention_mask, self.max_span_len))
1332
+
1333
+ gold_spans = (
1334
+ torch.tensor([spans[0] for spans, _ in entities_gold_spans], dtype=torch.long)
1335
+ if entities_gold_spans else
1336
+ torch.empty(0, 2, dtype=torch.long)
1337
+ )
1338
+
1339
+ gold_labels = (
1340
+ torch.tensor([self.label2id[label] for _, label in entities_gold_spans], dtype=torch.long)
1341
+ if entities_gold_spans else
1342
+ torch.empty(0, dtype=torch.long)
1343
+ )
1344
+
1345
+ all_labels = match_gold_labels(
1346
+ gold_spans,
1347
+ gold_labels,
1348
+ all_spans,
1349
+ default_label=0
1350
+ )
1351
+
1352
+ sampled_spans, sampled_labels = self.sample_spans(
1353
+ all_spans,
1354
+ all_labels,
1355
+ gold_spans
1356
+ )
1357
+
1358
+ gold_entities = []
1359
+
1360
+ for spans, label in entities_gold_spans:
1361
+ s, e = spans[0]
1362
+
1363
+ gold_entities.append((tuple(input_ids[s:e+1].tolist()), label))
1364
+
1365
+ input_ids = input_ids.reshape(self.max_n_parts, self.max_len)
1366
+ attention_mask = attention_mask.reshape(self.max_n_parts, self.max_len)
1367
+
1368
+ n_valid_parts = math.ceil(attention_mask.sum().item() / self.max_len)
1369
+
1370
+ input_ids = input_ids[:n_valid_parts]
1371
+ attention_mask = attention_mask[:n_valid_parts]
1372
+
1373
+ return {
1374
+ "input_ids": input_ids,
1375
+ "attention_mask": attention_mask,
1376
+
1377
+ "sampled_spans": sampled_spans,
1378
+ "sampled_labels": sampled_labels,
1379
+
1380
+ "all_spans": all_spans,
1381
+
1382
+ "gold_entities": gold_entities,
1383
+ }
1384
+
1385
+ def _pad_batch(tensor_list, pad_value=0):
1386
+ """
1387
+ tensor_list: list of tensors
1388
+ mỗi tensor shape: (Nk, n_parts_i, max_len_i)
1389
+
1390
+ return:
1391
+ padded tensor shape: (B, max_Nk, max_n_parts, max_len)
1392
+ """
1393
+
1394
+ # lấy max toàn batch
1395
+ max_Nk = max(t.size(0) for t in tensor_list)
1396
+ max_n_parts = max(t.size(1) for t in tensor_list)
1397
+ max_len = max(t.size(2) for t in tensor_list)
1398
+
1399
+ padded = []
1400
+
1401
+ for t in tensor_list:
1402
+ Nk, n_parts_i, max_len_i = t.shape
1403
+
1404
+ # pad chiều n_parts và max_len trước
1405
+ if n_parts_i < max_n_parts or max_len_i < max_len:
1406
+ new_t = t.new_full(
1407
+ (Nk, max_n_parts, max_len),
1408
+ pad_value
1409
+ )
1410
+ new_t[:, :n_parts_i, :max_len_i] = t
1411
+ t = new_t
1412
+
1413
+ # pad chiều Nk
1414
+ if Nk < max_Nk:
1415
+ pad_tensor = t.new_full(
1416
+ (max_Nk - Nk, max_n_parts, max_len),
1417
+ pad_value
1418
+ )
1419
+ t = torch.cat([t, pad_tensor], dim=0)
1420
+
1421
+ padded.append(t)
1422
+
1423
+ return torch.stack(padded) # (B, max_Nk, max_n_parts, max_len)
1424
+
1425
+ def collate_fn(batch):
1426
+ gold_entities = []
1427
+ for bidx, b in enumerate(batch):
1428
+ for entity in b['gold_entities']:
1429
+ gold_entities.append([bidx, entity])
1430
+
1431
+ input_ids = [b["input_ids"].unsqueeze(-1) for b in batch]
1432
+ attention_mask = [b["attention_mask"].unsqueeze(-1) for b in batch]
1433
+ sampled_spans = [b["sampled_spans"].unsqueeze(-1) for b in batch]
1434
+ sampled_labels = [b["sampled_labels"].unsqueeze(-1).unsqueeze(-1) for b in batch]
1435
+ all_spans = [b["all_spans"].unsqueeze(-1) for b in batch]
1436
+
1437
+ # pad theo Nk
1438
+ input_ids = _pad_batch(input_ids, pad_value=0).squeeze(-1)
1439
+ attention_mask = _pad_batch(attention_mask, pad_value=0).squeeze(-1)
1440
+ sampled_spans = _pad_batch(sampled_spans, pad_value=0).squeeze(-1)
1441
+ sampled_labels = _pad_batch(sampled_labels, pad_value=-100).squeeze(-1).squeeze(-1)
1442
+ all_spans = _pad_batch(all_spans, pad_value=0).squeeze(-1)
1443
+
1444
+ return {
1445
+ "input_ids": input_ids,
1446
+ "attention_mask": attention_mask,
1447
+
1448
+ "sampled_spans": sampled_spans,
1449
+ "sampled_labels": sampled_labels,
1450
+
1451
+ "all_spans": all_spans,
1452
+ "gold_entities": gold_entities,
1453
+ }
1454
+
1455
+ # %% [code]
1456
+ def shift_bidx(spans, batch_idx):
1457
+ shifted = []
1458
+ for bidx, ent in spans:
1459
+ new_bidx = bidx + batch_idx * batch_size
1460
+ shifted.append((new_bidx, ent))
1461
+ return shifted
1462
+
1463
+ def refactor_entities(entities, save_dict):
1464
+ i, c = [], []
1465
+ for bidx, (ids, lb) in entities:
1466
+ if (bidx, ids) not in i:
1467
+ i.append((bidx, ids))
1468
+
1469
+ if (bidx, (ids, lb)) not in c:
1470
+ c.append((bidx, (ids, lb)))
1471
+
1472
+ save_dict['Ent-I'].extend(i)
1473
+ save_dict['Ent-C'].extend(c)
1474
+
1475
+ def test(network, state_dicts, test_loader, eval_fn, analyzer, device, id2label, tokenizer):
1476
+ if torch.cuda.device_count() > 1:
1477
+ network = DataParallelProxy(network)
1478
+ network = network.to(device)
1479
+ network.eval()
1480
+
1481
+ eval_types = ['Ent-I', 'Ent-C']
1482
+
1483
+ all_pred = {eval_type: [] for eval_type in eval_types}
1484
+ all_gold = {eval_type: [] for eval_type in eval_types}
1485
+
1486
+ list_input_ids = []
1487
+
1488
+ with torch.no_grad():
1489
+ for batch_idx, batch in enumerate(test_loader):
1490
+ input_ids = batch['input_ids'].to(device)
1491
+ attention_mask = batch['attention_mask'].to(device)
1492
+ all_spans = batch['all_spans'].to(device)
1493
+ gold_entities = batch['gold_entities']
1494
+
1495
+ B, _, _ = input_ids.shape
1496
+ list_input_ids.extend(input_ids.reshape(B, -1).tolist())
1497
+
1498
+ list_hidden_states = []
1499
+ list_logits = []
1500
+ list_start_logits = []
1501
+ list_end_logits = []
1502
+ for sd in state_dicts:
1503
+ if torch.cuda.device_count() > 1:
1504
+ network.module.load_state_dict(sd)
1505
+ else:
1506
+ network.load_state_dict(sd)
1507
+
1508
+ span_logits = network(input_ids, attention_mask, all_spans)
1509
+ list_logits.append(span_logits)
1510
+
1511
+ ensemble_logits = torch.stack(list_logits, dim=0).mean(dim=0)
1512
+ pred_entities = extract_entities(input_ids.reshape(B, -1), ensemble_logits, all_spans, id2label)
1513
+ pred_entities = shift_bidx(pred_entities, batch_idx)
1514
+ refactor_entities(pred_entities, all_pred)
1515
+
1516
+ gold_entities = shift_bidx(gold_entities, batch_idx)
1517
+ refactor_entities(gold_entities, all_gold)
1518
+
1519
+ # ===== GLOBAL EVAL =====
1520
+ final_score = {}
1521
+ for eval_type in eval_types:
1522
+ score = eval_fn(list_to_tuple(all_pred[eval_type]), list_to_tuple(all_gold[eval_type]))
1523
+ final_score[eval_type] = score
1524
+
1525
+ analyze_result = analyzer.analyze(list_to_tuple(all_pred['Ent-I']), list_to_tuple(all_gold['Ent-I']))
1526
+
1527
+ # ===== PREDICT =====
1528
+ predictions = []
1529
+ for input_ids in list_input_ids:
1530
+ predictions.append([tokenizer.decode(input_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)])
1531
+ for bidx, (ids, lb) in all_pred['Ent-C']:
1532
+ predictions[bidx].append((tokenizer.decode(ids, skip_special_tokens=True, clean_up_tokenization_spaces=True), lb))
1533
+
1534
+ return final_score, analyze_result, predictions
1535
+
1536
+ # %% [code]
1537
+ with open(f'{train_dir}/train.json', "r", encoding="utf-8") as f:
1538
+ data_train = json.load(f)
1539
+
1540
+ with open(f'{test_dir}/test.json', "r", encoding="utf-8") as f:
1541
+ data_test = json.load(f)
1542
+
1543
+ print('Train:', len(data_train))
1544
+ print('Test:', len(data_test))
1545
+
1546
+ # %% [code]
1547
+ entity_types = ['O'] + sorted(list(set([e['label'] for d in data_train + data_test for e in d['entities']])))
1548
+ # bio_entity_type = ['O'] + [f'{prefix}-{ent}' for ent in entity_types for prefix in ['B', 'I']]
1549
+ label2id = {l: i for i, l in enumerate(entity_types)}
1550
+ id2label = {i: l for l, i in label2id.items()}
1551
+
1552
+ # %% [code]
1553
+ zero_entities_idxes = []
1554
+ for idx, d in enumerate(data_train):
1555
+ if len(d['entities']) == 0:
1556
+ zero_entities_idxes.append(idx)
1557
+
1558
+ n_zero_entities_samples = len(zero_entities_idxes)
1559
+ n_has_entities_samples = len(data_train) - n_zero_entities_samples
1560
+
1561
+ random.seed(42)
1562
+ k = min(int(n_has_entities_samples * zero_entities_rate), len(zero_entities_idxes))
1563
+ sampled_zero_entities_idxes = random.sample(zero_entities_idxes, k)
1564
+
1565
+ new_data_train = []
1566
+ for idx, d in enumerate(data_train):
1567
+ if len(d['entities']) == 0:
1568
+ if idx in sampled_zero_entities_idxes:
1569
+ new_data_train.append(d)
1570
+ else:
1571
+ new_data_train.append(d)
1572
+ data_train = new_data_train
1573
+
1574
+ print('Train:', len(data_train))
1575
+
1576
+ # %% [code]
1577
+ if debug_only:
1578
+ data_train = data_train[:20]
1579
+ data_test = data_test[:20]
1580
+
1581
+ print('Train:', len(data_train))
1582
+ print('Test:', len(data_test))
1583
+
1584
+ # %% [code]
1585
+ tokenizer = AutoTokenizer.from_pretrained(backbone_model_name)
1586
+
1587
+ # %% [code]
1588
+ print('Experiment name:', state_dict_save_name)
1589
+
1590
+ # %% [code]
1591
+ # trainset = KLTNDataset(data_train, np.array(range(len(data_train))), label2id, tokenizer, **train_memory_params)
1592
+ # train_loader = DataLoader(trainset, collate_fn=collate_fn, **train_loader_params)
1593
+ # for b in train_loader:
1594
+ # break
1595
+
1596
+ # %% [code]
1597
+ if not test_only:
1598
+ full_idxes = np.array(range(len(data_train)))
1599
+ training_logs, best_models, last_models = [], [], []
1600
+ start_training_time = time.time()
1601
+ for seed in SEEDS:
1602
+ kf = KFold(n_splits=nfolds, shuffle=True, random_state=seed)
1603
+ for fold_idx, (tr_idx, va_idx) in enumerate(kf.split(full_idxes)):
1604
+ if only_fold_idx is not None and only_fold_idx >= 0 and only_fold_idx != fold_idx:
1605
+ continue
1606
+ set_seed(seed)
1607
+
1608
+ train_idxes, val_idxes = full_idxes[tr_idx], full_idxes[va_idx]
1609
+
1610
+ trainset = KLTNDataset(data_train, train_idxes, label2id, tokenizer, **train_memory_params)
1611
+ valset = KLTNDataset(data_train, val_idxes, label2id, tokenizer, **val_memory_params)
1612
+
1613
+ generator = torch.Generator()
1614
+ generator.manual_seed(seed)
1615
+ train_loader = DataLoader(trainset, generator=generator, collate_fn=collate_fn, **train_loader_params)
1616
+ val_loader = DataLoader(valset, generator=generator, collate_fn=collate_fn, **val_loader_params)
1617
+
1618
+ my_model = IEModel(
1619
+ num_labels=len(label2id),
1620
+ **model_params
1621
+ )
1622
+ total_params = sum(p.numel() for p in my_model.parameters())
1623
+ print(f"Total params: {total_params:,}")
1624
+
1625
+ # optimizer, scheduler = configure_optimizers(my_model, optim_params, scheduler_params)
1626
+ encoder_params = set(map(id, my_model.encoder.parameters()))
1627
+ other_params = [
1628
+ p for p in my_model.parameters()
1629
+ if id(p) not in encoder_params
1630
+ ]
1631
+ optimizer = optim.AdamW([
1632
+ {"params": my_model.encoder.parameters(), "lr": 2e-5},
1633
+ {"params": other_params}
1634
+ ], lr=5e-4)
1635
+ scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=20, eta_min=1e-6)
1636
+
1637
+ loss_fn = CustomLoss(
1638
+ **loss_func_params
1639
+ )
1640
+ eval_fn = CustomEvalFn(**eval_func_params)
1641
+ trainer_params['save_name'] = f'{state_dict_save_name}_s{seed}_f{fold_idx}'
1642
+ trainer = Trainer(**trainer_params)
1643
+
1644
+ print(f'Start Training Fold {fold_idx}...')
1645
+ training_log, best_model, last_model = trainer.fit(
1646
+ my_model, optimizer, scheduler, loss_fn, epochs, train_loader, val_loader, eval_fn,
1647
+ start_epoch=1, start_training_time=start_training_time, id2label=id2label
1648
+ )
1649
+
1650
+ training_logs.append(training_log)
1651
+ best_models.append(best_model)
1652
+ last_models.append(last_model)
1653
+
1654
+ # %% [code]
1655
+ def load_all_state_dicts(folder):
1656
+ files = []
1657
+
1658
+ for file in os.listdir(folder):
1659
+ if file.endswith(".pt") or file.endswith(".pth"):
1660
+ m = re.search(r"f(\d+)", file) # tìm f<số>
1661
+ if m:
1662
+ fold = int(m.group(1))
1663
+ files.append((fold, file))
1664
+
1665
+ # sort theo fold
1666
+ files.sort(key=lambda x: x[0])
1667
+
1668
+ state_dicts = []
1669
+ for fold, file in files:
1670
+ path = os.path.join(folder, file)
1671
+ print(f"Loading fold {fold}: {file}")
1672
+ state_dict = torch.load(path, map_location="cpu")
1673
+ state_dicts.append(state_dict)
1674
+
1675
+ return state_dicts
1676
+
1677
+ if test_only:
1678
+ snapshot_download(repo_id=repo_name, local_dir="", repo_type="model", allow_patterns=[f"{state_dict_save_name}/**"])
1679
+ get_ipython().system('rm -rf .cache .gitattributes')
1680
+
1681
+ best_models = load_all_state_dicts(f"{state_dict_save_name}/r1s")
1682
+ last_models = load_all_state_dicts(f"{state_dict_save_name}/lasts")
1683
+
1684
+ # %% [code]
1685
+ os.makedirs(f'{checkpoints_dir}/results', exist_ok=True)
1686
+ testset = KLTNDataset(data_test, range(len(data_test)), label2id, tokenizer, **val_memory_params)
1687
+ generator = torch.Generator()
1688
+ test_loader = DataLoader(testset, generator=generator, collate_fn=collate_fn, **val_loader_params)
1689
+ eval_fn = CustomEvalFn(**eval_func_params)
1690
+ analyzer = SpanErrorAnalyzer()
1691
+ my_model = IEModel(
1692
+ num_labels=len(label2id),
1693
+ **model_params
1694
+ )
1695
+ total_params = sum(p.numel() for p in my_model.parameters())
1696
+ print(f"Total params: {total_params:,}")
1697
+
1698
+ # %% [code]
1699
+ start_time = time.time()
1700
+
1701
+ best_score, best_analyze_result, best_pred_test = test(my_model, best_models, test_loader, eval_fn, analyzer, device, id2label, tokenizer)
1702
+ last_score, last_analyze_result, last_pred_test = test(my_model, last_models, test_loader, eval_fn, analyzer, device, id2label, tokenizer)
1703
+
1704
+ result_test = {"Best model": best_score, "Last model": last_score}
1705
+ analyze_result = {"Best model": best_analyze_result, "Last model": last_analyze_result}
1706
+ analyze_result_sumary = {"Best model": best_analyze_result['summary'], "Last model": last_analyze_result['summary']}
1707
+ pred_test = {"Best model": best_pred_test, "Last model": last_pred_test}
1708
+
1709
+ with open(f"{checkpoints_dir}/results/{state_dict_save_name}_test.json", "w", encoding="utf-8") as f:
1710
+ json.dump(result_test, f, ensure_ascii=False, indent=2)
1711
+
1712
+ with open(f"{checkpoints_dir}/results/{state_dict_save_name}_error_analyze_result.json", "w", encoding="utf-8") as f:
1713
+ json.dump(analyze_result, f, ensure_ascii=False, indent=2)
1714
+
1715
+ with open(f"{checkpoints_dir}/results/{state_dict_save_name}_pred_test.json", "w", encoding="utf-8") as f:
1716
+ json.dump(pred_test, f, ensure_ascii=False, indent=2)
1717
+
1718
+ print('Test:', time.time() - start_time, 's --> Done!')
1719
+ print(json.dumps(analyze_result_sumary, ensure_ascii=False, indent=4))
1720
+
1721
+ # %% [code]
1722
+ best_pred_test[:10]
1723
+
1724
+ # %% [code]
1725
+ last_pred_test[:10]
1726
+
1727
+ # %% [code]
1728
+ def dict_to_df(data):
1729
+ row_tuples = []
1730
+ row_values = []
1731
+
1732
+ metrics = ["precision", "recall", "f1"]
1733
+
1734
+ # Lấy model đầu tiên
1735
+ first_model = next(iter(data.values()))
1736
+
1737
+ # eval_keys
1738
+ eval_keys = list(first_model.keys())
1739
+
1740
+ for eval_key in eval_keys:
1741
+ row_tuples.append(eval_key)
1742
+ row = {}
1743
+
1744
+ for model_name, model_data in data.items():
1745
+ for metric in metrics:
1746
+ row[(model_name, metric)] = model_data[eval_key][metric]
1747
+
1748
+ row_values.append(row)
1749
+
1750
+ # ===== DataFrame =====
1751
+ df = pd.DataFrame(row_values)
1752
+
1753
+ # MultiIndex columns
1754
+ df.columns = pd.MultiIndex.from_tuples(df.columns)
1755
+
1756
+ # Index
1757
+ df.index = pd.Index(row_tuples, name="evaluation")
1758
+
1759
+ # ===== Sort =====
1760
+ sort_keys = []
1761
+ if ("Best model", "f1") in df.columns:
1762
+ sort_keys.append(("Best model", "f1"))
1763
+ if ("Last model", "f1") in df.columns:
1764
+ sort_keys.append(("Last model", "f1"))
1765
+
1766
+ if sort_keys:
1767
+ df = df.sort_values(by=sort_keys, ascending=False)
1768
+
1769
+ return df
1770
+
1771
+ result_test_df = dict_to_df(result_test)
1772
+ result_test_df.to_excel(f"{checkpoints_dir}/results/{state_dict_save_name}_test_df.xlsx")
1773
+ result_test_df
1774
+
1775
+ # %% [code]
1776
+ key = ("Best model", "f1")
1777
+ result_test_df_best = result_test_df.sort_values(by=key, ascending=False).groupby(level="evaluation").head(1)
1778
+ result_test_df_best.to_excel(f"{checkpoints_dir}/results/{state_dict_save_name}_test_df_best.xlsx")
1779
+ result_test_df_best
1780
+
1781
+ # %% [code]
1782
+ def get_avg_best_score(logs):
1783
+ return float(np.mean([list(log.values())[-1]['best_score'] for log in logs]))
1784
+
1785
+ def get_avg_log(logs, epochs):
1786
+ avg_log = {}
1787
+
1788
+ for epoch in range(1, epochs + 1):
1789
+ val_score = 0.0
1790
+ train_loss = 0.0
1791
+ n_eval = 0
1792
+
1793
+ for idx in range(len(logs)):
1794
+ log = logs[idx].get(epoch, logs[idx].get(str(epoch)))
1795
+ if log is None:
1796
+ continue
1797
+
1798
+ val_score += log.get('val_score', 0.0)
1799
+ train_loss += log.get('train_loss', 0.0)
1800
+ n_eval += 1
1801
+
1802
+ if n_eval == 0:
1803
+ continue
1804
+
1805
+ avg_log[epoch] = {
1806
+ 'train_loss': train_loss / n_eval,
1807
+ 'val_score': val_score / n_eval if val_score != 0 else float('inf')
1808
+ }
1809
+
1810
+ return avg_log
1811
+
1812
+ def parse_label_key(label: str):
1813
+ try:
1814
+ first = float(label.split('_', 1)[0]) # số đầu: trước dấu _
1815
+ last = float(re.findall(r'_(\d+(?:\.\d+)?)$', label)[0])
1816
+ return first, last
1817
+ except:
1818
+ return (0, 0)
1819
+
1820
+ def plot_training_logs(logs_dict, save_path=None, figsize=(24, 10)):
1821
+ fig, axes = plt.subplots(1, 2, figsize=figsize)
1822
+
1823
+ # ===== Plot Train Loss =====
1824
+ for name, log in logs_dict.items():
1825
+ epochs = sorted(log.keys())
1826
+ train_loss = [log[e]['train_loss'] for e in epochs]
1827
+ axes[0].plot(epochs, train_loss, label=name)
1828
+
1829
+ axes[0].set_xlabel('Epoch')
1830
+ axes[0].set_ylabel('Train Loss')
1831
+ axes[0].set_title('Training Loss')
1832
+ axes[0].grid(True)
1833
+
1834
+ # ===== Plot Validation Score =====
1835
+ for name, log in logs_dict.items():
1836
+ epochs = sorted(log.keys())
1837
+ val_score = [log[e]['val_score'] for e in epochs]
1838
+ axes[1].plot(epochs, val_score, label=name)
1839
+
1840
+ axes[1].set_xlabel('Epoch')
1841
+ axes[1].set_ylabel('Validation Score')
1842
+ axes[1].set_title('Validation Score')
1843
+ axes[1].grid(True)
1844
+
1845
+ # ===== Shared Legend =====
1846
+ handles, labels = axes[0].get_legend_handles_labels()
1847
+ pairs = list(zip(handles, labels))
1848
+ pairs_sorted = sorted(
1849
+ pairs,
1850
+ key=lambda x: parse_label_key(x[1])
1851
+ )
1852
+ handles_sorted, labels_sorted = zip(*pairs_sorted)
1853
+
1854
+ axes[0].legend(
1855
+ handles_sorted,
1856
+ labels_sorted,
1857
+ loc='center left',
1858
+ bbox_to_anchor=(1.01, 0.5),
1859
+ borderaxespad=0.
1860
+ )
1861
+
1862
+ plt.tight_layout(rect=[0, 0, 1, 1])
1863
+
1864
+ if save_path is not None:
1865
+ os.makedirs(os.path.dirname(save_path), exist_ok=True) if os.path.dirname(save_path) else None
1866
+ plt.savefig(save_path, dpi=300, bbox_inches='tight')
1867
+
1868
+ plt.show()
1869
+
1870
+ # %% [code]
1871
+ # if not test_only:
1872
+ # snapshot_download(repo_id=repo_name, local_dir="", repo_type="model", allow_patterns=["**/*.json"])
1873
+ # !rm -rf .cache .gitattributes
1874
+
1875
+ # %% [code]
1876
+ if not test_only:
1877
+ experiments = {}
1878
+ for experiment in os.listdir(pretrained_dir):
1879
+ if '.virtual_documents' in experiment:
1880
+ continue
1881
+ experiment_logs = []
1882
+ try:
1883
+ for seed in SEEDS:
1884
+ for fold_idx in range(nfolds):
1885
+ with open(f"{pretrained_dir}/{experiment}/logs/{experiment}_s{seed}_f{fold_idx}_logging.json", "r", encoding="utf-8") as f:
1886
+ experiment_log = json.load(f)
1887
+ experiment_logs.append(experiment_log)
1888
+ except:
1889
+ pass
1890
+ experiments[experiment] = get_avg_log(experiment_logs, 1000)
1891
+ experiments[state_dict_save_name] = get_avg_log(training_logs, 1000)
1892
+
1893
+ # %% [code]
1894
+ if not test_only:
1895
+ score = get_avg_best_score(training_logs)
1896
+ state_dict_save_name, score
1897
+
1898
+ # %% [code]
1899
+ if not test_only:
1900
+ plot_training_logs(experiments, save_path=f'{checkpoints_dir}/logs/{state_dict_save_name}_log_plot.jpg', figsize=(18, 7.5))
1901
+
0_entities_phoner_1/lasts/0_entities_phoner_1_s26092004_f0_last_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ce1afdfb29fc78dbb5f77163d4bea5ba7ecf365d4b699181ee815628d2898297
3
+ size 573212395
0_entities_phoner_1/logs/0_entities_phoner_1_log_plot.jpg ADDED

Git LFS Details

  • SHA256: 949bc63d9b81322b6c3b3b3ca4aa60076c23c0a8c789c8dfe96904157bfad01d
  • Pointer size: 131 Bytes
  • Size of remote file: 437 kB
0_entities_phoner_1/logs/0_entities_phoner_1_s26092004_f0_logging.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"1": {"lr": [2e-05, 0.0005], "train_loss": 0.10182062536478043, "total": 0.10182062062350186, "span_loss": 0.10182062062350186}, "2": {"lr": [1.988303923565381e-05, 0.0004969282409784868], "train_loss": 0.017111176624894142, "total": 0.01711117679422552, "span_loss": 0.01711117679422552}, "3": {"lr": [1.9535036904803962e-05, 0.0004877886008156408], "train_loss": 0.014072098769247532, "total": 0.014072098515250465, "span_loss": 0.014072098515250465}, "4": {"lr": [1.8964561979789496e-05, 0.00047280612778499774], "train_loss": 0.010926872491836548, "total": 0.01092687181451104, "span_loss": 0.01092687181451104}, "5": {"lr": [1.8185661446562005e-05, 0.00045234974009654937], "train_loss": 0.009199966676533222, "total": 0.009199966083873402, "span_loss": 0.009199966083873402}, "6": {"lr": [1.7217514421272206e-05, 0.00042692314190604356], "train_loss": 0.009163443930447102, "total": 0.009163443337787281, "span_loss": 0.009163443337787281}, "7": {"lr": [1.60839598967785e-05, 0.00039715242044697206], "train_loss": 0.0073513975366950035, "total": 0.007351397113366561, "span_loss": 0.007351397113366561}, "8": {"lr": [1.4812909747525698e-05, 0.00036377062968501693], "train_loss": 0.006471510045230389, "total": 0.0064715099605647, "span_loss": 0.0064715099605647, "val_score": 0.9135424685985943, "best_score": 0.9135424685985943, "new_best_model": true, "precision": 0.8736971122373686, "recall": 0.9580202185167708, "f1": 0.9135424685985943}, "9": {"lr": [1.3435661446562005e-05, 0.0003275997400965494], "train_loss": 0.005831211339682341, "total": 0.005831211128018119, "span_loss": 0.005831211128018119, "val_score": 0.9132964301732863, "best_score": 0.9135424685985943, "new_best_model": false, "precision": 0.8723739812970763, "recall": 0.9589872506731172, "f1": 0.9132964301732863}, "10": {"lr": [1.1986127417882198e-05, 0.00028953039902753766], "train_loss": 0.00477367639541626, "total": 0.004773676056753506, "span_loss": 0.004773676056753506, "val_score": 0.9137298524143769, "best_score": 0.9137298524143769, "new_best_model": true, "precision": 0.8725783897957857, "recall": 0.9597278770159615, "f1": 0.9137298524143769}, "11": {"lr": [1.0500000000000003e-05, 0.0002505], "train_loss": 0.00423548324033618, "total": 0.004235483028671958, "span_loss": 0.004235483028671958, "val_score": 0.9146864024012803, "best_score": 0.9146864024012803, "new_best_model": true, "precision": 0.8741519752784811, "recall": 0.9599825632021097, "f1": 0.9146864024012803}, "12": {"lr": [9.013872582117811e-06, 0.00021146960097246246], "train_loss": 0.003919586539268494, "total": 0.003919586539268494, "span_loss": 0.003919586539268494, "val_score": 0.9159539540796388, "best_score": 0.9159539540796388, "new_best_model": true, "precision": 0.8756837080168451, "recall": 0.960894314959996, "f1": 0.9159539540796388}, "13": {"lr": [7.564338553438001e-06, 0.00017340025990345064], "train_loss": 0.0031489101238548756, "total": 0.0031489099968563428, "span_loss": 0.0031489099968563428, "val_score": 0.9162749505229946, "best_score": 0.9162749505229946, "new_best_model": true, "precision": 0.8762345403945873, "recall": 0.9608787325102797, "f1": 0.9162749505229946}, "14": {"lr": [6.1870902524743065e-06, 0.00013722937031498307], "train_loss": 0.0029559824615716934, "total": 0.0029559822922403164, "span_loss": 0.0029559822922403164, "val_score": 0.9182433573764149, "best_score": 0.9182433573764149, "new_best_model": true, "precision": 0.8790550012609976, "recall": 0.961866483512528, "f1": 0.9182433573764149}, "15": {"lr": [4.916040103221507e-06, 0.00010384757955302797], "train_loss": 0.0027618855237960815, "total": 0.0027618853544647045, "span_loss": 0.0027618853544647045, "val_score": 0.9190868974204812, "best_score": 0.9190868974204812, "new_best_model": true, "precision": 0.8806436035647913, "recall": 0.9618276862582977, "f1": 0.9190868974204812}, "16": {"lr": [3.7824855787278e-06, 7.40768580939564e-05], "train_loss": 0.002336186356842518, "total": 0.0023361862721768293, "span_loss": 0.0023361862721768293, "val_score": 0.9201149178562193, "best_score": 0.9201149178562193, "new_best_model": true, "precision": 0.8822941944392911, "recall": 0.9621016563884331, "f1": 0.9201149178562193}, "17": {"lr": [2.814338553438001e-06, 4.865025990345063e-05], "train_loss": 0.002105257473886013, "total": 0.0021052573892203245, "span_loss": 0.0021052573892203245, "val_score": 0.9204695749241476, "best_score": 0.9204695749241476, "new_best_model": true, "precision": 0.8831027698429179, "recall": 0.96188100325518, "f1": 0.9204695749241476}, "18": {"lr": [2.0354380202105066e-06, 2.8193872215002235e-05], "train_loss": 0.0020009821746498346, "total": 0.002000982111150568, "span_loss": 0.002000982111150568, "val_score": 0.9213177789842686, "best_score": 0.9213177789842686, "new_best_model": true, "precision": 0.8846552146602089, "recall": 0.9619017543821223, "f1": 0.9213177789842686}}
0_entities_phoner_1/r1s/0_entities_phoner_1_s26092004_f0_r1_vs0.92132_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:85b2e7619f47479d85619925bee6e427a0ea68661538aa2569e9bd21cfc5169e
3
+ size 573214323
0_entities_phoner_1/results/0_entities_phoner_1_error_analyze_result.json ADDED
The diff for this file is too large to render. See raw diff
 
0_entities_phoner_1/results/0_entities_phoner_1_pred_test.json ADDED
The diff for this file is too large to render. See raw diff
 
0_entities_phoner_1/results/0_entities_phoner_1_test.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "Best model": {
3
+ "Ent-I": {
4
+ "precision": 0.893083333332589,
5
+ "recall": 0.9634990560092029,
6
+ "f1": 0.9269558398362139
7
+ },
8
+ "Ent-C": {
9
+ "precision": 0.8875843117654362,
10
+ "recall": 0.9564788226839944,
11
+ "f1": 0.9207446069355232
12
+ }
13
+ },
14
+ "Last model": {
15
+ "Ent-I": {
16
+ "precision": 0.893083333332589,
17
+ "recall": 0.9634990560092029,
18
+ "f1": 0.9269558398362139
19
+ },
20
+ "Ent-C": {
21
+ "precision": 0.8875843117654362,
22
+ "recall": 0.9564788226839944,
23
+ "f1": 0.9207446069355232
24
+ }
25
+ }
26
+ }
0_entities_phoner_1/results/0_entities_phoner_1_test_df.xlsx ADDED
Binary file (5.22 kB). View file
 
0_entities_phoner_1/results/0_entities_phoner_1_test_df_best.xlsx ADDED
Binary file (5.22 kB). View file