SS3M commited on
Commit
7659e50
·
verified ·
1 Parent(s): 3743fbe

Upload 11_12_13_lr_17's state dict

Browse files
.gitattributes CHANGED
@@ -39,3 +39,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
39
  1_lr_add_bm25_10/logs/1_lr_add_bm25_10_log_plot.jpg filter=lfs diff=lfs merge=lfs -text
40
  10_lr_attn_chunk_pool_instead_mean_12/logs/10_lr_attn_chunk_pool_instead_mean_12_log_plot.jpg filter=lfs diff=lfs merge=lfs -text
41
  11_12_lr_14/logs/11_12_lr_14_log_plot.jpg filter=lfs diff=lfs merge=lfs -text
 
 
39
  1_lr_add_bm25_10/logs/1_lr_add_bm25_10_log_plot.jpg filter=lfs diff=lfs merge=lfs -text
40
  10_lr_attn_chunk_pool_instead_mean_12/logs/10_lr_attn_chunk_pool_instead_mean_12_log_plot.jpg filter=lfs diff=lfs merge=lfs -text
41
  11_12_lr_14/logs/11_12_lr_14_log_plot.jpg filter=lfs diff=lfs merge=lfs -text
42
+ 11_12_13_lr_17/logs/11_12_13_lr_17_log_plot.jpg filter=lfs diff=lfs merge=lfs -text
11_12_13_lr_17/11_12_13_lr_17.py ADDED
@@ -0,0 +1,1593 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ file_path = "/kaggle/input/notebooks/sambui22022517/kltn-lr-bm25/bm25_scores.npy"
60
+
61
+ bm25_scores = np.load(file_path, allow_pickle=True)
62
+ print(bm25_scores.shape)
63
+
64
+ # %% [code]
65
+ # Global config
66
+ SEEDS = [26092004]
67
+ topk = 1
68
+ nfolds = 5
69
+ only_fold_idx = None
70
+ test_only = 0
71
+ debug_only = 0
72
+
73
+ # Config thư mục
74
+ dataset = 'kltn/raw' # vhe, bkee, casie, kltn/only_issues, kltn/only_actions, kltn/raw
75
+ root_dir = f'/kaggle/input/notebooks/sambui22022517/kltn-data/{dataset}' ## Thư mục chứa file train, val, test
76
+ train_dir = f'{root_dir}'
77
+ # val_dir = f'{root_dir}/val'
78
+ test_dir = f'{root_dir}'
79
+
80
+ # Config checkpoints
81
+
82
+ # Config training
83
+ epochs = 18 if not debug_only else 2
84
+ batch_size = 32
85
+ device = "cuda" if torch.cuda.is_available() else "cpu"
86
+ # # Thêm biến toàn cục nào đó vào đây
87
+ repo_name = 'SS3M/kltn-lr-experiments'
88
+ state_dict_save_name = "11_12_13_lr_17"
89
+ checkpoints_dir = state_dict_save_name
90
+ pretrained_dir = "/kaggle/working"
91
+ os.makedirs(f'{checkpoints_dir}', exist_ok=True)
92
+
93
+ backbone_model_name = "bert-base-uncased" if dataset == "casie" else "vinai/phobert-base"
94
+ word_tokenize = lambda text: [token.text for token in en_tokenize_tool(text)] if dataset == "casie" else vi_tokenize_tool(text)
95
+ max_len_dict = {
96
+ 'kltn/raw': 256,
97
+ 'kltn/only_issues': 52,
98
+ 'kltn/only_actions': 69,
99
+ 'vhe': 51,
100
+ 'bkee': 62,
101
+ 'casie': 40,
102
+ }
103
+ zero_events_rate_dict = {
104
+ 'kltn/raw': 1000,
105
+ 'kltn/only_issues': 0,
106
+ 'kltn/only_actions': 0.2,
107
+ 'vhe': 1000, # mean keep all zero-events samples
108
+ 'bkee': 1000,
109
+ 'casie': 1000,
110
+ }
111
+
112
+ max_len = max_len_dict[dataset]
113
+ max_n_parts = 2
114
+ max_span_len = 14
115
+ n_negs = 5 * 20
116
+ zero_events_rate = zero_events_rate_dict[dataset]
117
+
118
+ # Trainer
119
+ trainer_params = {
120
+ "training_time": "00:11:30:00",
121
+ "eval_mode": "max",
122
+ "topk": topk,
123
+ "save_name": state_dict_save_name,
124
+ "save_best": True,
125
+ "save_last": True,
126
+ "device": device,
127
+ "logging": True,
128
+ "logging_file": True,
129
+ "checkpoints_dir": checkpoints_dir,
130
+ "early_stopping": 30,
131
+ "eval_from_ratio": 0.4,
132
+ "eval_every": 1,
133
+ "schedule_in_step": False,
134
+ "use_ema": True,
135
+ "ema_from_ratio": 0.3,
136
+ "ema_decay": 0.9995,
137
+ "max_grad_norm": 200.0,
138
+ "return_best": True,
139
+ "return_last": True,
140
+ }
141
+
142
+ # Memory
143
+ train_memory_params = {
144
+ 'max_len': max_len,
145
+ 'max_n_parts': max_n_parts,
146
+ 'n_negs': n_negs,
147
+ }
148
+ val_memory_params = {
149
+ 'max_len': max_len,
150
+ 'max_n_parts': max_n_parts,
151
+ 'n_negs': n_negs,
152
+ }
153
+ corpus_memory_params = {
154
+ 'max_len': max_len,
155
+ 'max_n_parts': max_n_parts,
156
+ }
157
+
158
+ # Data Loader
159
+ def seed_worker(worker_id):
160
+ worker_seed = torch.initial_seed() % 2**32
161
+ np.random.seed(worker_seed)
162
+ random.seed(worker_seed)
163
+
164
+ train_loader_params = {
165
+ 'batch_size': batch_size,
166
+ 'shuffle': True,
167
+ 'pin_memory':True,
168
+ 'num_workers': 2,
169
+ 'drop_last': False,
170
+ 'worker_init_fn': seed_worker,
171
+ 'persistent_workers': False,
172
+ }
173
+ val_loader_params = {
174
+ 'batch_size': batch_size,
175
+ 'shuffle': False,
176
+ 'pin_memory':True,
177
+ 'num_workers': 1,
178
+ 'drop_last': False,
179
+ 'worker_init_fn': seed_worker,
180
+ 'persistent_workers': False,
181
+ }
182
+
183
+ # Model
184
+ model_params = {
185
+ 'backbone_name': backbone_model_name,
186
+ 'projection_dim': 256,
187
+ 'normalize': True,
188
+ }
189
+
190
+ # Loss Func
191
+ loss_func_params = {
192
+ 'lambda_contrastive': 1.0,
193
+ 'lambda_triplet': 0.5,
194
+ }
195
+ eval_func_params = {}
196
+
197
+ # Optim
198
+ optim_params = {
199
+ 'name': 'AdamW',
200
+ 'lr': 1e-4,
201
+ 'weight_decay': 1e-4,
202
+ }
203
+ scheduler_params = {
204
+ 'name': 'CosineAnnealingLR',
205
+ 'T_max': 20, # Số epoch để hoàn thành một chu kỳ giảm LR
206
+ 'eta_min': 1e-6 # Learning rate nhỏ nhất trong chu kỳ
207
+ }
208
+
209
+ # %% [code]
210
+ def set_seed(seed=42):
211
+ random.seed(seed)
212
+ np.random.seed(seed)
213
+ torch.manual_seed(seed)
214
+ torch.cuda.manual_seed(seed)
215
+ torch.cuda.manual_seed_all(seed) # if using multi-GPU
216
+ torch.use_deterministic_algorithms(False)
217
+ torch.backends.cudnn.deterministic = True
218
+ torch.backends.cudnn.benchmark = False
219
+ os.environ['PYTHONHASHSEED'] = str(seed)
220
+
221
+ # %% [code]
222
+ class CustomLoss(nn.Module):
223
+ def __init__(
224
+ self,
225
+ temperature=0.05,
226
+ margin=0.2,
227
+ lambda_contrastive=1.0,
228
+ lambda_triplet=0.5,
229
+ ):
230
+ super().__init__()
231
+
232
+ self.temperature = temperature
233
+ self.margin = margin
234
+
235
+ self.lambda_contrastive = lambda_contrastive
236
+ self.lambda_triplet = lambda_triplet
237
+
238
+ def forward(
239
+ self,
240
+ encoded_text,
241
+ encoded_pos,
242
+ encoded_neg,
243
+ pos_mask
244
+ ):
245
+ loss_contrastive = self.multi_pos_contrastive_loss(encoded_text, encoded_pos, encoded_neg, pos_mask)
246
+ loss_triplet = self.hardest_triplet_loss(encoded_text, encoded_pos, encoded_neg, pos_mask)
247
+
248
+ total_loss = (
249
+ self.lambda_contrastive * loss_contrastive +
250
+ self.lambda_triplet * loss_triplet
251
+ )
252
+
253
+ return {
254
+ "total": total_loss,
255
+ "contrastive_loss": loss_contrastive,
256
+ "triplet_loss": loss_triplet,
257
+ }
258
+
259
+ def multi_pos_contrastive_loss(self, q, pos, neg, pos_mask):
260
+ B, P, D = pos.shape
261
+ N = neg.shape[1]
262
+
263
+ # ===== concat docs =====
264
+ docs = torch.cat([pos, neg], dim=1) # [B, P+N, D]
265
+
266
+ # ===== similarity =====
267
+ logits = torch.matmul(q.unsqueeze(1), docs.transpose(1, 2)).squeeze(1)
268
+ logits = logits / self.temperature # [B, P+N]
269
+
270
+ # ===== labels =====
271
+ labels = torch.zeros_like(logits)
272
+ labels[:, :P] = pos_mask # chỉ pos hợp lệ
273
+
274
+ # ===== log-softmax =====
275
+ log_prob = logits - torch.logsumexp(logits, dim=1, keepdim=True)
276
+
277
+ # ===== normalize theo số pos thật =====
278
+ pos_count = pos_mask.sum(dim=1).clamp(min=1)
279
+
280
+ loss = -(labels * log_prob).sum(dim=1) / pos_count
281
+
282
+ return loss.mean()
283
+
284
+ def hardest_triplet_loss(self, q, pos, neg, pos_mask):
285
+ # ===== similarity =====
286
+ pos_sim = torch.matmul(q.unsqueeze(1), pos.transpose(1, 2)).squeeze(1) # [B, P]
287
+ neg_sim = torch.matmul(q.unsqueeze(1), neg.transpose(1, 2)).squeeze(1) # [B, N]
288
+
289
+ # ===== mask pos =====
290
+ pos_sim_masked = pos_sim.clone()
291
+ pos_sim_masked[pos_mask == 0] = float('inf') # loại pad
292
+
293
+ # ===== hardest =====
294
+ hardest_pos = pos_sim_masked.min(dim=1).values
295
+ hardest_neg = neg_sim.max(dim=1).values
296
+
297
+ # ===== loss =====
298
+ loss = F.relu(self.margin + hardest_neg - hardest_pos)
299
+
300
+ return loss.mean()
301
+
302
+ # %% [code]
303
+ class CustomEvalFn(nn.Module):
304
+ def __init__(self):
305
+ super().__init__()
306
+
307
+ def forward(self, pred_topk, real_topk):
308
+ """
309
+ pred_topk: List[List[int]] shape [B, K]
310
+ real_topk: List[List[int]] shape [B, Ki]
311
+ """
312
+
313
+ B = len(pred_topk)
314
+
315
+ total_recall = 0.0
316
+ total_map = 0.0
317
+ total_mrp = 0.0
318
+
319
+ for i in range(B):
320
+ preds = pred_topk[i]
321
+ gts = set(real_topk[i])
322
+
323
+ # ===== Recall@K =====
324
+ hit = any(p in gts for p in preds)
325
+ total_recall += 1.0 if hit else 0.0
326
+
327
+ # ===== AP =====
328
+ num_hits = 0
329
+ ap = 0.0
330
+
331
+ for rank, p in enumerate(preds, start=1):
332
+ if p in gts:
333
+ num_hits += 1
334
+ precision_at_rank = num_hits / rank
335
+ ap += precision_at_rank
336
+
337
+ if len(gts) > 0:
338
+ ap /= len(gts)
339
+
340
+ total_map += ap
341
+
342
+ # ===== R-Precision =====
343
+ r = len(gts)
344
+
345
+ if r > 0:
346
+ top_r = preds[:r]
347
+
348
+ tp_r = sum(p in gts for p in top_r)
349
+
350
+ rp = tp_r / r
351
+ else:
352
+ rp = 0.0
353
+
354
+ total_mrp += rp
355
+
356
+ recall = total_recall / B
357
+ mAP = total_map / B
358
+ mRP = total_mrp / B
359
+
360
+ return {
361
+ "recall": recall,
362
+ "mAP": mAP,
363
+ "mRP": mRP,
364
+ }
365
+
366
+ # %% [code]
367
+ class EncodeModel(nn.Module):
368
+ def __init__(
369
+ self,
370
+ backbone_name,
371
+ projection_dim,
372
+ normalize=True,
373
+ dropout=0.1
374
+ ):
375
+ super().__init__()
376
+
377
+ self.encoder = AutoModel.from_pretrained(backbone_name)
378
+
379
+ hidden_size = self.encoder.config.hidden_size
380
+
381
+ # mạnh hơn single linear
382
+ self.proj = nn.Sequential(
383
+ nn.Linear(hidden_size, hidden_size),
384
+ nn.GELU(),
385
+ nn.Dropout(dropout),
386
+ nn.Linear(hidden_size, projection_dim)
387
+ )
388
+
389
+ # residual projection
390
+ self.residual_proj = (
391
+ nn.Identity()
392
+ if hidden_size == projection_dim
393
+ else nn.Linear(hidden_size, projection_dim)
394
+ )
395
+ self.chunk_attn = nn.Linear(hidden_size, 1)
396
+
397
+ self.normalize = normalize
398
+
399
+ def mean_pooling(self, hidden, attention_mask):
400
+ mask = attention_mask.unsqueeze(-1).float() # [N, L, 1]
401
+ pooled = (hidden * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1e-6)
402
+
403
+ return pooled
404
+
405
+ def chunk_attention_pooling(self, chunk_repr, dim):
406
+ scores = self.chunk_attn(chunk_repr)
407
+
408
+ weights = torch.softmax(scores, dim=dim)
409
+
410
+ pooled = (chunk_repr * weights).sum(dim=dim)
411
+
412
+ return pooled
413
+
414
+ def forward(self, input_ids, attention_mask, is_query=True):
415
+
416
+ if is_query:
417
+ # [B, n_parts, L]
418
+ B, n_parts, L = input_ids.shape
419
+
420
+ input_ids = input_ids.view(-1, L)
421
+ attention_mask = attention_mask.view(-1, L)
422
+
423
+ outputs = self.encoder(
424
+ input_ids=input_ids,
425
+ attention_mask=attention_mask
426
+ )
427
+
428
+ hidden = outputs.last_hidden_state # [B*n_parts, L, H]
429
+
430
+ chunk_repr = self.mean_pooling(hidden, attention_mask) # [B*n_parts, H]
431
+ chunk_repr = chunk_repr.view(B, n_parts, -1) # [B, n_parts, H]
432
+ final_repr = self.chunk_attention_pooling(chunk_repr, dim=1) # [B, H]
433
+ # [B, H]
434
+
435
+ else:
436
+ # [B, K, n_parts, L]
437
+ B, K, n_parts, L = input_ids.shape
438
+
439
+ input_ids = input_ids.view(-1, L)
440
+ attention_mask = attention_mask.view(-1, L)
441
+
442
+ outputs = self.encoder(
443
+ input_ids=input_ids,
444
+ attention_mask=attention_mask
445
+ )
446
+
447
+ hidden = outputs.last_hidden_state
448
+
449
+ chunk_repr = self.mean_pooling(hidden, attention_mask) # [B*K*n_parts, H]
450
+ chunk_repr = chunk_repr.view(B, K, n_parts, -1) # [B, K, n_parts, H]
451
+ final_repr = self.chunk_attention_pooling(chunk_repr, dim=2) # [B, K, H]
452
+
453
+ # residual MLP projection
454
+ emb = self.proj(final_repr) + self.residual_proj(final_repr)
455
+
456
+ if self.normalize:
457
+ emb = F.normalize(emb, dim=-1)
458
+
459
+ return emb
460
+
461
+ def test_model():
462
+ model = nn.DataParallel(EncodeModel('vinai/phobert-base', 256, True)).to(device)
463
+ model.eval()
464
+
465
+ bz = 32
466
+ vocab_size = 1000
467
+ qi = torch.randint(0, vocab_size, (bz, 1, 256)).to(device)
468
+ qa = torch.ones(bz, 1, 256).to(device)
469
+ di = torch.randint(0, vocab_size, (bz, 5, 2, 256)).to(device)
470
+ da = torch.ones(bz, 5, 2, 256).to(device)
471
+
472
+ st = time.time()
473
+ with torch.no_grad():
474
+ encoded_text = model(qi, qa, is_query=True)
475
+ encoded_pos = model(di, da, is_query=False)
476
+ encoded_neg = model(di, da, is_query=False)
477
+ print(encoded_text.shape, encoded_pos.shape, encoded_neg.shape)
478
+ print(time.time() - st)
479
+
480
+ del model, qi, qa, di, da, encoded_text, encoded_pos, encoded_neg
481
+ torch.cuda.empty_cache()
482
+ gc.collect()
483
+ test_model()
484
+
485
+ # %% [code]
486
+ def configure_optimizers(network, optim_params, scheduler_params):
487
+ try:
488
+ optim_params = copy.copy(optim_params)
489
+ scheduler_params = copy.copy(scheduler_params)
490
+
491
+ optim_name = optim_params.pop('name')
492
+ scheduler_name = scheduler_params.pop('name')
493
+
494
+ optimizer_cls = globals().get(optim_name) or getattr(optim, optim_name, None)
495
+ scheduler_cls = globals().get(scheduler_name) or getattr(optim.lr_scheduler, scheduler_name, None)
496
+
497
+ if optimizer_cls is None:
498
+ raise ValueError(f"Optimizer '{optim_name}' is not available!")
499
+
500
+ optimizer = optimizer_cls(network.parameters(), **optim_params)
501
+
502
+ scheduler = None
503
+ if scheduler_params and scheduler_cls: # Chỉ tạo scheduler nếu có tham số
504
+ scheduler = scheduler_cls(optimizer, **scheduler_params)
505
+
506
+ return optimizer, scheduler
507
+
508
+ except KeyError as e:
509
+ raise ValueError(f"Missing {e} in config!!")
510
+
511
+ def freeze(self, model):
512
+ model.eval()
513
+ for param in model.parameters():
514
+ param.requires_grad = False
515
+
516
+ def unfreeze(self, model):
517
+ model.train()
518
+ for param in model.parameters():
519
+ param.requires_grad = True
520
+
521
+ def reduce_batch_size(loader, ratio=0.5):
522
+ new_bs = max(1, int(loader.batch_size * ratio))
523
+
524
+ shuffle = isinstance(loader.sampler, RandomSampler)
525
+
526
+ new_loader = DataLoader(
527
+ dataset=loader.dataset,
528
+ batch_size=new_bs,
529
+ shuffle=shuffle,
530
+ sampler=None if shuffle else loader.sampler,
531
+ num_workers=loader.num_workers,
532
+ collate_fn=loader.collate_fn,
533
+ pin_memory=loader.pin_memory,
534
+ drop_last=loader.drop_last,
535
+ timeout=loader.timeout,
536
+ worker_init_fn=loader.worker_init_fn,
537
+ multiprocessing_context=loader.multiprocessing_context,
538
+ generator=loader.generator,
539
+ prefetch_factor=loader.prefetch_factor if loader.num_workers > 0 else None,
540
+ persistent_workers=loader.persistent_workers,
541
+ pin_memory_device=loader.pin_memory_device
542
+ )
543
+
544
+ return new_loader
545
+
546
+ def list_to_tuple(x):
547
+ if isinstance(x, (list, tuple)):
548
+ return tuple(list_to_tuple(i) for i in x)
549
+ return x
550
+
551
+ def fmt(x):
552
+ if isinstance(x, float):
553
+ return round(x, 5)
554
+ if isinstance(x, dict):
555
+ return {k: fmt(v) for k, v in x.items()}
556
+ if isinstance(x, list):
557
+ return [fmt(v) for v in x]
558
+ return x
559
+
560
+ class ModelEmaV3Proxy(ModelEmaV3):
561
+ def __getattr__(self, name):
562
+ try:
563
+ return super().__getattr__(name)
564
+ except AttributeError:
565
+ return getattr(self.module, name)
566
+
567
+ class DataParallelProxy(nn.DataParallel):
568
+ def __getattr__(self, name):
569
+ try:
570
+ return super().__getattr__(name)
571
+ except AttributeError:
572
+ attr = getattr(self.module, name)
573
+
574
+ if callable(attr):
575
+ def wrapper(*args, **kwargs):
576
+ return self._parallel_apply_method(name, *args, **kwargs)
577
+ return wrapper
578
+
579
+ return attr
580
+
581
+ def _parallel_apply_method(self, method_name, *inputs, **kwargs):
582
+ if not self.device_ids:
583
+ return getattr(self.module, method_name)(*inputs, **kwargs)
584
+
585
+ inputs_scattered, kwargs_scattered = self.scatter(inputs, kwargs, self.device_ids)
586
+
587
+ replicas = self.replicate(self.module, self.device_ids)
588
+
589
+ outputs = self.parallel_apply(
590
+ [getattr(replica, method_name) for replica in replicas],
591
+ inputs_scattered,
592
+ kwargs_scattered
593
+ )
594
+
595
+ return self.gather(outputs, self.output_device)
596
+
597
+ class Trainer:
598
+ def __init__(
599
+ 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,
600
+ logging=0, logging_file=False, checkpoints_dir="", early_stopping=False, eval_from_ratio=-1, eval_every=1, device='cpu',
601
+ schedule_in_step=True, use_ema=True, ema_from_ratio=-1, ema_decay=0.999, return_best=True, return_last=True
602
+ ):
603
+ self.ema_net = None
604
+
605
+ self.training_time = self._time_str_to_seconds(training_time)
606
+ self.mode = eval_mode
607
+ self.topk = topk
608
+ self.device = device
609
+ self.logging = logging if logging < epochs else 1
610
+ self.logging_file = logging_file
611
+ self.checkpoints_dir = checkpoints_dir
612
+ self.early_stopping = early_stopping
613
+ self.eval_from_ratio = eval_from_ratio
614
+ self.eval_every = eval_every
615
+ self.save_name = save_name
616
+ self.save_best = save_best
617
+ self.save_last = save_last
618
+ self.return_best = return_best
619
+ self.return_last = return_last
620
+ self.max_grad_norm = max_grad_norm
621
+ self.schedule_in_step = schedule_in_step
622
+ self.use_ema = use_ema
623
+ self.ema_from_ratio = ema_from_ratio
624
+ self.ema_decay = ema_decay
625
+
626
+ self.best_stage = [[float('-inf') if self.mode == 'max' else float('inf'), None, None]]
627
+ self.grad_scaler = torch.amp.GradScaler(self.device, init_scale=1024.0)
628
+
629
+ def fit(self, network, optimizer, scheduler, loss_fn, epochs, train_loader, val_loader=None, corpus_loader=None, eval_fn=None, start_epoch=1, start_training_time=None, refresh_every=3):
630
+ if eval_fn is None:
631
+ if self.mode == "max":
632
+ eval_fn = lambda *x: -loss_fn(*x)
633
+ else:
634
+ eval_fn = lambda *x: loss_fn(*x)
635
+
636
+ if torch.cuda.device_count() > 1:
637
+ network = DataParallelProxy(network)
638
+ network = network.to(self.device)
639
+
640
+ if not start_training_time:
641
+ start_training_time = time.time()
642
+
643
+ start_ema = int(epochs * self.ema_from_ratio)
644
+ start_eval = int(epochs * self.eval_from_ratio)
645
+
646
+ if val_loader is None:
647
+ print(f'[Trainer CallBack] 📢 Không có Val Set, không thể đánh giá và Early Stopping!')
648
+ else:
649
+ model_to_use_str = 'mô hình EMA' if self.use_ema else 'mô hình gốc'
650
+ start_model_update_str = f'Bắt đầu cập nhật EMA từ epoch {start_epoch + start_ema}!' if self.use_ema else ''
651
+ print(f'[Trainer CallBack] 📢 Đánh giá bằng {model_to_use_str} từ epoch {start_epoch + start_eval}!', start_model_update_str)
652
+
653
+ training_log = {}
654
+ for epoch in range(start_epoch, epochs+start_epoch):
655
+ if self.use_ema and self.ema_net is None and epoch - start_epoch >= start_ema:
656
+ self.ema_net = ModelEmaV3Proxy(network, self.ema_decay, device=self.device)
657
+
658
+ try:
659
+ eval_net = self.ema_net if (self.use_ema and self.ema_net is not None) else network
660
+ if (epoch - start_epoch) % refresh_every == 0:
661
+ encoded_docs = self._get_encoded_docs(eval_net, corpus_loader)
662
+ print(f"[Trainer CallBack] 📢 Epoch {epoch}/{epochs}: Refresh Encoded Doc (refresh_every={refresh_every})!")
663
+
664
+ train_loss_epoch, train_loss_epoch_dict = self._train_epoch(network, train_loader, optimizer, scheduler, loss_fn, encoded_docs)
665
+ logging_dict = {'lr': [group['lr'] for group in optimizer.param_groups], 'train_loss': train_loss_epoch}
666
+ logging_dict.update(train_loss_epoch_dict)
667
+
668
+ if val_loader is not None and epoch - start_epoch >= start_eval and (epoch - start_epoch - start_eval) % self.eval_every == 0:
669
+ val_score, val_score_dict, _ = self._eval_epoch(eval_net, val_loader, eval_fn, encoded_docs)
670
+ update = self._update_best_network(eval_net, val_score, epoch)
671
+ logging_dict.update({'val_score': val_score, 'best_score': self.best_stage[0][0], 'new_best_model': update})
672
+ logging_dict.update(val_score_dict)
673
+ if not self.schedule_in_step and scheduler:
674
+ scheduler.step()
675
+
676
+ except RuntimeError as e:
677
+ if "out of memory" in str(e).lower():
678
+ print(f"[Trainer CallBack] ⚠️ Epoch {epoch}/{epochs}: CUDA Out of Memory! Clearing GPU cache...")
679
+ torch.cuda.empty_cache()
680
+ gc.collect()
681
+ if torch.cuda.is_available():
682
+ torch.cuda.synchronize()
683
+ print(f"[Trainer CallBack] ✅ Epoch {epoch}/{epochs}: GPU memory cleared")
684
+
685
+ train_loader = reduce_batch_size(train_loader, ratio=0.5)
686
+ if val_loader is not None:
687
+ val_loader = reduce_batch_size(val_loader, ratio=0.5)
688
+
689
+ logging_dict = {'lr': [group['lr'] for group in optimizer.param_groups], 'train_loss': float('inf')}
690
+ else:
691
+ raise
692
+
693
+ training_log[epoch] = logging_dict
694
+ if self.is_early_stopping(epoch):
695
+ print(f'[Trainer CallBack] 📢 Epoch {epoch}/{epochs}: Detect Overfitting! Breaking Training Process...')
696
+ break
697
+ if self.logging:
698
+ if epoch % self.logging == 0:
699
+ print(f'[Trainer CallBack] 📢 Epoch {epoch}/{epochs}:', fmt(logging_dict))
700
+ else:
701
+ print(f'{epoch}...', end=' ')
702
+
703
+ if self._at_time_limit(start_training_time):
704
+ 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}')
705
+ break
706
+
707
+ if self.logging_file:
708
+ os.makedirs(f'{self.checkpoints_dir}/logs', exist_ok=True)
709
+ with open(f"{self.checkpoints_dir}/logs/{self.save_name}_logging.json", "a", encoding="utf-8") as f:
710
+ f.write(json.dumps(training_log))
711
+
712
+ if self.use_ema and self.ema_net is not None:
713
+ self._save_state_dict(self.ema_net.module)
714
+ else:
715
+ self._save_state_dict(network)
716
+ print(f'[Trainer CallBack] 📢 Kết thúc training.\n')
717
+
718
+ best_model, last_model = None, None
719
+ eval_net = self.ema_net.module if (self.use_ema and self.ema_net is not None) else network
720
+ if self.return_best :
721
+ best_model = self.best_stage[0][2] if self.best_stage[0][2] is not None else eval_net.state_dict()
722
+ best_model = {k.replace("module.", ""): v.detach().cpu().clone() for k, v in best_model.items()}
723
+ if self.return_last:
724
+ last_model = eval_net.state_dict()
725
+ last_model = {k.replace("module.", ""): v.detach().cpu().clone() for k, v in last_model.items()}
726
+
727
+ del network
728
+ torch.cuda.empty_cache()
729
+ gc.collect()
730
+ return training_log, best_model, last_model
731
+
732
+ def _time_str_to_seconds(self, time_str):
733
+ days, hours, minutes, seconds = map(int, time_str.split(":"))
734
+ return days * 86400 + hours * 3600 + minutes * 60 + seconds
735
+
736
+ def _update_best_network(self, network, val_score, epoch):
737
+ topk = max(1, self.topk)
738
+ self.best_stage.append([val_score, epoch, {k: v.detach().cpu().clone() for k, v in network.state_dict().items()}])
739
+ self.best_stage = sorted(self.best_stage, reverse=(self.mode == 'max'), key=lambda x: x[0])[:topk]
740
+ if val_score in [x[0] for x in self.best_stage]:
741
+ return True
742
+ return False
743
+
744
+ def is_early_stopping(self, epoch):
745
+ if self.best_stage[0][1] is None:
746
+ return False
747
+ if not self.early_stopping:
748
+ return False
749
+ return epoch - self.best_stage[0][1] >= self.early_stopping
750
+
751
+ def _at_time_limit(self, start_training_time):
752
+ return time.time() - start_training_time >= self.training_time
753
+
754
+ def _save_state_dict(self, network):
755
+ if self.topk <= 0:
756
+ return
757
+
758
+ if self.save_best:
759
+ for r in range(self.topk):
760
+ os.makedirs(f'{self.checkpoints_dir}/r{r+1}s', exist_ok=True)
761
+
762
+ for rank, (score, epoch, state_dict) in enumerate(self.best_stage):
763
+ if state_dict is None:
764
+ continue
765
+ state_dict = {k.replace("module.", ""): v.detach().cpu().clone() for k, v in state_dict.items()}
766
+ 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')
767
+ if self.save_last:
768
+ os.makedirs(f'{self.checkpoints_dir}/lasts', exist_ok=True)
769
+ state_dict = {k.replace("module.", ""): v.detach().cpu().clone() for k, v in network.state_dict().items()}
770
+ torch.save(state_dict, f'{self.checkpoints_dir}/lasts/{self.save_name}_last_{"ema" if self.ema_net is not None else ""}.pth')
771
+
772
+ def _train_epoch(self, network, train_loader, optimizer, scheduler, loss_fn, encoded_docs):
773
+ network.train()
774
+ total_loss = 0
775
+ total_loss_dict = {}
776
+ for batch_idx, batch in enumerate(train_loader):
777
+ optimizer.zero_grad()
778
+ with torch.autocast(device_type=self.device, dtype=torch.float16):
779
+ loss, loss_dict = self._cal_loss(network, batch, batch_idx, loss_fn, encoded_docs)
780
+
781
+ for k, v in loss_dict.items():
782
+ t = total_loss_dict.get(k, 0)
783
+ total_loss_dict[k] = t + v
784
+ self.grad_scaler.scale(loss).backward()
785
+ self.grad_scaler.unscale_(optimizer)
786
+ grad_norm = nn.utils.clip_grad_norm_(network.parameters(), self.max_grad_norm)
787
+ # print(grad_norm) # Bỏ cmt dòng này để biết nên chọn max_grad_norm bằng bao nhiêu...
788
+ self.grad_scaler.step(optimizer)
789
+ self.grad_scaler.update()
790
+ if self.schedule_in_step and scheduler:
791
+ scheduler.step()
792
+ if self.use_ema and self.ema_net is not None:
793
+ self.ema_net.update(network)
794
+ total_loss += loss
795
+ return (total_loss / len(train_loader)).item(), {k: v.item() / len(train_loader) for k, v in total_loss_dict.items()}
796
+
797
+ def _eval_epoch(self, network, val_loader, eval_fn, encoded_docs):
798
+ network.eval()
799
+ total_score = 0.0
800
+ total_score_dict = {}
801
+ object_lists = None # sẽ init sau
802
+
803
+ with torch.no_grad():
804
+ for batch_idx, batch in enumerate(val_loader):
805
+ score, score_dict, objects = self._cal_val_score(network, batch, batch_idx, eval_fn, encoded_docs)
806
+ total_score += score
807
+
808
+ for k, v in score_dict.items():
809
+ t = total_score_dict.get(k, 0)
810
+ total_score_dict[k] = t + v
811
+
812
+ if objects:
813
+ if object_lists is None:
814
+ object_lists = [[] for _ in range(len(objects))]
815
+
816
+ for i, obj in enumerate(objects):
817
+ object_lists[i].append(obj.detach())
818
+
819
+ if object_lists is not None:
820
+ object_arrays = [
821
+ torch.concat(obj_list, dim=0).cpu().numpy()
822
+ for obj_list in object_lists
823
+ ]
824
+ else:
825
+ object_arrays = []
826
+
827
+ return total_score / len(val_loader), {k: v / len(val_loader) for k, v in total_score_dict.items()}, object_arrays
828
+
829
+ def _get_encoded_docs(self, network, corpus_loader):
830
+ network.eval()
831
+ with torch.no_grad():
832
+ encoded_docs = []
833
+ for batch_idx, batch in enumerate(corpus_loader):
834
+ input_ids = batch['input_ids'].to(self.device)
835
+ attn_mask = batch['attn_mask'].to(self.device)
836
+ encoded_doc = network(input_ids, attn_mask, is_query=False)
837
+ encoded_docs.append(encoded_doc)
838
+ encoded_docs = torch.concat(encoded_docs, dim=0).squeeze(1)
839
+ return encoded_docs
840
+
841
+ def _cal_loss(self, network, batch, batch_idx, loss_fn, encoded_docs):
842
+ # Bạn cần override _cal_loss để tính loss
843
+ text_input_ids = batch['text_input_ids'].to(self.device)
844
+ text_attn_mask = batch['text_attn_mask'].to(self.device)
845
+ pos_idxes = batch['pos_idxes'].to(self.device)
846
+ pos_mask = batch['pos_mask'].to(self.device)
847
+ neg_idxes = batch['neg_idxes'].to(self.device)
848
+
849
+ encoded_text = network(text_input_ids, text_attn_mask, is_query=True)
850
+ encoded_pos = encoded_docs[pos_idxes]
851
+ encoded_neg = encoded_docs[neg_idxes]
852
+
853
+ loss_dict = loss_fn(encoded_text, encoded_pos, encoded_neg, pos_mask)
854
+ return loss_dict['total'], loss_dict
855
+
856
+ def _cal_val_score(self, network, batch, batch_idx, eval_fn, encoded_docs):
857
+ # 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)
858
+ text_input_ids = batch['text_input_ids'].to(self.device)
859
+ text_attn_mask = batch['text_attn_mask'].to(self.device)
860
+ gt_pos_idxes = batch['gt_pos_idxes']
861
+ encoded_text = network(text_input_ids, text_attn_mask, is_query=True)
862
+
863
+ scores = torch.matmul(encoded_text, encoded_docs.T)
864
+ topk_scores, topk_indices = torch.topk(scores, k=10)
865
+ pred_topk = [
866
+ idx[score > 0].tolist()
867
+ for score, idx in zip(topk_scores, topk_indices)
868
+ ]
869
+
870
+ pred_topk = list_to_tuple(pred_topk)
871
+ gt_pos_idxes = list_to_tuple(gt_pos_idxes)
872
+ score_dict = eval_fn(pred_topk, gt_pos_idxes)
873
+ return score_dict['recall'], score_dict, []
874
+
875
+ # %% [code]
876
+ def tokenize_to_parts(text, tokenizer, max_len, max_n_parts):
877
+ # Tokenize với overflow để chia thành nhiều đoạn
878
+ enc = tokenizer(
879
+ text,
880
+ max_length=max_len*max_n_parts,
881
+ truncation=True,
882
+ padding="max_length",
883
+ return_overflowing_tokens=True,
884
+ return_tensors="pt"
885
+ )
886
+
887
+ input_ids = enc["input_ids"].reshape(max_n_parts, max_len) # (n_parts, max_len)
888
+ attn_mask = enc["attention_mask"].reshape(max_n_parts, max_len) # (n_parts, max_len)
889
+
890
+ return input_ids, attn_mask
891
+
892
+ class LawRetrievalDataset(Dataset):
893
+ def __init__(self, all_data, using_idxes, corpus_dict, tokenizer, max_len, max_n_parts, n_negs):
894
+ super().__init__()
895
+
896
+ self.all_data = all_data
897
+ self.using_idxes = using_idxes
898
+ self.tokenizer = tokenizer
899
+ self.max_len = max_len
900
+ self.max_n_parts = max_n_parts
901
+ self.n_negs = n_negs
902
+
903
+ # ===== BUILD CORPUS =====
904
+ idx = 0
905
+ self.corpus_list = []
906
+ self.corpus_dict = {}
907
+
908
+ for doc_name, articles_dict in corpus_dict.items():
909
+ self.corpus_dict[doc_name] = {}
910
+ for article_idx, content in articles_dict.items():
911
+ self.corpus_list.append([doc_name, article_idx, content])
912
+ self.corpus_dict[doc_name][article_idx] = {
913
+ 'content': content,
914
+ 'idx': idx
915
+ }
916
+ idx += 1
917
+
918
+ def __len__(self):
919
+ return len(self.using_idxes)
920
+
921
+ # ===== ENCODE DOC =====
922
+ def _encode_contexts(self, idxes):
923
+ all_input_ids, all_attn_mask = [], []
924
+
925
+ for idx in idxes:
926
+ name, art, _ = self.corpus_list[idx]
927
+ corpus = self.corpus_dict[name][art]
928
+
929
+ if 'content_input_ids' in corpus:
930
+ content_input_ids = corpus['content_input_ids']
931
+ content_attn_mask = corpus['content_attn_mask']
932
+ else:
933
+ content = corpus['content']
934
+ content_input_ids, content_attn_mask = tokenize_to_parts(
935
+ content, self.tokenizer, self.max_len, self.max_n_parts
936
+ )
937
+ corpus['content_input_ids'] = content_input_ids
938
+ corpus['content_attn_mask'] = content_attn_mask
939
+
940
+ all_input_ids.append(content_input_ids)
941
+ all_attn_mask.append(content_attn_mask)
942
+
943
+ all_input_ids = torch.stack(all_input_ids)
944
+ all_attn_mask = torch.stack(all_attn_mask)
945
+
946
+ return all_input_ids, all_attn_mask
947
+
948
+ def __getitem__(self, idx):
949
+ ridx = self.using_idxes[idx]
950
+ data = self.all_data[ridx]
951
+
952
+ query_text = data['text']
953
+
954
+ text_input_ids, text_attn_mask = tokenize_to_parts(
955
+ query_text, self.tokenizer, self.max_len, 1
956
+ )
957
+
958
+ # ===== POS =====
959
+ gt_pos_idxes = []
960
+ hard_names = []
961
+ for law in data['relevant_law']:
962
+ name = law['doc']
963
+ art = law['art']
964
+ gt_pos_idxes.append(self.corpus_dict[name][art]['idx'])
965
+ if name not in hard_names:
966
+ hard_names.append(name)
967
+
968
+ pos_idxes = torch.tensor(gt_pos_idxes, dtype=torch.long)
969
+ pos_mask = torch.ones(len(pos_idxes))
970
+
971
+ # ===== NEG =====
972
+ hard_neg_idxes = []
973
+ for name in hard_names:
974
+ for content in self.corpus_dict[name].values():
975
+ if content['idx'] in gt_pos_idxes:
976
+ continue
977
+ hard_neg_idxes.append(content['idx'])
978
+
979
+ easy_neg_idxes = list(range(len(self.corpus_list)))
980
+ for i in gt_pos_idxes + hard_neg_idxes:
981
+ if i in easy_neg_idxes:
982
+ easy_neg_idxes.remove(i)
983
+
984
+ n_hards = min(len(hard_neg_idxes), self.n_negs // 2)
985
+ neg_idxes = random.sample(hard_neg_idxes, n_hards) + random.sample(easy_neg_idxes, self.n_negs - n_hards)
986
+ neg_idxes = torch.tensor(neg_idxes, dtype=torch.long)
987
+
988
+ return {
989
+ 'text_input_ids': text_input_ids,
990
+ 'text_attn_mask': text_attn_mask,
991
+ 'gt_pos_idxes': gt_pos_idxes,
992
+ 'pos_idxes': pos_idxes,
993
+ 'pos_mask': pos_mask,
994
+ 'neg_idxes': neg_idxes,
995
+ }
996
+
997
+ class CorpusDataset(Dataset):
998
+ def __init__(self, corpus_dict, tokenizer, max_len, max_n_parts):
999
+ super().__init__()
1000
+ self.tokenizer = tokenizer
1001
+ self.max_len = max_len
1002
+ self.max_n_parts = max_n_parts
1003
+
1004
+ idx = 0
1005
+ self.corpus_list = []
1006
+ self.corpus_dict = {}
1007
+ for doc_name, articles_dict in corpus_dict.items():
1008
+ self.corpus_dict[doc_name] = {}
1009
+ for article_idx, content in articles_dict.items():
1010
+ self.corpus_list.append([doc_name, article_idx, content])
1011
+ self.corpus_dict[doc_name][article_idx] = {'content': content, 'idx': idx}
1012
+ idx += 1
1013
+
1014
+ def __len__(self):
1015
+ return len(self.corpus_list)
1016
+
1017
+ def _encode_contexts(self, idxes):
1018
+ all_input_ids, all_attn_mask = [], []
1019
+ for idx in idxes:
1020
+ name = self.corpus_list[idx][0]
1021
+ art = self.corpus_list[idx][1]
1022
+ corpus = self.corpus_dict[name][art]
1023
+ if 'content_input_ids' in corpus and 'content_attn_mask' in corpus:
1024
+ content_input_ids = corpus['content_input_ids']
1025
+ content_attn_mask = corpus['content_attn_mask']
1026
+ else:
1027
+ content = corpus['content']
1028
+ content_input_ids, content_attn_mask = tokenize_to_parts(content, self.tokenizer, self.max_len, self.max_n_parts)
1029
+ corpus['content_input_ids'] = content_input_ids
1030
+ corpus['content_attn_mask'] = content_attn_mask
1031
+
1032
+ all_input_ids.append(content_input_ids)
1033
+ all_attn_mask.append(content_attn_mask)
1034
+
1035
+ all_input_ids = torch.stack(all_input_ids)
1036
+ all_attn_mask = torch.stack(all_attn_mask)
1037
+ return all_input_ids, all_attn_mask
1038
+
1039
+ def __getitem__(self, idx):
1040
+ input_ids, attn_mask = self._encode_contexts([idx])
1041
+
1042
+ return {
1043
+ 'input_ids': input_ids,
1044
+ 'attn_mask': attn_mask,
1045
+ }
1046
+
1047
+ def _pad_batch(tensor_list, pad_value=0):
1048
+ """
1049
+ tensor_list: list of tensors, mỗi tensor shape (Nk, max_n_parts, max_len)
1050
+ return: tensor shape (B, max_Nk, max_n_parts, max_len)
1051
+ """
1052
+ max_Nk = max(t.size(0) for t in tensor_list)
1053
+
1054
+ padded = []
1055
+ for t in tensor_list:
1056
+ Nk = t.size(0)
1057
+
1058
+ if Nk < max_Nk:
1059
+ pad_shape = (max_Nk - Nk, *t.shape[1:])
1060
+ pad_tensor = t.new_full(pad_shape, pad_value)
1061
+ t = torch.cat([t, pad_tensor], dim=0)
1062
+
1063
+ padded.append(t)
1064
+
1065
+ return torch.stack(padded) # (B, max_Nk, max_n_parts, max_len)
1066
+
1067
+ def collate_fn(batch):
1068
+ text_input_ids = torch.stack([b["text_input_ids"] for b in batch])
1069
+ text_attn_mask = torch.stack([b["text_attn_mask"] for b in batch])
1070
+ gt_pos_idxes = [b["gt_pos_idxes"] for b in batch]
1071
+ neg_idxes = torch.stack([b["neg_idxes"] for b in batch])
1072
+
1073
+ pos_idxes = [b["pos_idxes"].unsqueeze(-1).unsqueeze(-1) for b in batch]
1074
+ pos_mask = [b["pos_mask"].unsqueeze(-1).unsqueeze(-1) for b in batch]
1075
+
1076
+ # pad theo Nk
1077
+ pos_idxes = _pad_batch(pos_idxes, pad_value=0).squeeze(-1).squeeze(-1)
1078
+ pos_mask = _pad_batch(pos_mask, pad_value=0).squeeze(-1).squeeze(-1)
1079
+
1080
+ return {
1081
+ 'text_input_ids': text_input_ids,
1082
+ 'text_attn_mask': text_attn_mask,
1083
+ 'gt_pos_idxes': gt_pos_idxes,
1084
+ 'pos_idxes': pos_idxes,
1085
+ 'pos_mask': pos_mask,
1086
+ 'neg_idxes': neg_idxes,
1087
+ }
1088
+
1089
+ # %% [code]
1090
+ def encode_corpus(state_dicts, network, corpus_loader, device):
1091
+ if torch.cuda.device_count() > 1:
1092
+ network = nn.DataParallel(network)
1093
+ network.to(device)
1094
+ network.eval()
1095
+
1096
+ all_model_embs = []
1097
+ for i, state_dict in enumerate(state_dicts):
1098
+ # ===== load model =====
1099
+ if torch.cuda.device_count() > 1:
1100
+ network.module.load_state_dict(state_dict)
1101
+ else:
1102
+ network.load_state_dict(state_dict)
1103
+
1104
+ encoded_docs = []
1105
+
1106
+ with torch.no_grad():
1107
+ for batch in corpus_loader:
1108
+ input_ids = batch['input_ids'].to(device)
1109
+ attn_mask = batch['attn_mask'].to(device)
1110
+
1111
+ emb = network(input_ids, attn_mask, is_query=False) # [B, 1, D] hoặc [B, D]
1112
+
1113
+ encoded_docs.append(emb)
1114
+
1115
+ encoded_docs = torch.concat(encoded_docs, dim=0).squeeze(1) # [N, D]
1116
+ all_model_embs.append(encoded_docs)
1117
+
1118
+ # ===== ensemble =====
1119
+ # stack → [M, N, D]
1120
+ all_model_embs = torch.stack(all_model_embs, dim=0)
1121
+ final_embs = all_model_embs.mean(dim=0) # [N, D]
1122
+
1123
+ return final_embs
1124
+
1125
+ def test(state_dicts, network, test_loader, device, eval_fn, encoded_docs, bm25_scores, topks=[5, 10, 15]):
1126
+ if torch.cuda.device_count() > 1:
1127
+ network = nn.DataParallel(network)
1128
+ network.to(device)
1129
+ network.eval()
1130
+
1131
+ per_model_scores = []
1132
+ max_k = max(topks)
1133
+
1134
+ all_scores = []
1135
+ all_gt_pos_idxes = []
1136
+ with torch.no_grad():
1137
+ for batch in test_loader:
1138
+ text_input_ids = batch['text_input_ids'].to(device)
1139
+ text_attn_mask = batch['text_attn_mask'].to(device)
1140
+ gt_pos_idxes = batch['gt_pos_idxes']
1141
+ all_gt_pos_idxes.extend(gt_pos_idxes)
1142
+
1143
+ list_encoded_texts = []
1144
+
1145
+ for state_dict in state_dicts:
1146
+ # ===== load model =====
1147
+ if torch.cuda.device_count() > 1:
1148
+ network.module.load_state_dict(state_dict)
1149
+ else:
1150
+ network.load_state_dict(state_dict)
1151
+
1152
+ encoded_text = network(text_input_ids, text_attn_mask, is_query=True)
1153
+ list_encoded_texts.append(encoded_text)
1154
+
1155
+ ensemble_encoded_text = torch.stack(list_encoded_texts, dim=0).mean(dim=0)
1156
+ scores = torch.matmul(ensemble_encoded_text, encoded_docs.T) # B, M
1157
+ all_scores.append(scores)
1158
+
1159
+ all_scores = torch.concat(all_scores, dim=0) # (N, M)
1160
+
1161
+ bm25_scores = torch.tensor(bm25_scores).to(all_scores.device) # (N, M)
1162
+ bm25_scores = bm25_scores.float()
1163
+
1164
+ # min-max về [0, 1]
1165
+ bm25_scores = (
1166
+ bm25_scores - bm25_scores.min(dim=-1, keepdim=True).values
1167
+ ) / (
1168
+ bm25_scores.max(dim=-1, keepdim=True).values
1169
+ - bm25_scores.min(dim=-1, keepdim=True).values
1170
+ + 1e-8
1171
+ )
1172
+ # đổi sang [-1, 1]
1173
+ bm25_scores = bm25_scores * 2 - 1
1174
+
1175
+ all_gt_pos_idxes = list_to_tuple(all_gt_pos_idxes)
1176
+
1177
+ final_score = {}
1178
+ for weight in [0, 0.25, 0.5, 0.75, 1]:
1179
+
1180
+ # score cuối
1181
+ final_scores = all_scores + weight * bm25_scores
1182
+
1183
+ # topk lớn nhất
1184
+ topk_scores, topk_indices = torch.topk(final_scores, k=max_k)
1185
+
1186
+ pred_topk_full = [
1187
+ idx[score > 0].tolist()
1188
+ for score, idx in zip(topk_scores, topk_indices)
1189
+ ]
1190
+
1191
+ pred_topk_full = list_to_tuple(pred_topk_full)
1192
+
1193
+ final_score[weight] = {}
1194
+
1195
+ for k in topks:
1196
+ pred_topk_k = [p[:k] for p in pred_topk_full]
1197
+ final_score[weight][k] = eval_fn(pred_topk_k, all_gt_pos_idxes)
1198
+
1199
+ return final_score
1200
+
1201
+ # %% [code]
1202
+ with open(f'{train_dir}/train.json', "r", encoding="utf-8") as f:
1203
+ data_train = json.load(f)
1204
+
1205
+ with open(f'{test_dir}/test.json', "r", encoding="utf-8") as f:
1206
+ data_test = json.load(f)
1207
+
1208
+ with open(f'{test_dir}/corpus.json', "r", encoding="utf-8") as f:
1209
+ data_corpus = json.load(f)
1210
+
1211
+ print('Train:', len(data_train))
1212
+ print('Test:', len(data_test))
1213
+ print('Corpus:', len(data_corpus))
1214
+
1215
+ # %% [code]
1216
+ # trigger_types = sorted(list(set([e['label'] for d in data_train + data_test for e in d['issues']]))) # NBR : Neighbor relation
1217
+ # bio_trigger_types = ['O'] + [f'{prefix}-{trg}' for trg in trigger_types for prefix in ['B', 'I']]
1218
+ # trigger_label2id = {l: i for i, l in enumerate(bio_trigger_types)}
1219
+ # trigger_id2label = {i: l for l, i in trigger_label2id.items()}
1220
+
1221
+ # argument_types = sorted(list(set([a['role'] for d in data_train + data_test for e in d['issues'] for a in e['arguments']])))
1222
+ # bio_argument_types = ['O'] + [f'{prefix}-{arg}' for arg in argument_types for prefix in ['B', 'I']]
1223
+ # argument_label2id = {l: i for i, l in enumerate(bio_argument_types)}
1224
+ # argument_id2label = {i: l for l, i in argument_label2id.items()}
1225
+
1226
+ # label2id = {
1227
+ # 'Trg': trigger_label2id,
1228
+ # 'Arg': argument_label2id,
1229
+ # }
1230
+
1231
+ # id2label = {
1232
+ # 'Trg': trigger_id2label,
1233
+ # 'Arg': argument_id2label,
1234
+ # }
1235
+
1236
+ # %% [code]
1237
+ # zero_events_idxes = []
1238
+ # for idx, d in enumerate(data_train):
1239
+ # if len(d['issues']) == 0:
1240
+ # zero_events_idxes.append(idx)
1241
+
1242
+ # n_zero_events_samples = len(zero_events_idxes)
1243
+ # n_has_events_samples = len(data_train) - n_zero_events_samples
1244
+
1245
+ # random.seed(42)
1246
+ # k = min(int(n_has_events_samples * zero_events_rate), len(zero_events_idxes))
1247
+ # sampled_zero_events_idxes = random.sample(zero_events_idxes, k)
1248
+
1249
+ # new_data_train = []
1250
+ # for idx, d in enumerate(data_train):
1251
+ # if len(d['issues']) == 0:
1252
+ # if idx in sampled_zero_events_idxes:
1253
+ # new_data_train.append(d)
1254
+ # else:
1255
+ # new_data_train.append(d)
1256
+ # data_train = new_data_train
1257
+
1258
+ # print('Train:', len(data_train))
1259
+
1260
+ # %% [code]
1261
+ if debug_only:
1262
+ data_train = data_train[:20]
1263
+ data_test = data_test[:20]
1264
+
1265
+ print('Train:', len(data_train))
1266
+ print('Test:', len(data_test))
1267
+
1268
+ # %% [code]
1269
+ tokenizer = AutoTokenizer.from_pretrained(backbone_model_name)
1270
+
1271
+ # %% [code]
1272
+ print('Experiment name:', state_dict_save_name)
1273
+
1274
+ # %% [code]
1275
+ if not test_only:
1276
+ full_idxes = np.array(range(len(data_train)))
1277
+ training_logs, best_models, last_models = [], [], []
1278
+ start_training_time = time.time()
1279
+ for seed in SEEDS:
1280
+ kf = KFold(n_splits=nfolds, shuffle=True, random_state=seed)
1281
+ generator = torch.Generator()
1282
+ generator.manual_seed(seed)
1283
+
1284
+ corpusset = CorpusDataset(data_corpus, tokenizer, **corpus_memory_params)
1285
+ corpus_loader = DataLoader(corpusset, generator=generator, **val_loader_params)
1286
+ for fold_idx, (tr_idx, va_idx) in enumerate(kf.split(full_idxes)):
1287
+ if only_fold_idx is not None and only_fold_idx >= 0 and only_fold_idx != fold_idx:
1288
+ continue
1289
+ set_seed(seed)
1290
+
1291
+ train_idxes, val_idxes = full_idxes[tr_idx], full_idxes[va_idx]
1292
+
1293
+ trainset = LawRetrievalDataset(data_train, train_idxes, data_corpus, tokenizer, **train_memory_params)
1294
+ valset = LawRetrievalDataset(data_train, val_idxes, data_corpus, tokenizer, **val_memory_params)
1295
+
1296
+ train_loader = DataLoader(trainset, generator=generator, collate_fn=collate_fn, **train_loader_params)
1297
+ val_loader = DataLoader(valset, generator=generator, collate_fn=collate_fn, **val_loader_params)
1298
+
1299
+ my_model = EncodeModel(
1300
+ **model_params
1301
+ )
1302
+ total_params = sum(p.numel() for p in my_model.parameters())
1303
+ print(f"Total params: {total_params:,}")
1304
+
1305
+ # optimizer, scheduler = configure_optimizers(my_model, optim_params, scheduler_params)
1306
+ encoder_params = set(map(id, my_model.encoder.parameters()))
1307
+ other_params = [
1308
+ p for p in my_model.parameters()
1309
+ if id(p) not in encoder_params
1310
+ ]
1311
+ optimizer = optim.AdamW([
1312
+ {"params": my_model.encoder.parameters(), "lr": 2e-5},
1313
+ {"params": other_params}
1314
+ ], lr=5e-4)
1315
+ scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=20, eta_min=1e-6)
1316
+
1317
+ loss_fn = CustomLoss(
1318
+ **loss_func_params
1319
+ )
1320
+ eval_fn = CustomEvalFn(**eval_func_params)
1321
+ trainer_params['save_name'] = f'{state_dict_save_name}_s{seed}_f{fold_idx}'
1322
+ trainer = Trainer(**trainer_params)
1323
+
1324
+ print(f'Start Training Fold {fold_idx}...')
1325
+ training_log, best_model, last_model = trainer.fit(
1326
+ my_model, optimizer, scheduler, loss_fn, epochs, train_loader, val_loader, corpus_loader, eval_fn,
1327
+ start_epoch=1, start_training_time=start_training_time, refresh_every=2,
1328
+ )
1329
+
1330
+ training_logs.append(training_log)
1331
+ best_models.append(best_model)
1332
+ last_models.append(last_model)
1333
+
1334
+ # %% [code]
1335
+ def load_all_state_dicts(folder):
1336
+ files = []
1337
+
1338
+ for file in os.listdir(folder):
1339
+ if file.endswith(".pt") or file.endswith(".pth"):
1340
+ m = re.search(r"f(\d+)", file) # tìm f<số>
1341
+ if m:
1342
+ fold = int(m.group(1))
1343
+ files.append((fold, file))
1344
+
1345
+ # sort theo fold
1346
+ files.sort(key=lambda x: x[0])
1347
+
1348
+ state_dicts = []
1349
+ for fold, file in files:
1350
+ path = os.path.join(folder, file)
1351
+ print(f"Loading fold {fold}: {file}")
1352
+ state_dict = torch.load(path, map_location="cpu")
1353
+ state_dicts.append(state_dict)
1354
+
1355
+ return state_dicts
1356
+
1357
+ if test_only:
1358
+ snapshot_download(repo_id=repo_name, local_dir="", repo_type="model", allow_patterns=[f"{state_dict_save_name}/**"])
1359
+ get_ipython().system('rm -rf .cache .gitattributes')
1360
+
1361
+ best_models = load_all_state_dicts(f"{state_dict_save_name}/r1s")
1362
+ last_models = load_all_state_dicts(f"{state_dict_save_name}/lasts")
1363
+
1364
+ # %% [code]
1365
+ os.makedirs(f'{checkpoints_dir}/results', exist_ok=True)
1366
+ testset = LawRetrievalDataset(data_test, range(len(data_test)), data_corpus, tokenizer, **val_memory_params)
1367
+ generator = torch.Generator()
1368
+ test_loader = DataLoader(testset, generator=generator, collate_fn=collate_fn, **val_loader_params)
1369
+ eval_fn = CustomEvalFn(**eval_func_params)
1370
+ my_model = EncodeModel(
1371
+ **model_params
1372
+ )
1373
+ total_params = sum(p.numel() for p in my_model.parameters())
1374
+ print(f"Total params: {total_params:,}")
1375
+
1376
+ # %% [code]
1377
+ start_time = time.time()
1378
+ encoded_docs = encode_corpus(best_models, my_model, corpus_loader, device)
1379
+ best_score = test(best_models, my_model, test_loader, device, eval_fn, encoded_docs, bm25_scores)
1380
+
1381
+ encoded_docs = encode_corpus(last_models, my_model, corpus_loader, device)
1382
+ last_score = test(last_models, my_model, test_loader, device, eval_fn, encoded_docs, bm25_scores)
1383
+
1384
+ result_test = {"Best model": best_score, "Last model": last_score}
1385
+
1386
+ with open(f"{checkpoints_dir}/results/{state_dict_save_name}_test.json", "w", encoding="utf-8") as f:
1387
+ json.dump(result_test, f, ensure_ascii=False, indent=2)
1388
+
1389
+ print('Test:', time.time() - start_time, 's --> Done!')
1390
+
1391
+ # %% [code]
1392
+ def dict_to_df(data):
1393
+ """
1394
+ data format:
1395
+ {
1396
+ model_name: {
1397
+ weight: {
1398
+ topk: {
1399
+ metric: value
1400
+ }
1401
+ }
1402
+ }
1403
+ }
1404
+ """
1405
+
1406
+ row_tuples = []
1407
+ row_values = []
1408
+
1409
+ # ===== lấy model đầu tiên =====
1410
+ first_model = next(iter(data.values()))
1411
+
1412
+ # ===== weight keys =====
1413
+ weight_keys = list(first_model.keys())
1414
+
1415
+ # ===== topk keys =====
1416
+ first_weight = next(iter(first_model.values()))
1417
+ topk_keys = list(first_weight.keys())
1418
+
1419
+ # ===== metric keys =====
1420
+ first_topk = next(iter(first_weight.values()))
1421
+ metrics = list(first_topk.keys())
1422
+
1423
+ for weight in weight_keys:
1424
+
1425
+ for topk in topk_keys:
1426
+
1427
+ # ===== multi index row =====
1428
+ row_tuples.append((weight, topk))
1429
+
1430
+ row = {}
1431
+
1432
+ for model_name, model_data in data.items():
1433
+
1434
+ for metric in metrics:
1435
+
1436
+ row[(model_name, metric)] = (
1437
+ model_data[weight][topk][metric]
1438
+ )
1439
+
1440
+ row_values.append(row)
1441
+
1442
+ # ===== dataframe =====
1443
+ df = pd.DataFrame(row_values)
1444
+
1445
+ # ===== multi columns =====
1446
+ df.columns = pd.MultiIndex.from_tuples(
1447
+ df.columns,
1448
+ names=["model", "metric"]
1449
+ )
1450
+
1451
+ # ===== multi index =====
1452
+ df.index = pd.MultiIndex.from_tuples(
1453
+ row_tuples,
1454
+ names=["weight", "topk"]
1455
+ )
1456
+
1457
+ return df
1458
+
1459
+ result_test_df = dict_to_df(result_test)
1460
+ result_test_df.to_excel(f"{checkpoints_dir}/results/{state_dict_save_name}_test_df.xlsx")
1461
+ result_test_df
1462
+
1463
+ # %% [code]
1464
+ key = ("Best model", "recall")
1465
+
1466
+ result_test_df_best = (
1467
+ result_test_df
1468
+ .sort_values(by=key, ascending=False)
1469
+ .groupby(level="weight")
1470
+ .head(1)
1471
+ )
1472
+ result_test_df_best.to_excel(f"{checkpoints_dir}/results/{state_dict_save_name}_test_df_best.xlsx")
1473
+ result_test_df_best
1474
+
1475
+ # %% [code]
1476
+ def get_avg_best_score(logs):
1477
+ return float(np.mean([list(log.values())[-1]['best_score'] for log in logs]))
1478
+
1479
+ def get_avg_log(logs, epochs):
1480
+ avg_log = {}
1481
+
1482
+ for epoch in range(1, epochs + 1):
1483
+ val_score = 0.0
1484
+ train_loss = 0.0
1485
+ n_eval = 0
1486
+
1487
+ for idx in range(len(logs)):
1488
+ log = logs[idx].get(epoch, logs[idx].get(str(epoch)))
1489
+ if log is None:
1490
+ continue
1491
+
1492
+ val_score += log.get('val_score', 0.0)
1493
+ train_loss += log.get('train_loss', 0.0)
1494
+ n_eval += 1
1495
+
1496
+ if n_eval == 0:
1497
+ continue
1498
+
1499
+ avg_log[epoch] = {
1500
+ 'train_loss': train_loss / n_eval,
1501
+ 'val_score': val_score / n_eval if val_score != 0 else float('inf')
1502
+ }
1503
+
1504
+ return avg_log
1505
+
1506
+ def parse_label_key(label: str):
1507
+ try:
1508
+ first = float(label.split('_', 1)[0]) # số đầu: trước dấu _
1509
+ last = float(re.findall(r'_(\d+(?:\.\d+)?)$', label)[0])
1510
+ return first, last
1511
+ except:
1512
+ return (0, 0)
1513
+
1514
+ def plot_training_logs(logs_dict, save_path=None, figsize=(24, 10)):
1515
+ fig, axes = plt.subplots(1, 2, figsize=figsize)
1516
+
1517
+ # ===== Plot Train Loss =====
1518
+ for name, log in logs_dict.items():
1519
+ epochs = sorted(log.keys())
1520
+ train_loss = [log[e]['train_loss'] for e in epochs]
1521
+ axes[0].plot(epochs, train_loss, label=name)
1522
+
1523
+ axes[0].set_xlabel('Epoch')
1524
+ axes[0].set_ylabel('Train Loss')
1525
+ axes[0].set_title('Training Loss')
1526
+ axes[0].grid(True)
1527
+
1528
+ # ===== Plot Validation Score =====
1529
+ for name, log in logs_dict.items():
1530
+ epochs = sorted(log.keys())
1531
+ val_score = [log[e]['val_score'] for e in epochs]
1532
+ axes[1].plot(epochs, val_score, label=name)
1533
+
1534
+ axes[1].set_xlabel('Epoch')
1535
+ axes[1].set_ylabel('Validation Score')
1536
+ axes[1].set_title('Validation Score')
1537
+ axes[1].grid(True)
1538
+
1539
+ # ===== Shared Legend =====
1540
+ handles, labels = axes[0].get_legend_handles_labels()
1541
+ pairs = list(zip(handles, labels))
1542
+ pairs_sorted = sorted(
1543
+ pairs,
1544
+ key=lambda x: parse_label_key(x[1])
1545
+ )
1546
+ handles_sorted, labels_sorted = zip(*pairs_sorted)
1547
+
1548
+ axes[0].legend(
1549
+ handles_sorted,
1550
+ labels_sorted,
1551
+ loc='center left',
1552
+ bbox_to_anchor=(1.01, 0.5),
1553
+ borderaxespad=0.
1554
+ )
1555
+
1556
+ plt.tight_layout(rect=[0, 0, 1, 1])
1557
+
1558
+ if save_path is not None:
1559
+ os.makedirs(os.path.dirname(save_path), exist_ok=True) if os.path.dirname(save_path) else None
1560
+ plt.savefig(save_path, dpi=300, bbox_inches='tight')
1561
+
1562
+ plt.show()
1563
+
1564
+ # %% [code]
1565
+ if not test_only:
1566
+ snapshot_download(repo_id=repo_name, local_dir="", repo_type="model", allow_patterns=["**/*lr*.json"], ignore_patterns=[])
1567
+ get_ipython().system('rm -rf .cache .gitattributes')
1568
+
1569
+ # %% [code]
1570
+ if not test_only:
1571
+ experiments = {}
1572
+ for experiment in os.listdir(pretrained_dir):
1573
+ experiment_logs = []
1574
+ try:
1575
+ for seed in SEEDS:
1576
+ for fold_idx in range(nfolds):
1577
+ with open(f"{pretrained_dir}/{experiment}/logs/{experiment}_s{seed}_f{fold_idx}_logging.json", "r", encoding="utf-8") as f:
1578
+ experiment_log = json.load(f)
1579
+ experiment_logs.append(experiment_log)
1580
+ except:
1581
+ pass
1582
+ experiments[experiment] = get_avg_log(experiment_logs, 1000)
1583
+ experiments[state_dict_save_name] = get_avg_log(training_logs, 1000)
1584
+
1585
+ # %% [code]
1586
+ if not test_only:
1587
+ score = get_avg_best_score(training_logs)
1588
+ state_dict_save_name, score
1589
+
1590
+ # %% [code]
1591
+ if not test_only:
1592
+ plot_training_logs(experiments, save_path=f'{checkpoints_dir}/logs/{state_dict_save_name}_log_plot.jpg', figsize=(18, 7.5))
1593
+
11_12_13_lr_17/lasts/11_12_13_lr_17_s26092004_f0_last_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ec484758ccbb98bd4185af20d8cb19b080df3a837c407de38d03569b7a4f3407
3
+ size 544007234
11_12_13_lr_17/lasts/11_12_13_lr_17_s26092004_f1_last_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:885527f9be01fc8322a85502efea2864c60e5648a07ee381e8eeb38b6f8a1b5f
3
+ size 544007234
11_12_13_lr_17/lasts/11_12_13_lr_17_s26092004_f2_last_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:938789aef501b8e7db3c04215bab9a242204c68521fce2bee52140bc81b64370
3
+ size 544007234
11_12_13_lr_17/lasts/11_12_13_lr_17_s26092004_f3_last_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4903aec45da6ae86ccc278dcd5fb530e0f0db36a1cdfa48c09197171a5dec09f
3
+ size 544007234
11_12_13_lr_17/lasts/11_12_13_lr_17_s26092004_f4_last_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f65a71018b9e955d6613cd375bc1bd8fa27ad40af7dfef94fad1a5b1633db8a1
3
+ size 544007234
11_12_13_lr_17/logs/11_12_13_lr_17_log_plot.jpg ADDED

Git LFS Details

  • SHA256: ccbab742570bf66d4bc0ab606b856bb980f81259989853ea326e45bef6115d8b
  • Pointer size: 131 Bytes
  • Size of remote file: 541 kB
11_12_13_lr_17/logs/11_12_13_lr_17_s26092004_f0_logging.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"1": {"lr": [2e-05, 0.0005], "train_loss": 3.849350929260254, "total": 3.849350945207985, "contrastive_loss": 3.7087908588524248, "triplet_loss": 0.27320234113712377}, "2": {"lr": [1.988303923565381e-05, 0.0004969282409784868], "train_loss": 3.6270928382873535, "total": 3.6270927505748327, "contrastive_loss": 3.4903425644073995, "triplet_loss": 0.266304347826087}, "3": {"lr": [1.9535036904803962e-05, 0.0004877886008156408], "train_loss": 3.4080309867858887, "total": 3.408031042602947, "contrastive_loss": 3.2548078964386495, "triplet_loss": 0.30288461538461536}, "4": {"lr": [1.8964561979789496e-05, 0.00047280612778499774], "train_loss": 3.135387897491455, "total": 3.135388020288984, "contrastive_loss": 2.9909837397444607, "triplet_loss": 0.2842809364548495}, "5": {"lr": [1.8185661446562005e-05, 0.00045234974009654937], "train_loss": 3.102684497833252, "total": 3.1026846078725963, "contrastive_loss": 2.9599497102973453, "triplet_loss": 0.27968227424749165}, "6": {"lr": [1.7217514421272206e-05, 0.00042692314190604356], "train_loss": 2.8865349292755127, "total": 2.886535032138378, "contrastive_loss": 2.7526385967548075, "triplet_loss": 0.2637959866220736}, "7": {"lr": [1.60839598967785e-05, 0.00039715242044697206], "train_loss": 2.8706984519958496, "total": 2.870698552466555, "contrastive_loss": 2.7297577618755224, "triplet_loss": 0.27738294314381273}, "8": {"lr": [1.4812909747525698e-05, 0.00036377062968501693], "train_loss": 2.579120397567749, "total": 2.579120342548077, "contrastive_loss": 2.4513306888848243, "triplet_loss": 0.2548076923076923, "val_score": 0.8321726190476191, "best_score": 0.8321726190476191, "new_best_model": true, "recall": 0.8321726190476191, "mAP": 0.32399420233371123, "mRP": 0.3117083333333332}, "9": {"lr": [1.3435661446562005e-05, 0.0003275997400965494], "train_loss": 2.4573817253112793, "total": 2.4573817428537836, "contrastive_loss": 2.332941469938859, "triplet_loss": 0.24749163879598662, "val_score": 0.830029761904762, "best_score": 0.8321726190476191, "new_best_model": false, "recall": 0.830029761904762, "mAP": 0.3227199105568152, "mRP": 0.31034027777777773}, "10": {"lr": [1.1986127417882198e-05, 0.00028953039902753766], "train_loss": 2.2760982513427734, "total": 2.27609834702916, "contrastive_loss": 2.160639223845109, "triplet_loss": 0.23369565217391305, "val_score": 0.8321726190476191, "best_score": 0.8321726190476191, "new_best_model": true, "recall": 0.8321726190476191, "mAP": 0.3276874283509699, "mRP": 0.31656448412698407}, "11": {"lr": [1.0500000000000003e-05, 0.0002505], "train_loss": 2.2247889041900635, "total": 2.2247888061115177, "contrastive_loss": 2.11044505447847, "triplet_loss": 0.23056020066889632, "val_score": 0.8139880952380952, "best_score": 0.8321726190476191, "new_best_model": false, "recall": 0.8139880952380952, "mAP": 0.3163277409690729, "mRP": 0.30428521825396815}, "12": {"lr": [9.013872582117811e-06, 0.00021146960097246246], "train_loss": 2.0722544193267822, "total": 2.0722543977973453, "contrastive_loss": 1.9660775175062708, "triplet_loss": 0.2122700668896321, "val_score": 0.8139880952380952, "best_score": 0.8321726190476191, "new_best_model": false, "recall": 0.8139880952380952, "mAP": 0.31827680146132536, "mRP": 0.3060352182539681}, "13": {"lr": [7.564338553438001e-06, 0.00017340025990345064], "train_loss": 2.0603482723236084, "total": 2.0603482555784907, "contrastive_loss": 1.9539109041858278, "triplet_loss": 0.2121655518394649, "val_score": 0.7973214285714286, "best_score": 0.8321726190476191, "new_best_model": false, "recall": 0.7973214285714286, "mAP": 0.3080162509448222, "mRP": 0.297126984126984}, "14": {"lr": [6.1870902524743065e-06, 0.00013722937031498307], "train_loss": 1.9397445917129517, "total": 1.939744624007107, "contrastive_loss": 1.8402303740332357, "triplet_loss": 0.19742892976588627, "val_score": 0.7971130952380953, "best_score": 0.8321726190476191, "new_best_model": false, "recall": 0.7971130952380953, "mAP": 0.30994053721025444, "mRP": 0.297766369047619}, "15": {"lr": [4.916040103221507e-06, 0.00010384757955302797], "train_loss": 1.9679230451583862, "total": 1.9679230654917432, "contrastive_loss": 1.866120711616848, "triplet_loss": 0.20286371237458195, "val_score": 0.7804464285714287, "best_score": 0.8321726190476191, "new_best_model": false, "recall": 0.7804464285714287, "mAP": 0.2988514526643991, "mRP": 0.28777083333333353}, "16": {"lr": [3.7824855787278e-06, 7.40768580939564e-05], "train_loss": 1.8696411848068237, "total": 1.8696411541074414, "contrastive_loss": 1.773466690726902, "triplet_loss": 0.19199414715719063, "val_score": 0.777529761904762, "best_score": 0.8321726190476191, "new_best_model": false, "recall": 0.777529761904762, "mAP": 0.30044554811507945, "mRP": 0.2886006944444444}, "17": {"lr": [2.814338553438001e-06, 4.865025990345063e-05], "train_loss": 1.9341967105865479, "total": 1.934196752848035, "contrastive_loss": 1.8339760056307484, "triplet_loss": 0.19972826086956522, "val_score": 0.7604464285714286, "best_score": 0.8321726190476191, "new_best_model": false, "recall": 0.7604464285714286, "mAP": 0.2879113760550518, "mRP": 0.2753110119047619}, "18": {"lr": [2.0354380202105066e-06, 2.8193872215002235e-05], "train_loss": 1.8726832866668701, "total": 1.8726833177649456, "contrastive_loss": 1.775915445691367, "triplet_loss": 0.1939799331103679, "val_score": 0.7583630952380953, "best_score": 0.8321726190476191, "new_best_model": false, "recall": 0.7583630952380953, "mAP": 0.2899708530171327, "mRP": 0.2778735119047619}}
11_12_13_lr_17/logs/11_12_13_lr_17_s26092004_f1_logging.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"1": {"lr": [2e-05, 0.0005], "train_loss": 3.860725164413452, "total": 3.860725122151965, "contrastive_loss": 3.7198208710022995, "triplet_loss": 0.2752926421404682}, "2": {"lr": [1.988303923565381e-05, 0.0004969282409784868], "train_loss": 3.6681532859802246, "total": 3.6681532843854514, "contrastive_loss": 3.530774374869356, "triplet_loss": 0.26672240802675584}, "3": {"lr": [1.9535036904803962e-05, 0.0004877886008156408], "train_loss": 3.4691953659057617, "total": 3.4691954137489547, "contrastive_loss": 3.3150232627639005, "triplet_loss": 0.3030936454849498}, "4": {"lr": [1.8964561979789496e-05, 0.00047280612778499774], "train_loss": 3.212824583053589, "total": 3.2128246907007734, "contrastive_loss": 3.067079269766409, "triplet_loss": 0.2861622073578595}, "5": {"lr": [1.8185661446562005e-05, 0.00045234974009654937], "train_loss": 3.2040324211120605, "total": 3.2040323621054556, "contrastive_loss": 3.056296664336852, "triplet_loss": 0.28971571906354515}, "6": {"lr": [1.7217514421272206e-05, 0.00042692314190604356], "train_loss": 2.9750967025756836, "total": 2.975096635595213, "contrastive_loss": 2.8368605801891724, "triplet_loss": 0.2709030100334448}, "7": {"lr": [1.60839598967785e-05, 0.00039715242044697206], "train_loss": 2.9426071643829346, "total": 2.9426071524221364, "contrastive_loss": 2.799535438767245, "triplet_loss": 0.28135451505016723}, "8": {"lr": [1.4812909747525698e-05, 0.00036377062968501693], "train_loss": 2.682934284210205, "total": 2.682934407007734, "contrastive_loss": 2.5520023613869145, "triplet_loss": 0.2594063545150502, "val_score": 0.8349198717948718, "best_score": 0.8349198717948718, "new_best_model": true, "recall": 0.8349198717948718, "mAP": 0.3240826978191562, "mRP": 0.31000934829059834}, "9": {"lr": [1.3435661446562005e-05, 0.0003275997400965494], "train_loss": 2.564674139022827, "total": 2.5646741988268187, "contrastive_loss": 2.436463014736622, "triplet_loss": 0.2543896321070234, "val_score": 0.8345032051282052, "best_score": 0.8349198717948718, "new_best_model": false, "recall": 0.8345032051282052, "mAP": 0.32246053654100537, "mRP": 0.3050430021367523}, "10": {"lr": [1.1986127417882198e-05, 0.00028953039902753766], "train_loss": 2.3795409202575684, "total": 2.3795408931464257, "contrastive_loss": 2.2601263244016514, "triplet_loss": 0.2408026755852843, "val_score": 0.8362820512820512, "best_score": 0.8362820512820512, "new_best_model": true, "recall": 0.8362820512820512, "mAP": 0.32689650827567507, "mRP": 0.30914369658119667}, "11": {"lr": [1.0500000000000003e-05, 0.0002505], "train_loss": 2.3244407176971436, "total": 2.324440844481605, "contrastive_loss": 2.205558445142663, "triplet_loss": 0.23933946488294314, "val_score": 0.8185737179487179, "best_score": 0.8362820512820512, "new_best_model": false, "recall": 0.8185737179487179, "mAP": 0.31795989498541577, "mRP": 0.30211591880341887}, "12": {"lr": [9.013872582117811e-06, 0.00021146960097246246], "train_loss": 2.158068895339966, "total": 2.158069010961016, "contrastive_loss": 2.0481330590901963, "triplet_loss": 0.22031772575250835, "val_score": 0.8200320512820513, "best_score": 0.8362820512820512, "new_best_model": false, "recall": 0.8200320512820513, "mAP": 0.32182467588353003, "mRP": 0.30531036324786326}, "13": {"lr": [7.564338553438001e-06, 0.00017340025990345064], "train_loss": 2.149510145187378, "total": 2.1495102081809154, "contrastive_loss": 2.0386587289663463, "triplet_loss": 0.2226170568561873, "val_score": 0.8012820512820513, "best_score": 0.8362820512820512, "new_best_model": false, "recall": 0.8012820512820513, "mAP": 0.3119528853573125, "mRP": 0.2956888354700855}, "14": {"lr": [6.1870902524743065e-06, 0.00013722937031498307], "train_loss": 2.021688938140869, "total": 2.0216889142192724, "contrastive_loss": 1.9180859211695234, "triplet_loss": 0.20558110367892976, "val_score": 0.7989903846153846, "best_score": 0.8362820512820512, "new_best_model": false, "recall": 0.7989903846153846, "mAP": 0.3150698477352125, "mRP": 0.29909161324786343}, "15": {"lr": [4.916040103221507e-06, 0.00010384757955302797], "train_loss": 2.0624663829803467, "total": 2.062466318392036, "contrastive_loss": 1.9556607147522993, "triplet_loss": 0.21362876254180602, "val_score": 0.7713942307692307, "best_score": 0.8362820512820512, "new_best_model": false, "recall": 0.7713942307692307, "mAP": 0.3039083502916837, "mRP": 0.2907532051282051}, "16": {"lr": [3.7824855787278e-06, 7.40768580939564e-05], "train_loss": 1.957850456237793, "total": 1.957850427531877, "contrastive_loss": 1.8569625803459449, "triplet_loss": 0.20035535117056857, "val_score": 0.774727564102564, "best_score": 0.8362820512820512, "new_best_model": false, "recall": 0.774727564102564, "mAP": 0.30521715040360875, "mRP": 0.2920552884615385}, "17": {"lr": [2.814338553438001e-06, 4.865025990345063e-05], "train_loss": 2.0349791049957275, "total": 2.0349790643290135, "contrastive_loss": 1.9296113591529056, "triplet_loss": 0.20944816053511706, "val_score": 0.7548237179487179, "best_score": 0.8362820512820512, "new_best_model": false, "recall": 0.7548237179487179, "mAP": 0.2929323419057794, "mRP": 0.2787393162393163}, "18": {"lr": [2.0354380202105066e-06, 2.8193872215002235e-05], "train_loss": 1.9656423330307007, "total": 1.9656423103051839, "contrastive_loss": 1.8640391882446696, "triplet_loss": 0.20171404682274247, "val_score": 0.7512820512820513, "best_score": 0.8362820512820512, "new_best_model": false, "recall": 0.7512820512820513, "mAP": 0.2927700959630647, "mRP": 0.2797809829059828}}
11_12_13_lr_17/logs/11_12_13_lr_17_s26092004_f2_logging.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"1": {"lr": [2e-05, 0.0005], "train_loss": 3.8641021251678467, "total": 3.8641022647104935, "contrastive_loss": 3.723213935775502, "triplet_loss": 0.27487458193979936}, "2": {"lr": [1.988303923565381e-05, 0.0004969282409784868], "train_loss": 3.668407917022705, "total": 3.668408039820234, "contrastive_loss": 3.5310556673285953, "triplet_loss": 0.26734949832775917}, "3": {"lr": [1.9535036904803962e-05, 0.0004877886008156408], "train_loss": 3.4840831756591797, "total": 3.484083092730978, "contrastive_loss": 3.330072409333194, "triplet_loss": 0.3030936454849498}, "4": {"lr": [1.8964561979789496e-05, 0.00047280612778499774], "train_loss": 3.2300777435302734, "total": 3.23007783921666, "contrastive_loss": 3.084018056607964, "triplet_loss": 0.28825250836120403}, "5": {"lr": [1.8185661446562005e-05, 0.00045234974009654937], "train_loss": 3.186211347579956, "total": 3.1862113212662, "contrastive_loss": 3.0409927623327757, "triplet_loss": 0.2842809364548495}, "6": {"lr": [1.7217514421272206e-05, 0.00042692314190604356], "train_loss": 2.9956812858581543, "total": 2.99568120133518, "contrastive_loss": 2.8581351085650084, "triplet_loss": 0.2692307692307692}, "7": {"lr": [1.60839598967785e-05, 0.00039715242044697206], "train_loss": 2.9812674522399902, "total": 2.981267514436141, "contrastive_loss": 2.837190864078177, "triplet_loss": 0.282190635451505}, "8": {"lr": [1.4812909747525698e-05, 0.00036377062968501693], "train_loss": 2.7061684131622314, "total": 2.706168388443248, "contrastive_loss": 2.5743163245976173, "triplet_loss": 0.25961538461538464, "val_score": 0.8394871794871794, "best_score": 0.8394871794871794, "new_best_model": true, "recall": 0.8394871794871794, "mAP": 0.3159504038207164, "mRP": 0.3011132478632479}, "9": {"lr": [1.3435661446562005e-05, 0.0003275997400965494], "train_loss": 2.581252098083496, "total": 2.581252082135765, "contrastive_loss": 2.452596300820443, "triplet_loss": 0.25585284280936454, "val_score": 0.8374038461538461, "best_score": 0.8394871794871794, "new_best_model": false, "recall": 0.8374038461538461, "mAP": 0.31595295467456924, "mRP": 0.30317174145299153}, "10": {"lr": [1.1986127417882198e-05, 0.00028953039902753766], "train_loss": 2.3935935497283936, "total": 2.393593472381898, "contrastive_loss": 2.273653266421927, "triplet_loss": 0.24101170568561872, "val_score": 0.8419871794871795, "best_score": 0.8419871794871795, "new_best_model": true, "recall": 0.8419871794871795, "mAP": 0.3222575051299008, "mRP": 0.3078194444444446}, "11": {"lr": [1.0500000000000003e-05, 0.0002505], "train_loss": 2.3397023677825928, "total": 2.339702287246551, "contrastive_loss": 2.2210040140311453, "triplet_loss": 0.2387123745819398, "val_score": 0.8228205128205128, "best_score": 0.8419871794871795, "new_best_model": false, "recall": 0.8228205128205128, "mAP": 0.3118896490469409, "mRP": 0.29764022435897447}, "12": {"lr": [9.013872582117811e-06, 0.00021146960097246246], "train_loss": 2.1804616451263428, "total": 2.1804617687212584, "contrastive_loss": 2.069898930680393, "triplet_loss": 0.2217809364548495, "val_score": 0.8286538461538462, "best_score": 0.8419871794871795, "new_best_model": false, "recall": 0.8286538461538462, "mAP": 0.31701540507139453, "mRP": 0.302280982905983}, "13": {"lr": [7.564338553438001e-06, 0.00017340025990345064], "train_loss": 2.1661744117736816, "total": 2.1661744388848243, "contrastive_loss": 2.0551480194397995, "triplet_loss": 0.2226170568561873, "val_score": 0.8004326923076923, "best_score": 0.8419871794871795, "new_best_model": false, "recall": 0.8004326923076923, "mAP": 0.30549148966388545, "mRP": 0.2918141025641025}, "14": {"lr": [6.1870902524743065e-06, 0.00013722937031498307], "train_loss": 2.0381269454956055, "total": 2.038126967822429, "contrastive_loss": 1.9339911929739757, "triplet_loss": 0.20819397993311037, "val_score": 0.8030288461538462, "best_score": 0.8419871794871795, "new_best_model": false, "recall": 0.8030288461538462, "mAP": 0.31110761970475515, "mRP": 0.2976455662393164}, "15": {"lr": [4.916040103221507e-06, 0.00010384757955302797], "train_loss": 2.075420618057251, "total": 2.075420673076923, "contrastive_loss": 1.9684501316236414, "triplet_loss": 0.21331521739130435, "val_score": 0.7778365384615384, "best_score": 0.8419871794871795, "new_best_model": false, "recall": 0.7778365384615384, "mAP": 0.2960950131851172, "mRP": 0.28284722222222214}, "16": {"lr": [3.7824855787278e-06, 7.40768580939564e-05], "train_loss": 1.9671577215194702, "total": 1.9671577785326086, "contrastive_loss": 1.8663962884092808, "triplet_loss": 0.20004180602006688, "val_score": 0.7822115384615385, "best_score": 0.8419871794871795, "new_best_model": false, "recall": 0.7822115384615385, "mAP": 0.299882612921415, "mRP": 0.28617708333333347}, "17": {"lr": [2.814338553438001e-06, 4.865025990345063e-05], "train_loss": 2.042740821838379, "total": 2.0427407357206313, "contrastive_loss": 1.9371276651337792, "triplet_loss": 0.21206103678929766, "val_score": 0.7542948717948719, "best_score": 0.8419871794871795, "new_best_model": false, "recall": 0.7542948717948719, "mAP": 0.2851599067502712, "mRP": 0.2716145833333334}, "18": {"lr": [2.0354380202105066e-06, 2.8193872215002235e-05], "train_loss": 1.9720823764801025, "total": 1.972082437878867, "contrastive_loss": 1.8706252694528638, "triplet_loss": 0.2014005016722408, "val_score": 0.7561698717948718, "best_score": 0.8419871794871795, "new_best_model": false, "recall": 0.7561698717948718, "mAP": 0.28773541687864584, "mRP": 0.27583680555555545}}
11_12_13_lr_17/logs/11_12_13_lr_17_s26092004_f3_logging.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"1": {"lr": [2e-05, 0.0005], "train_loss": 3.875497341156006, "total": 3.875497263012124, "contrastive_loss": 3.7347408026755855, "triplet_loss": 0.27508361204013376}, "2": {"lr": [1.988303923565381e-05, 0.0004969282409784868], "train_loss": 3.6717770099639893, "total": 3.6717770171404682, "contrastive_loss": 3.5345597793426005, "triplet_loss": 0.26755852842809363}, "3": {"lr": [1.9535036904803962e-05, 0.0004877886008156408], "train_loss": 3.4881162643432617, "total": 3.4881163121864547, "contrastive_loss": 3.3336840983617266, "triplet_loss": 0.3039297658862876}, "4": {"lr": [1.8964561979789496e-05, 0.00047280612778499774], "train_loss": 3.242488384246826, "total": 3.2424883890311453, "contrastive_loss": 3.0960501476275084, "triplet_loss": 0.28887959866220736}, "5": {"lr": [1.8185661446562005e-05, 0.00045234974009654937], "train_loss": 3.2089149951934814, "total": 3.208914970474498, "contrastive_loss": 3.0625361311794523, "triplet_loss": 0.2861622073578595}, "6": {"lr": [1.7217514421272206e-05, 0.00042692314190604356], "train_loss": 3.022059679031372, "total": 3.0220598201687916, "contrastive_loss": 2.8833042514762752, "triplet_loss": 0.2713210702341137}, "7": {"lr": [1.60839598967785e-05, 0.00039715242044697206], "train_loss": 3.005990505218506, "total": 3.005990427074624, "contrastive_loss": 2.86139997909699, "triplet_loss": 0.28448996655518394}, "8": {"lr": [1.4812909747525698e-05, 0.00036377062968501693], "train_loss": 2.735560655593872, "total": 2.7355605926003346, "contrastive_loss": 2.6027446223740593, "triplet_loss": 0.262123745819398, "val_score": 0.8403205128205128, "best_score": 0.8403205128205128, "new_best_model": true, "recall": 0.8403205128205128, "mAP": 0.3177980988629426, "mRP": 0.30497569444444445}, "9": {"lr": [1.3435661446562005e-05, 0.0003275997400965494], "train_loss": 2.6214733123779297, "total": 2.621473229449728, "contrastive_loss": 2.491391797528219, "triplet_loss": 0.25794314381270905, "val_score": 0.8381410256410255, "best_score": 0.8403205128205128, "new_best_model": false, "recall": 0.8381410256410255, "mAP": 0.31950706675654594, "mRP": 0.3073985042735044}, "10": {"lr": [1.1986127417882198e-05, 0.00028953039902753766], "train_loss": 2.434934139251709, "total": 2.434934277996969, "contrastive_loss": 2.313398992736204, "triplet_loss": 0.24519230769230768, "val_score": 0.8443910256410256, "best_score": 0.8443910256410256, "new_best_model": true, "recall": 0.8443910256410256, "mAP": 0.32661201509717136, "mRP": 0.31245005341880355}, "11": {"lr": [1.0500000000000003e-05, 0.0002505], "train_loss": 2.383178234100342, "total": 2.3831783026755855, "contrastive_loss": 2.2625046541858276, "triplet_loss": 0.2418478260869565, "val_score": 0.8224198717948719, "best_score": 0.8443910256410256, "new_best_model": false, "recall": 0.8224198717948719, "mAP": 0.3184463779083572, "mRP": 0.30494951923076935}, "12": {"lr": [9.013872582117811e-06, 0.00021146960097246246], "train_loss": 2.215616464614868, "total": 2.215616589804557, "contrastive_loss": 2.1034852094873537, "triplet_loss": 0.225752508361204, "val_score": 0.8240865384615385, "best_score": 0.8443910256410256, "new_best_model": false, "recall": 0.8240865384615385, "mAP": 0.32351596130528404, "mRP": 0.3094775641025641}, "13": {"lr": [7.564338553438001e-06, 0.00017340025990345064], "train_loss": 2.2090399265289307, "total": 2.2090398986204014, "contrastive_loss": 2.095944407791597, "triplet_loss": 0.22721571906354515, "val_score": 0.8050160256410256, "best_score": 0.8443910256410256, "new_best_model": false, "recall": 0.8050160256410256, "mAP": 0.31032289589268736, "mRP": 0.2953974358974359}, "14": {"lr": [6.1870902524743065e-06, 0.00013722937031498307], "train_loss": 2.071117877960205, "total": 2.0711177966267766, "contrastive_loss": 1.9657551947246028, "triplet_loss": 0.20997073578595318, "val_score": 0.8078365384615385, "best_score": 0.8443910256410256, "new_best_model": false, "recall": 0.8078365384615385, "mAP": 0.31303145021452317, "mRP": 0.2965435363247863}, "15": {"lr": [4.916040103221507e-06, 0.00010384757955302797], "train_loss": 2.105041742324829, "total": 2.1050417080372075, "contrastive_loss": 1.9968508717208402, "triplet_loss": 0.21676421404682275, "val_score": 0.7866826923076923, "best_score": 0.8443910256410256, "new_best_model": false, "recall": 0.7866826923076923, "mAP": 0.3014011297440984, "mRP": 0.28593936965811956}, "16": {"lr": [3.7824855787278e-06, 7.40768580939564e-05], "train_loss": 2.0002076625823975, "total": 2.0002076011836327, "contrastive_loss": 1.897946360916597, "triplet_loss": 0.20286371237458195, "val_score": 0.7877243589743589, "best_score": 0.8443910256410256, "new_best_model": false, "recall": 0.7877243589743589, "mAP": 0.30329969061609685, "mRP": 0.28867654914529906}, "17": {"lr": [2.814338553438001e-06, 4.865025990345063e-05], "train_loss": 2.0700764656066895, "total": 2.0700765246132944, "contrastive_loss": 1.9635234309678093, "triplet_loss": 0.21352424749163879, "val_score": 0.7631410256410256, "best_score": 0.8443910256410256, "new_best_model": false, "recall": 0.7631410256410256, "mAP": 0.28980782214506173, "mRP": 0.2753709935897435}, "18": {"lr": [2.0354380202105066e-06, 2.8193872215002235e-05], "train_loss": 1.9971362352371216, "total": 1.9971362467992266, "contrastive_loss": 1.8945594200721154, "triplet_loss": 0.20390886287625418, "val_score": 0.7589743589743589, "best_score": 0.8443910256410256, "new_best_model": false, "recall": 0.7589743589743589, "mAP": 0.29014007438356393, "mRP": 0.2742772435897434}}
11_12_13_lr_17/logs/11_12_13_lr_17_s26092004_f4_logging.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"1": {"lr": [2e-05, 0.0005], "train_loss": 3.851969003677368, "total": 3.851969128867057, "contrastive_loss": 3.711077942098662, "triplet_loss": 0.27424749163879597}, "2": {"lr": [1.988303923565381e-05, 0.0004969282409784868], "train_loss": 3.640805721282959, "total": 3.640805860028219, "contrastive_loss": 3.503629448421823, "triplet_loss": 0.26714046822742477}, "3": {"lr": [1.9535036904803962e-05, 0.0004877886008156408], "train_loss": 3.4500555992126465, "total": 3.4500556869251673, "contrastive_loss": 3.2963773287259617, "triplet_loss": 0.3030936454849498}, "4": {"lr": [1.8964561979789496e-05, 0.00047280612778499774], "train_loss": 3.1876673698425293, "total": 3.1876673873850336, "contrastive_loss": 3.0420881290499584, "triplet_loss": 0.28532608695652173}, "5": {"lr": [1.8185661446562005e-05, 0.00045234974009654937], "train_loss": 3.18599796295166, "total": 3.1859980044157608, "contrastive_loss": 3.0406712560749374, "triplet_loss": 0.28365384615384615}, "6": {"lr": [1.7217514421272206e-05, 0.00042692314190604356], "train_loss": 2.9865071773529053, "total": 2.986507147849603, "contrastive_loss": 2.8489696285796406, "triplet_loss": 0.2692307692307692}, "7": {"lr": [1.60839598967785e-05, 0.00039715242044697206], "train_loss": 2.9650192260742188, "total": 2.9650193026233276, "contrastive_loss": 2.821347443953804, "triplet_loss": 0.28135451505016723}, "8": {"lr": [1.4812909747525698e-05, 0.00036377062968501693], "train_loss": 2.7059366703033447, "total": 2.705936699806647, "contrastive_loss": 2.5739331707906565, "triplet_loss": 0.26045150501672243, "val_score": 0.8276442307692308, "best_score": 0.8276442307692308, "new_best_model": true, "recall": 0.8276442307692308, "mAP": 0.31551935424721883, "mRP": 0.3047799145299148}, "9": {"lr": [1.3435661446562005e-05, 0.0003275997400965494], "train_loss": 2.595609188079834, "total": 2.5956092247596154, "contrastive_loss": 2.4664006568117682, "triplet_loss": 0.25668896321070234, "val_score": 0.8261858974358974, "best_score": 0.8276442307692308, "new_best_model": false, "recall": 0.8261858974358974, "mAP": 0.3137598860822817, "mRP": 0.3043637820512822}, "10": {"lr": [1.1986127417882198e-05, 0.00028953039902753766], "train_loss": 2.4035379886627197, "total": 2.4035379161005435, "contrastive_loss": 2.2831286172005645, "triplet_loss": 0.24289297658862877, "val_score": 0.8341025641025641, "best_score": 0.8341025641025641, "new_best_model": true, "recall": 0.8341025641025641, "mAP": 0.31814129485483644, "mRP": 0.30650267094017103}, "11": {"lr": [1.0500000000000003e-05, 0.0002505], "train_loss": 2.353267192840576, "total": 2.3532671976248953, "contrastive_loss": 2.233728925519962, "triplet_loss": 0.2418478260869565, "val_score": 0.8159775641025641, "best_score": 0.8341025641025641, "new_best_model": false, "recall": 0.8159775641025641, "mAP": 0.3084219487688237, "mRP": 0.29757905982905997}, "12": {"lr": [9.013872582117811e-06, 0.00021146960097246246], "train_loss": 2.196225881576538, "total": 2.196225781903219, "contrastive_loss": 2.0846955672554346, "triplet_loss": 0.2234531772575251, "val_score": 0.8196153846153846, "best_score": 0.8341025641025641, "new_best_model": false, "recall": 0.8196153846153846, "mAP": 0.31561128557013973, "mRP": 0.3008741987179487}, "13": {"lr": [7.564338553438001e-06, 0.00017340025990345064], "train_loss": 2.1827356815338135, "total": 2.1827355834552677, "contrastive_loss": 2.070810375404996, "triplet_loss": 0.22596153846153846, "val_score": 0.7988942307692307, "best_score": 0.8341025641025641, "new_best_model": false, "recall": 0.7988942307692307, "mAP": 0.3017346372184914, "mRP": 0.29122836538461544}, "14": {"lr": [6.1870902524743065e-06, 0.00013722937031498307], "train_loss": 2.04959774017334, "total": 2.0495976987092392, "contrastive_loss": 1.9451228623406145, "triplet_loss": 0.2091346153846154, "val_score": 0.8045192307692307, "best_score": 0.8341025641025641, "new_best_model": false, "recall": 0.8045192307692307, "mAP": 0.3062614875864873, "mRP": 0.29303044871794875}, "15": {"lr": [4.916040103221507e-06, 0.00010384757955302797], "train_loss": 2.0831048488616943, "total": 2.083104774704745, "contrastive_loss": 1.9759256114130435, "triplet_loss": 0.2148829431438127, "val_score": 0.7813942307692308, "best_score": 0.8341025641025641, "new_best_model": false, "recall": 0.7813942307692308, "mAP": 0.2919516331951227, "mRP": 0.2804193376068376}, "16": {"lr": [3.7824855787278e-06, 7.40768580939564e-05], "train_loss": 1.9813275337219238, "total": 1.9813275289376044, "contrastive_loss": 1.8798632159280937, "triplet_loss": 0.20192307692307693, "val_score": 0.7799358974358974, "best_score": 0.8341025641025641, "new_best_model": false, "recall": 0.7799358974358974, "mAP": 0.2952255528422196, "mRP": 0.28285336538461536}, "17": {"lr": [2.814338553438001e-06, 4.865025990345063e-05], "train_loss": 2.056546211242676, "total": 2.0565461123667435, "contrastive_loss": 1.950353309860995, "triplet_loss": 0.21195652173913043, "val_score": 0.7576602564102565, "best_score": 0.8341025641025641, "new_best_model": false, "recall": 0.7576602564102565, "mAP": 0.2823129175993759, "mRP": 0.27259561965811974}, "18": {"lr": [2.0354380202105066e-06, 2.8193872215002235e-05], "train_loss": 1.9893100261688232, "total": 1.9893100700250836, "contrastive_loss": 1.8868479648960075, "triplet_loss": 0.20464046822742474, "val_score": 0.7579807692307693, "best_score": 0.8341025641025641, "new_best_model": false, "recall": 0.7579807692307693, "mAP": 0.2839630115062406, "mRP": 0.2736477029914531}}
11_12_13_lr_17/r1s/11_12_13_lr_17_s26092004_f0_r1_vs0.83217_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d08d0e413bbc0a5b6fc1b17c2eacdf18cb9888728858c713443f0b5c39dd3c39
3
+ size 544008938
11_12_13_lr_17/r1s/11_12_13_lr_17_s26092004_f1_r1_vs0.83628_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:669e5bc066647fcbe01cde1fc0f4e238eebfc7144825b5dd700edebfd078789e
3
+ size 544008938
11_12_13_lr_17/r1s/11_12_13_lr_17_s26092004_f2_r1_vs0.84199_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e7da7b0667f4cc5e86af4c9586f0c26ccba9136d5b04a5d3856b4ceccb046e8
3
+ size 544008938
11_12_13_lr_17/r1s/11_12_13_lr_17_s26092004_f3_r1_vs0.84439_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:197756e86c7d9b8ab126c812d689ebac7752b7478b7b46fa0c3e14a79890c359
3
+ size 544008938
11_12_13_lr_17/r1s/11_12_13_lr_17_s26092004_f4_r1_vs0.83410_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:11e475b8653192cd7b806bf6330a83a3bc1dea7e1ccfaf9ff0dc7506467fadc8
3
+ size 544008938
11_12_13_lr_17/results/11_12_13_lr_17_test.json ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "Best model": {
3
+ "0": {
4
+ "5": {
5
+ "recall": 0.7420933734939759,
6
+ "mAP": 0.3063965235943786,
7
+ "mRP": 0.31039784136546333
8
+ },
9
+ "10": {
10
+ "recall": 0.829066265060241,
11
+ "mAP": 0.32095892996589587,
12
+ "mRP": 0.31039784136546333
13
+ },
14
+ "15": {
15
+ "recall": 0.8708584337349398,
16
+ "mAP": 0.32718328062360497,
17
+ "mRP": 0.31039784136546333
18
+ }
19
+ },
20
+ "0.25": {
21
+ "5": {
22
+ "recall": 0.7948042168674698,
23
+ "mAP": 0.3253631191432417,
24
+ "mRP": 0.3285642570281146
25
+ },
26
+ "10": {
27
+ "recall": 0.8708584337349398,
28
+ "mAP": 0.341724170989515,
29
+ "mRP": 0.3285642570281146
30
+ },
31
+ "15": {
32
+ "recall": 0.9002259036144579,
33
+ "mAP": 0.34808647386819574,
34
+ "mRP": 0.3285642570281146
35
+ }
36
+ },
37
+ "0.5": {
38
+ "5": {
39
+ "recall": 0.7654367469879518,
40
+ "mAP": 0.30770310408300017,
41
+ "mRP": 0.312305471887552
42
+ },
43
+ "10": {
44
+ "recall": 0.8411144578313253,
45
+ "mAP": 0.3227786269084286,
46
+ "mRP": 0.312305471887552
47
+ },
48
+ "15": {
49
+ "recall": 0.8765060240963856,
50
+ "mAP": 0.3285299822089177,
51
+ "mRP": 0.312305471887552
52
+ }
53
+ },
54
+ "0.75": {
55
+ "5": {
56
+ "recall": 0.7473644578313253,
57
+ "mAP": 0.2939539407630535,
58
+ "mRP": 0.2997615461847405
59
+ },
60
+ "10": {
61
+ "recall": 0.827183734939759,
62
+ "mAP": 0.3087747418244413,
63
+ "mRP": 0.2997615461847405
64
+ },
65
+ "15": {
66
+ "recall": 0.8625753012048193,
67
+ "mAP": 0.31438866103775803,
68
+ "mRP": 0.2997615461847405
69
+ }
70
+ },
71
+ "1": {
72
+ "5": {
73
+ "recall": 0.7379518072289156,
74
+ "mAP": 0.28719157881526197,
75
+ "mRP": 0.2915097891566277
76
+ },
77
+ "10": {
78
+ "recall": 0.8181475903614458,
79
+ "mAP": 0.3014128488158991,
80
+ "mRP": 0.2915097891566277
81
+ },
82
+ "15": {
83
+ "recall": 0.853539156626506,
84
+ "mAP": 0.3070904997919313,
85
+ "mRP": 0.2915097891566277
86
+ }
87
+ }
88
+ },
89
+ "Last model": {
90
+ "0": {
91
+ "5": {
92
+ "recall": 0.704066265060241,
93
+ "mAP": 0.28999027359437884,
94
+ "mRP": 0.2899096385542182
95
+ },
96
+ "10": {
97
+ "recall": 0.7921686746987951,
98
+ "mAP": 0.30397970353636844,
99
+ "mRP": 0.2899096385542182
100
+ },
101
+ "15": {
102
+ "recall": 0.829066265060241,
103
+ "mAP": 0.3085009147339727,
104
+ "mRP": 0.2899096385542182
105
+ }
106
+ },
107
+ "0.25": {
108
+ "5": {
109
+ "recall": 0.7891566265060241,
110
+ "mAP": 0.32182270749665487,
111
+ "mRP": 0.32599774096385736
112
+ },
113
+ "10": {
114
+ "recall": 0.8610692771084337,
115
+ "mAP": 0.33729405967122533,
116
+ "mRP": 0.32599774096385736
117
+ },
118
+ "15": {
119
+ "recall": 0.8953313253012049,
120
+ "mAP": 0.34405000567886546,
121
+ "mRP": 0.32599774096385736
122
+ }
123
+ },
124
+ "0.5": {
125
+ "5": {
126
+ "recall": 0.7579066265060241,
127
+ "mAP": 0.30209515143909127,
128
+ "mRP": 0.3060805722891582
129
+ },
130
+ "10": {
131
+ "recall": 0.8324548192771084,
132
+ "mAP": 0.3166018986660941,
133
+ "mRP": 0.3060805722891582
134
+ },
135
+ "15": {
136
+ "recall": 0.8648343373493976,
137
+ "mAP": 0.32223763195054717,
138
+ "mRP": 0.3060805722891582
139
+ }
140
+ },
141
+ "0.75": {
142
+ "5": {
143
+ "recall": 0.7409638554216867,
144
+ "mAP": 0.2905525225903625,
145
+ "mRP": 0.2963541666666681
146
+ },
147
+ "10": {
148
+ "recall": 0.8207831325301205,
149
+ "mAP": 0.3051159424403973,
150
+ "mRP": 0.2963541666666681
151
+ },
152
+ "15": {
153
+ "recall": 0.8550451807228916,
154
+ "mAP": 0.3104866205407441,
155
+ "mRP": 0.2963541666666681
156
+ }
157
+ },
158
+ "1": {
159
+ "5": {
160
+ "recall": 0.7243975903614458,
161
+ "mAP": 0.28203177292503423,
162
+ "mRP": 0.2882906626506035
163
+ },
164
+ "10": {
165
+ "recall": 0.8132530120481928,
166
+ "mAP": 0.2967050219728128,
167
+ "mRP": 0.2882906626506035
168
+ },
169
+ "15": {
170
+ "recall": 0.8460090361445783,
171
+ "mAP": 0.3021089467169105,
172
+ "mRP": 0.2882906626506035
173
+ }
174
+ }
175
+ }
176
+ }
11_12_13_lr_17/results/11_12_13_lr_17_test_df.xlsx ADDED
Binary file (6.25 kB). View file
 
11_12_13_lr_17/results/11_12_13_lr_17_test_df_best.xlsx ADDED
Binary file (5.55 kB). View file