SS3M commited on
Commit
d4f59f9
·
verified ·
1 Parent(s): 5aba231

Upload 8_entities_add_weight_keep_2_learn_all_10's state dict

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

Git LFS Details

  • SHA256: 7699c0e990122b13e157a5291ed493751b4bb001fbc0e44571e2e751d85618f9
  • Pointer size: 131 Bytes
  • Size of remote file: 561 kB
8_entities_add_weight_keep_2_learn_all_10/logs/8_entities_add_weight_keep_2_learn_all_10_s26092004_f0_logging.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"1": {"lr": [2e-05, 0.0005], "train_loss": 0.17205655574798584, "total": 0.17205655314923665, "span_loss": 0.03050398040310906, "start_loss": 0.06639170340148345, "end_loss": 0.07516084588926687}, "2": {"lr": [1.988303923565381e-05, 0.0004969282409784868], "train_loss": 0.12228421866893768, "total": 0.12228421701140214, "span_loss": 0.019649047169224252, "start_loss": 0.04880167586367646, "end_loss": 0.05383361338769477}, "3": {"lr": [1.9535036904803962e-05, 0.0004877886008156408], "train_loss": 0.11262249946594238, "total": 0.11262250359728725, "span_loss": 0.01783744232024208, "start_loss": 0.04549894124985807, "end_loss": 0.049286293810209526}, "4": {"lr": [1.8964561979789496e-05, 0.00047280612778499774], "train_loss": 0.10351164638996124, "total": 0.10351165037970758, "span_loss": 0.016240199362518668, "start_loss": 0.04209571100600676, "end_loss": 0.04517573041580055}, "5": {"lr": [1.8185661446562005e-05, 0.00045234974009654937], "train_loss": 0.0943237692117691, "total": 0.09432376970319924, "span_loss": 0.014663470264517975, "start_loss": 0.03863545434311024, "end_loss": 0.04102486641864126}, "6": {"lr": [1.7217514421272206e-05, 0.00042692314190604356], "train_loss": 0.08495538681745529, "total": 0.08495538497250996, "span_loss": 0.013166395627699331, "start_loss": 0.035007662317351695, "end_loss": 0.0367813067705422}, "7": {"lr": [1.60839598967785e-05, 0.00039715242044697206], "train_loss": 0.07525168359279633, "total": 0.07525168216848187, "span_loss": 0.011613162420794177, "start_loss": 0.03115768816432452, "end_loss": 0.03248078680491567}, "8": {"lr": [1.4812909747525698e-05, 0.00036377062968501693], "train_loss": 0.0662292018532753, "total": 0.06622920028319766, "span_loss": 0.010216151621836134, "start_loss": 0.027563307257322308, "end_loss": 0.02844969022867065, "val_score": 0.7113776848424967, "best_score": 0.7113776848424967, "new_best_model": true, "precision": 0.7469562606566188, "recall": 0.681850288610791, "f1": 0.7113776848424967}, "9": {"lr": [1.3435661446562005e-05, 0.0003275997400965494], "train_loss": 0.05802363157272339, "total": 0.05802363080642555, "span_loss": 0.008983593935937173, "start_loss": 0.02421071504067282, "end_loss": 0.02482932076366205, "val_score": 0.7085036544209539, "best_score": 0.7113776848424967, "new_best_model": false, "precision": 0.7421738541398917, "recall": 0.6805021280257832, "f1": 0.7085036544209539}, "10": {"lr": [1.1986127417882198e-05, 0.00028953039902753766], "train_loss": 0.05064263567328453, "total": 0.05064263724960916, "span_loss": 0.007810902902039154, "start_loss": 0.021243530921658836, "end_loss": 0.021588203425911168, "val_score": 0.7066251171207651, "best_score": 0.7113776848424967, "new_best_model": false, "precision": 0.741079131152867, "recall": 0.6780160921798563, "f1": 0.7066251171207651}, "11": {"lr": [1.0500000000000003e-05, 0.0002505], "train_loss": 0.04444040730595589, "total": 0.04444040860324815, "span_loss": 0.006902211734607541, "start_loss": 0.01870870830094501, "end_loss": 0.018829516287686907, "val_score": 0.7050203147889883, "best_score": 0.7113776848424967, "new_best_model": false, "precision": 0.7395641733822541, "recall": 0.6762359867646462, "f1": 0.7050203147889883}, "12": {"lr": [9.013872582117811e-06, 0.00021146960097246246], "train_loss": 0.03910835087299347, "total": 0.03910835313024036, "span_loss": 0.00609888158876047, "start_loss": 0.016462355902103022, "end_loss": 0.016547167347822196, "val_score": 0.7054488373698681, "best_score": 0.7113776848424967, "new_best_model": false, "precision": 0.7406460538183925, "recall": 0.6761903962790263, "f1": 0.7054488373698681}, "13": {"lr": [7.564338553438001e-06, 0.00017340025990345064], "train_loss": 0.034610453993082047, "total": 0.03461045616495336, "span_loss": 0.00538779344553385, "start_loss": 0.014589085800145311, "end_loss": 0.014633574253890419, "val_score": 0.703196628032294, "best_score": 0.7113776848424967, "new_best_model": false, "precision": 0.7385791367870125, "recall": 0.6736387953605673, "f1": 0.703196628032294}, "14": {"lr": [6.1870902524743065e-06, 0.00013722937031498307], "train_loss": 0.031157871708273888, "total": 0.031157871542728567, "span_loss": 0.004851977741205206, "start_loss": 0.01320279837321009, "end_loss": 0.013103089564468956, "val_score": 0.7025908343501286, "best_score": 0.7113776848424967, "new_best_model": false, "precision": 0.7398505248266302, "recall": 0.671404967018203, "f1": 0.7025908343501286}, "15": {"lr": [4.916040103221507e-06, 0.00010384757955302797], "train_loss": 0.02822270616889, "total": 0.028222706145984357, "span_loss": 0.00437733179500744, "start_loss": 0.012015827279173509, "end_loss": 0.011829555334493126, "val_score": 0.7016576419886317, "best_score": 0.7113776848424967, "new_best_model": false, "precision": 0.7391474209282664, "recall": 0.670375208524508, "f1": 0.7016576419886317}, "16": {"lr": [3.7824855787278e-06, 7.40768580939564e-05], "train_loss": 0.025938989594578743, "total": 0.025938990397317372, "span_loss": 0.004061840445452925, "start_loss": 0.011072817696346925, "end_loss": 0.010804323992827805, "val_score": 0.7012633119121163, "best_score": 0.7113776848424967, "new_best_model": false, "precision": 0.738430308350936, "recall": 0.6702400709289364, "f1": 0.7012633119121163}, "17": {"lr": [2.814338553438001e-06, 4.865025990345063e-05], "train_loss": 0.023989362642169, "total": 0.02398936238083645, "span_loss": 0.003759026727308569, "start_loss": 0.01017159919888031, "end_loss": 0.010058754312718894, "val_score": 0.7011592505043321, "best_score": 0.7113776848424967, "new_best_model": false, "precision": 0.7407287993976038, "recall": 0.6680803132772083, "f1": 0.7011592505043321}, "18": {"lr": [2.0354380202105066e-06, 2.8193872215002235e-05], "train_loss": 0.022796085104346275, "total": 0.022796084988776902, "span_loss": 0.0035551709792945824, "start_loss": 0.009723929868456103, "end_loss": 0.009516968148723536, "val_score": 0.7006301606510682, "best_score": 0.7113776848424967, "new_best_model": false, "precision": 0.7410366345434073, "recall": 0.6669696788586329, "f1": 0.7006301606510682}}
8_entities_add_weight_keep_2_learn_all_10/r1s/8_entities_add_weight_keep_2_learn_all_10_s26092004_f0_r1_vs0.71138_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d8c42744d979194ebab35f64808ed7b77f9d7b932abc6d98137aa03aff09f07e
3
+ size 554318617
8_entities_add_weight_keep_2_learn_all_10/results/8_entities_add_weight_keep_2_learn_all_10_error_analyze_result_1.json ADDED
The diff for this file is too large to render. See raw diff
 
8_entities_add_weight_keep_2_learn_all_10/results/8_entities_add_weight_keep_2_learn_all_10_error_analyze_result_2.json ADDED
The diff for this file is too large to render. See raw diff
 
8_entities_add_weight_keep_2_learn_all_10/results/8_entities_add_weight_keep_2_learn_all_10_pred_test_1.json ADDED
The diff for this file is too large to render. See raw diff
 
8_entities_add_weight_keep_2_learn_all_10/results/8_entities_add_weight_keep_2_learn_all_10_pred_test_2.json ADDED
The diff for this file is too large to render. See raw diff
 
8_entities_add_weight_keep_2_learn_all_10/results/8_entities_add_weight_keep_2_learn_all_10_test_1.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "Best model": {
3
+ "Ent-I": {
4
+ "precision": 0.7368183459726103,
5
+ "recall": 0.7585277442134413,
6
+ "f1": 0.7475154518357253
7
+ },
8
+ "Ent-C": {
9
+ "precision": 0.659263271938733,
10
+ "recall": 0.6780573869433763,
11
+ "f1": 0.668528262338439
12
+ }
13
+ },
14
+ "Last model": {
15
+ "Ent-I": {
16
+ "precision": 0.7341135594763334,
17
+ "recall": 0.7462589459980051,
18
+ "f1": 0.7401364256781204
19
+ },
20
+ "Ent-C": {
21
+ "precision": 0.6529212764006099,
22
+ "recall": 0.6631070665793823,
23
+ "f1": 0.6579747485240645
24
+ }
25
+ }
26
+ }
8_entities_add_weight_keep_2_learn_all_10/results/8_entities_add_weight_keep_2_learn_all_10_test_2.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "Best model": {
3
+ "Ent-I": {
4
+ "precision": 0.7320261437901943,
5
+ "recall": 0.7599219258288317,
6
+ "f1": 0.7457132383429139
7
+ },
8
+ "Ent-C": {
9
+ "precision": 0.6550273077261571,
10
+ "recall": 0.6793574148011149,
11
+ "f1": 0.666970548378755
12
+ }
13
+ },
14
+ "Last model": {
15
+ "Ent-I": {
16
+ "precision": 0.7311466472826357,
17
+ "recall": 0.7479319639364737,
18
+ "f1": 0.7394440565667
19
+ },
20
+ "Ent-C": {
21
+ "precision": 0.6502816645460201,
22
+ "recall": 0.6645928127025121,
23
+ "f1": 0.6573593520608381
24
+ }
25
+ }
26
+ }
8_entities_add_weight_keep_2_learn_all_10/results/8_entities_add_weight_keep_2_learn_all_10_test_df_1.xlsx ADDED
Binary file (5.28 kB). View file
 
8_entities_add_weight_keep_2_learn_all_10/results/8_entities_add_weight_keep_2_learn_all_10_test_df_2.xlsx ADDED
Binary file (5.28 kB). View file