SS3M commited on
Commit
5870c48
·
verified ·
1 Parent(s): 21bba08

Upload 10_lr_stronger_proj_residual_13's state dict

Browse files
Files changed (21) hide show
  1. .gitattributes +1 -0
  2. 10_lr_stronger_proj_residual_13/10_lr_stronger_proj_residual_13.py +1580 -0
  3. 10_lr_stronger_proj_residual_13/lasts/10_lr_stronger_proj_residual_13_s26092004_f0_last_ema.pth +3 -0
  4. 10_lr_stronger_proj_residual_13/lasts/10_lr_stronger_proj_residual_13_s26092004_f1_last_ema.pth +3 -0
  5. 10_lr_stronger_proj_residual_13/lasts/10_lr_stronger_proj_residual_13_s26092004_f2_last_ema.pth +3 -0
  6. 10_lr_stronger_proj_residual_13/lasts/10_lr_stronger_proj_residual_13_s26092004_f3_last_ema.pth +3 -0
  7. 10_lr_stronger_proj_residual_13/lasts/10_lr_stronger_proj_residual_13_s26092004_f4_last_ema.pth +3 -0
  8. 10_lr_stronger_proj_residual_13/logs/10_lr_stronger_proj_residual_13_log_plot.jpg +3 -0
  9. 10_lr_stronger_proj_residual_13/logs/10_lr_stronger_proj_residual_13_s26092004_f0_logging.json +1 -0
  10. 10_lr_stronger_proj_residual_13/logs/10_lr_stronger_proj_residual_13_s26092004_f1_logging.json +1 -0
  11. 10_lr_stronger_proj_residual_13/logs/10_lr_stronger_proj_residual_13_s26092004_f2_logging.json +1 -0
  12. 10_lr_stronger_proj_residual_13/logs/10_lr_stronger_proj_residual_13_s26092004_f3_logging.json +1 -0
  13. 10_lr_stronger_proj_residual_13/logs/10_lr_stronger_proj_residual_13_s26092004_f4_logging.json +1 -0
  14. 10_lr_stronger_proj_residual_13/r1s/10_lr_stronger_proj_residual_13_s26092004_f0_r1_vs0.82357_ema.pth +3 -0
  15. 10_lr_stronger_proj_residual_13/r1s/10_lr_stronger_proj_residual_13_s26092004_f1_r1_vs0.83753_ema.pth +3 -0
  16. 10_lr_stronger_proj_residual_13/r1s/10_lr_stronger_proj_residual_13_s26092004_f2_r1_vs0.84252_ema.pth +3 -0
  17. 10_lr_stronger_proj_residual_13/r1s/10_lr_stronger_proj_residual_13_s26092004_f3_r1_vs0.83418_ema.pth +3 -0
  18. 10_lr_stronger_proj_residual_13/r1s/10_lr_stronger_proj_residual_13_s26092004_f4_r1_vs0.81628_ema.pth +3 -0
  19. 10_lr_stronger_proj_residual_13/results/10_lr_stronger_proj_residual_13_test.json +176 -0
  20. 10_lr_stronger_proj_residual_13/results/10_lr_stronger_proj_residual_13_test_df.xlsx +0 -0
  21. 10_lr_stronger_proj_residual_13/results/10_lr_stronger_proj_residual_13_test_df_best.xlsx +0 -0
.gitattributes CHANGED
@@ -35,3 +35,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  12_13_lr_16/logs/12_13_lr_16_log_plot.jpg filter=lfs diff=lfs merge=lfs -text
37
  11_13_lr_15/logs/11_13_lr_15_log_plot.jpg filter=lfs diff=lfs merge=lfs -text
 
 
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  12_13_lr_16/logs/12_13_lr_16_log_plot.jpg filter=lfs diff=lfs merge=lfs -text
37
  11_13_lr_15/logs/11_13_lr_15_log_plot.jpg filter=lfs diff=lfs merge=lfs -text
38
+ 10_lr_stronger_proj_residual_13/logs/10_lr_stronger_proj_residual_13_log_plot.jpg filter=lfs diff=lfs merge=lfs -text
10_lr_stronger_proj_residual_13/10_lr_stronger_proj_residual_13.py ADDED
@@ -0,0 +1,1580 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = "10_lr_stronger_proj_residual_13"
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
+
396
+ self.normalize = normalize
397
+
398
+ def cls_pooling(self, hidden):
399
+ return hidden[:, 0]
400
+
401
+ def forward(self, input_ids, attention_mask, is_query=True):
402
+
403
+ if is_query:
404
+ # [B, n_parts, L]
405
+ B, n_parts, L = input_ids.shape
406
+
407
+ input_ids = input_ids.view(-1, L)
408
+ attention_mask = attention_mask.view(-1, L)
409
+
410
+ outputs = self.encoder(
411
+ input_ids=input_ids,
412
+ attention_mask=attention_mask
413
+ )
414
+
415
+ hidden = outputs.last_hidden_state # [B*n_parts, L, H]
416
+
417
+ chunk_repr = self.cls_pooling(hidden) # [B*n_parts, H]
418
+ chunk_repr = chunk_repr.view(B, n_parts, -1) # [B, n_parts, H]
419
+ pooled = chunk_repr.mean(dim=1)
420
+ # [B, H]
421
+
422
+ else:
423
+ # [B, K, n_parts, L]
424
+ B, K, n_parts, L = input_ids.shape
425
+
426
+ input_ids = input_ids.view(-1, L)
427
+ attention_mask = attention_mask.view(-1, L)
428
+
429
+ outputs = self.encoder(
430
+ input_ids=input_ids,
431
+ attention_mask=attention_mask
432
+ )
433
+
434
+ hidden = outputs.last_hidden_state
435
+
436
+ chunk_repr = self.cls_pooling(hidden)
437
+ chunk_repr = chunk_repr.view(B, K, n_parts, -1) # [B, K, n_parts, H]
438
+ pooled = chunk_repr.mean(dim=2) # [B, K, H]
439
+
440
+ # residual MLP projection
441
+ emb = self.proj(pooled) + self.residual_proj(pooled)
442
+
443
+ if self.normalize:
444
+ emb = F.normalize(emb, dim=-1)
445
+
446
+ return emb
447
+
448
+ def test_model():
449
+ model = nn.DataParallel(EncodeModel('vinai/phobert-base', 256, True)).to(device)
450
+ model.eval()
451
+
452
+ bz = 32
453
+ vocab_size = 1000
454
+ qi = torch.randint(0, vocab_size, (bz, 1, 256)).to(device)
455
+ qa = torch.ones(bz, 1, 256).to(device)
456
+ di = torch.randint(0, vocab_size, (bz, 5, 2, 256)).to(device)
457
+ da = torch.ones(bz, 5, 2, 256).to(device)
458
+
459
+ st = time.time()
460
+ with torch.no_grad():
461
+ encoded_text = model(qi, qa, is_query=True)
462
+ encoded_pos = model(di, da, is_query=False)
463
+ encoded_neg = model(di, da, is_query=False)
464
+ print(encoded_text.shape, encoded_pos.shape, encoded_neg.shape)
465
+ print(time.time() - st)
466
+
467
+ del model, qi, qa, di, da, encoded_text, encoded_pos, encoded_neg
468
+ torch.cuda.empty_cache()
469
+ gc.collect()
470
+ test_model()
471
+
472
+ # %% [code]
473
+ def configure_optimizers(network, optim_params, scheduler_params):
474
+ try:
475
+ optim_params = copy.copy(optim_params)
476
+ scheduler_params = copy.copy(scheduler_params)
477
+
478
+ optim_name = optim_params.pop('name')
479
+ scheduler_name = scheduler_params.pop('name')
480
+
481
+ optimizer_cls = globals().get(optim_name) or getattr(optim, optim_name, None)
482
+ scheduler_cls = globals().get(scheduler_name) or getattr(optim.lr_scheduler, scheduler_name, None)
483
+
484
+ if optimizer_cls is None:
485
+ raise ValueError(f"Optimizer '{optim_name}' is not available!")
486
+
487
+ optimizer = optimizer_cls(network.parameters(), **optim_params)
488
+
489
+ scheduler = None
490
+ if scheduler_params and scheduler_cls: # Chỉ tạo scheduler nếu có tham số
491
+ scheduler = scheduler_cls(optimizer, **scheduler_params)
492
+
493
+ return optimizer, scheduler
494
+
495
+ except KeyError as e:
496
+ raise ValueError(f"Missing {e} in config!!")
497
+
498
+ def freeze(self, model):
499
+ model.eval()
500
+ for param in model.parameters():
501
+ param.requires_grad = False
502
+
503
+ def unfreeze(self, model):
504
+ model.train()
505
+ for param in model.parameters():
506
+ param.requires_grad = True
507
+
508
+ def reduce_batch_size(loader, ratio=0.5):
509
+ new_bs = max(1, int(loader.batch_size * ratio))
510
+
511
+ shuffle = isinstance(loader.sampler, RandomSampler)
512
+
513
+ new_loader = DataLoader(
514
+ dataset=loader.dataset,
515
+ batch_size=new_bs,
516
+ shuffle=shuffle,
517
+ sampler=None if shuffle else loader.sampler,
518
+ num_workers=loader.num_workers,
519
+ collate_fn=loader.collate_fn,
520
+ pin_memory=loader.pin_memory,
521
+ drop_last=loader.drop_last,
522
+ timeout=loader.timeout,
523
+ worker_init_fn=loader.worker_init_fn,
524
+ multiprocessing_context=loader.multiprocessing_context,
525
+ generator=loader.generator,
526
+ prefetch_factor=loader.prefetch_factor if loader.num_workers > 0 else None,
527
+ persistent_workers=loader.persistent_workers,
528
+ pin_memory_device=loader.pin_memory_device
529
+ )
530
+
531
+ return new_loader
532
+
533
+ def list_to_tuple(x):
534
+ if isinstance(x, (list, tuple)):
535
+ return tuple(list_to_tuple(i) for i in x)
536
+ return x
537
+
538
+ def fmt(x):
539
+ if isinstance(x, float):
540
+ return round(x, 5)
541
+ if isinstance(x, dict):
542
+ return {k: fmt(v) for k, v in x.items()}
543
+ if isinstance(x, list):
544
+ return [fmt(v) for v in x]
545
+ return x
546
+
547
+ class ModelEmaV3Proxy(ModelEmaV3):
548
+ def __getattr__(self, name):
549
+ try:
550
+ return super().__getattr__(name)
551
+ except AttributeError:
552
+ return getattr(self.module, name)
553
+
554
+ class DataParallelProxy(nn.DataParallel):
555
+ def __getattr__(self, name):
556
+ try:
557
+ return super().__getattr__(name)
558
+ except AttributeError:
559
+ attr = getattr(self.module, name)
560
+
561
+ if callable(attr):
562
+ def wrapper(*args, **kwargs):
563
+ return self._parallel_apply_method(name, *args, **kwargs)
564
+ return wrapper
565
+
566
+ return attr
567
+
568
+ def _parallel_apply_method(self, method_name, *inputs, **kwargs):
569
+ if not self.device_ids:
570
+ return getattr(self.module, method_name)(*inputs, **kwargs)
571
+
572
+ inputs_scattered, kwargs_scattered = self.scatter(inputs, kwargs, self.device_ids)
573
+
574
+ replicas = self.replicate(self.module, self.device_ids)
575
+
576
+ outputs = self.parallel_apply(
577
+ [getattr(replica, method_name) for replica in replicas],
578
+ inputs_scattered,
579
+ kwargs_scattered
580
+ )
581
+
582
+ return self.gather(outputs, self.output_device)
583
+
584
+ class Trainer:
585
+ def __init__(
586
+ 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,
587
+ logging=0, logging_file=False, checkpoints_dir="", early_stopping=False, eval_from_ratio=-1, eval_every=1, device='cpu',
588
+ schedule_in_step=True, use_ema=True, ema_from_ratio=-1, ema_decay=0.999, return_best=True, return_last=True
589
+ ):
590
+ self.ema_net = None
591
+
592
+ self.training_time = self._time_str_to_seconds(training_time)
593
+ self.mode = eval_mode
594
+ self.topk = topk
595
+ self.device = device
596
+ self.logging = logging if logging < epochs else 1
597
+ self.logging_file = logging_file
598
+ self.checkpoints_dir = checkpoints_dir
599
+ self.early_stopping = early_stopping
600
+ self.eval_from_ratio = eval_from_ratio
601
+ self.eval_every = eval_every
602
+ self.save_name = save_name
603
+ self.save_best = save_best
604
+ self.save_last = save_last
605
+ self.return_best = return_best
606
+ self.return_last = return_last
607
+ self.max_grad_norm = max_grad_norm
608
+ self.schedule_in_step = schedule_in_step
609
+ self.use_ema = use_ema
610
+ self.ema_from_ratio = ema_from_ratio
611
+ self.ema_decay = ema_decay
612
+
613
+ self.best_stage = [[float('-inf') if self.mode == 'max' else float('inf'), None, None]]
614
+ self.grad_scaler = torch.amp.GradScaler(self.device, init_scale=1024.0)
615
+
616
+ 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):
617
+ if eval_fn is None:
618
+ if self.mode == "max":
619
+ eval_fn = lambda *x: -loss_fn(*x)
620
+ else:
621
+ eval_fn = lambda *x: loss_fn(*x)
622
+
623
+ if torch.cuda.device_count() > 1:
624
+ network = DataParallelProxy(network)
625
+ network = network.to(self.device)
626
+
627
+ if not start_training_time:
628
+ start_training_time = time.time()
629
+
630
+ start_ema = int(epochs * self.ema_from_ratio)
631
+ start_eval = int(epochs * self.eval_from_ratio)
632
+
633
+ if val_loader is None:
634
+ print(f'[Trainer CallBack] 📢 Không có Val Set, không thể đánh giá và Early Stopping!')
635
+ else:
636
+ model_to_use_str = 'mô hình EMA' if self.use_ema else 'mô hình gốc'
637
+ start_model_update_str = f'Bắt đầu cập nhật EMA từ epoch {start_epoch + start_ema}!' if self.use_ema else ''
638
+ print(f'[Trainer CallBack] 📢 Đánh giá bằng {model_to_use_str} từ epoch {start_epoch + start_eval}!', start_model_update_str)
639
+
640
+ training_log = {}
641
+ for epoch in range(start_epoch, epochs+start_epoch):
642
+ if self.use_ema and self.ema_net is None and epoch - start_epoch >= start_ema:
643
+ self.ema_net = ModelEmaV3Proxy(network, self.ema_decay, device=self.device)
644
+
645
+ try:
646
+ eval_net = self.ema_net if (self.use_ema and self.ema_net is not None) else network
647
+ if (epoch - start_epoch) % refresh_every == 0:
648
+ encoded_docs = self._get_encoded_docs(eval_net, corpus_loader)
649
+ print(f"[Trainer CallBack] 📢 Epoch {epoch}/{epochs}: Refresh Encoded Doc (refresh_every={refresh_every})!")
650
+
651
+ train_loss_epoch, train_loss_epoch_dict = self._train_epoch(network, train_loader, optimizer, scheduler, loss_fn, encoded_docs)
652
+ logging_dict = {'lr': [group['lr'] for group in optimizer.param_groups], 'train_loss': train_loss_epoch}
653
+ logging_dict.update(train_loss_epoch_dict)
654
+
655
+ if val_loader is not None and epoch - start_epoch >= start_eval and (epoch - start_epoch - start_eval) % self.eval_every == 0:
656
+ val_score, val_score_dict, _ = self._eval_epoch(eval_net, val_loader, eval_fn, encoded_docs)
657
+ update = self._update_best_network(eval_net, val_score, epoch)
658
+ logging_dict.update({'val_score': val_score, 'best_score': self.best_stage[0][0], 'new_best_model': update})
659
+ logging_dict.update(val_score_dict)
660
+ if not self.schedule_in_step and scheduler:
661
+ scheduler.step()
662
+
663
+ except RuntimeError as e:
664
+ if "out of memory" in str(e).lower():
665
+ print(f"[Trainer CallBack] ⚠️ Epoch {epoch}/{epochs}: CUDA Out of Memory! Clearing GPU cache...")
666
+ torch.cuda.empty_cache()
667
+ gc.collect()
668
+ if torch.cuda.is_available():
669
+ torch.cuda.synchronize()
670
+ print(f"[Trainer CallBack] ✅ Epoch {epoch}/{epochs}: GPU memory cleared")
671
+
672
+ train_loader = reduce_batch_size(train_loader, ratio=0.5)
673
+ if val_loader is not None:
674
+ val_loader = reduce_batch_size(val_loader, ratio=0.5)
675
+
676
+ logging_dict = {'lr': [group['lr'] for group in optimizer.param_groups], 'train_loss': float('inf')}
677
+ else:
678
+ raise
679
+
680
+ training_log[epoch] = logging_dict
681
+ if self.is_early_stopping(epoch):
682
+ print(f'[Trainer CallBack] 📢 Epoch {epoch}/{epochs}: Detect Overfitting! Breaking Training Process...')
683
+ break
684
+ if self.logging:
685
+ if epoch % self.logging == 0:
686
+ print(f'[Trainer CallBack] 📢 Epoch {epoch}/{epochs}:', fmt(logging_dict))
687
+ else:
688
+ print(f'{epoch}...', end=' ')
689
+
690
+ if self._at_time_limit(start_training_time):
691
+ 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}')
692
+ break
693
+
694
+ if self.logging_file:
695
+ os.makedirs(f'{self.checkpoints_dir}/logs', exist_ok=True)
696
+ with open(f"{self.checkpoints_dir}/logs/{self.save_name}_logging.json", "a", encoding="utf-8") as f:
697
+ f.write(json.dumps(training_log))
698
+
699
+ if self.use_ema and self.ema_net is not None:
700
+ self._save_state_dict(self.ema_net.module)
701
+ else:
702
+ self._save_state_dict(network)
703
+ print(f'[Trainer CallBack] 📢 Kết thúc training.\n')
704
+
705
+ best_model, last_model = None, None
706
+ eval_net = self.ema_net.module if (self.use_ema and self.ema_net is not None) else network
707
+ if self.return_best :
708
+ best_model = self.best_stage[0][2] if self.best_stage[0][2] is not None else eval_net.state_dict()
709
+ best_model = {k.replace("module.", ""): v.detach().cpu().clone() for k, v in best_model.items()}
710
+ if self.return_last:
711
+ last_model = eval_net.state_dict()
712
+ last_model = {k.replace("module.", ""): v.detach().cpu().clone() for k, v in last_model.items()}
713
+
714
+ del network
715
+ torch.cuda.empty_cache()
716
+ gc.collect()
717
+ return training_log, best_model, last_model
718
+
719
+ def _time_str_to_seconds(self, time_str):
720
+ days, hours, minutes, seconds = map(int, time_str.split(":"))
721
+ return days * 86400 + hours * 3600 + minutes * 60 + seconds
722
+
723
+ def _update_best_network(self, network, val_score, epoch):
724
+ topk = max(1, self.topk)
725
+ self.best_stage.append([val_score, epoch, {k: v.detach().cpu().clone() for k, v in network.state_dict().items()}])
726
+ self.best_stage = sorted(self.best_stage, reverse=(self.mode == 'max'), key=lambda x: x[0])[:topk]
727
+ if val_score in [x[0] for x in self.best_stage]:
728
+ return True
729
+ return False
730
+
731
+ def is_early_stopping(self, epoch):
732
+ if self.best_stage[0][1] is None:
733
+ return False
734
+ if not self.early_stopping:
735
+ return False
736
+ return epoch - self.best_stage[0][1] >= self.early_stopping
737
+
738
+ def _at_time_limit(self, start_training_time):
739
+ return time.time() - start_training_time >= self.training_time
740
+
741
+ def _save_state_dict(self, network):
742
+ if self.topk <= 0:
743
+ return
744
+
745
+ if self.save_best:
746
+ for r in range(self.topk):
747
+ os.makedirs(f'{self.checkpoints_dir}/r{r+1}s', exist_ok=True)
748
+
749
+ for rank, (score, epoch, state_dict) in enumerate(self.best_stage):
750
+ if state_dict is None:
751
+ continue
752
+ state_dict = {k.replace("module.", ""): v.detach().cpu().clone() for k, v in state_dict.items()}
753
+ 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')
754
+ if self.save_last:
755
+ os.makedirs(f'{self.checkpoints_dir}/lasts', exist_ok=True)
756
+ state_dict = {k.replace("module.", ""): v.detach().cpu().clone() for k, v in network.state_dict().items()}
757
+ torch.save(state_dict, f'{self.checkpoints_dir}/lasts/{self.save_name}_last_{"ema" if self.ema_net is not None else ""}.pth')
758
+
759
+ def _train_epoch(self, network, train_loader, optimizer, scheduler, loss_fn, encoded_docs):
760
+ network.train()
761
+ total_loss = 0
762
+ total_loss_dict = {}
763
+ for batch_idx, batch in enumerate(train_loader):
764
+ optimizer.zero_grad()
765
+ with torch.autocast(device_type=self.device, dtype=torch.float16):
766
+ loss, loss_dict = self._cal_loss(network, batch, batch_idx, loss_fn, encoded_docs)
767
+
768
+ for k, v in loss_dict.items():
769
+ t = total_loss_dict.get(k, 0)
770
+ total_loss_dict[k] = t + v
771
+ self.grad_scaler.scale(loss).backward()
772
+ self.grad_scaler.unscale_(optimizer)
773
+ grad_norm = nn.utils.clip_grad_norm_(network.parameters(), self.max_grad_norm)
774
+ # print(grad_norm) # Bỏ cmt dòng này để biết nên chọn max_grad_norm bằng bao nhiêu...
775
+ self.grad_scaler.step(optimizer)
776
+ self.grad_scaler.update()
777
+ if self.schedule_in_step and scheduler:
778
+ scheduler.step()
779
+ if self.use_ema and self.ema_net is not None:
780
+ self.ema_net.update(network)
781
+ total_loss += loss
782
+ return (total_loss / len(train_loader)).item(), {k: v.item() / len(train_loader) for k, v in total_loss_dict.items()}
783
+
784
+ def _eval_epoch(self, network, val_loader, eval_fn, encoded_docs):
785
+ network.eval()
786
+ total_score = 0.0
787
+ total_score_dict = {}
788
+ object_lists = None # sẽ init sau
789
+
790
+ with torch.no_grad():
791
+ for batch_idx, batch in enumerate(val_loader):
792
+ score, score_dict, objects = self._cal_val_score(network, batch, batch_idx, eval_fn, encoded_docs)
793
+ total_score += score
794
+
795
+ for k, v in score_dict.items():
796
+ t = total_score_dict.get(k, 0)
797
+ total_score_dict[k] = t + v
798
+
799
+ if objects:
800
+ if object_lists is None:
801
+ object_lists = [[] for _ in range(len(objects))]
802
+
803
+ for i, obj in enumerate(objects):
804
+ object_lists[i].append(obj.detach())
805
+
806
+ if object_lists is not None:
807
+ object_arrays = [
808
+ torch.concat(obj_list, dim=0).cpu().numpy()
809
+ for obj_list in object_lists
810
+ ]
811
+ else:
812
+ object_arrays = []
813
+
814
+ return total_score / len(val_loader), {k: v / len(val_loader) for k, v in total_score_dict.items()}, object_arrays
815
+
816
+ def _get_encoded_docs(self, network, corpus_loader):
817
+ network.eval()
818
+ with torch.no_grad():
819
+ encoded_docs = []
820
+ for batch_idx, batch in enumerate(corpus_loader):
821
+ input_ids = batch['input_ids'].to(self.device)
822
+ attn_mask = batch['attn_mask'].to(self.device)
823
+ encoded_doc = network(input_ids, attn_mask, is_query=False)
824
+ encoded_docs.append(encoded_doc)
825
+ encoded_docs = torch.concat(encoded_docs, dim=0).squeeze(1)
826
+ return encoded_docs
827
+
828
+ def _cal_loss(self, network, batch, batch_idx, loss_fn, encoded_docs):
829
+ # Bạn cần override _cal_loss để tính loss
830
+ text_input_ids = batch['text_input_ids'].to(self.device)
831
+ text_attn_mask = batch['text_attn_mask'].to(self.device)
832
+ pos_idxes = batch['pos_idxes'].to(self.device)
833
+ pos_mask = batch['pos_mask'].to(self.device)
834
+ neg_idxes = batch['neg_idxes'].to(self.device)
835
+
836
+ encoded_text = network(text_input_ids, text_attn_mask, is_query=True)
837
+ encoded_pos = encoded_docs[pos_idxes]
838
+ encoded_neg = encoded_docs[neg_idxes]
839
+
840
+ loss_dict = loss_fn(encoded_text, encoded_pos, encoded_neg, pos_mask)
841
+ return loss_dict['total'], loss_dict
842
+
843
+ def _cal_val_score(self, network, batch, batch_idx, eval_fn, encoded_docs):
844
+ # 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)
845
+ text_input_ids = batch['text_input_ids'].to(self.device)
846
+ text_attn_mask = batch['text_attn_mask'].to(self.device)
847
+ gt_pos_idxes = batch['gt_pos_idxes']
848
+ encoded_text = network(text_input_ids, text_attn_mask, is_query=True)
849
+
850
+ scores = torch.matmul(encoded_text, encoded_docs.T)
851
+ topk_scores, topk_indices = torch.topk(scores, k=10)
852
+ pred_topk = [
853
+ idx[score > 0].tolist()
854
+ for score, idx in zip(topk_scores, topk_indices)
855
+ ]
856
+
857
+ pred_topk = list_to_tuple(pred_topk)
858
+ gt_pos_idxes = list_to_tuple(gt_pos_idxes)
859
+ score_dict = eval_fn(pred_topk, gt_pos_idxes)
860
+ return score_dict['recall'], score_dict, []
861
+
862
+ # %% [code]
863
+ def tokenize_to_parts(text, tokenizer, max_len, max_n_parts):
864
+ # Tokenize với overflow để chia thành nhiều đoạn
865
+ enc = tokenizer(
866
+ text,
867
+ max_length=max_len*max_n_parts,
868
+ truncation=True,
869
+ padding="max_length",
870
+ return_overflowing_tokens=True,
871
+ return_tensors="pt"
872
+ )
873
+
874
+ input_ids = enc["input_ids"].reshape(max_n_parts, max_len) # (n_parts, max_len)
875
+ attn_mask = enc["attention_mask"].reshape(max_n_parts, max_len) # (n_parts, max_len)
876
+
877
+ return input_ids, attn_mask
878
+
879
+ class LawRetrievalDataset(Dataset):
880
+ def __init__(self, all_data, using_idxes, corpus_dict, tokenizer, max_len, max_n_parts, n_negs):
881
+ super().__init__()
882
+
883
+ self.all_data = all_data
884
+ self.using_idxes = using_idxes
885
+ self.tokenizer = tokenizer
886
+ self.max_len = max_len
887
+ self.max_n_parts = max_n_parts
888
+ self.n_negs = n_negs
889
+
890
+ # ===== BUILD CORPUS =====
891
+ idx = 0
892
+ self.corpus_list = []
893
+ self.corpus_dict = {}
894
+
895
+ for doc_name, articles_dict in corpus_dict.items():
896
+ self.corpus_dict[doc_name] = {}
897
+ for article_idx, content in articles_dict.items():
898
+ self.corpus_list.append([doc_name, article_idx, content])
899
+ self.corpus_dict[doc_name][article_idx] = {
900
+ 'content': content,
901
+ 'idx': idx
902
+ }
903
+ idx += 1
904
+
905
+ def __len__(self):
906
+ return len(self.using_idxes)
907
+
908
+ # ===== ENCODE DOC =====
909
+ def _encode_contexts(self, idxes):
910
+ all_input_ids, all_attn_mask = [], []
911
+
912
+ for idx in idxes:
913
+ name, art, _ = self.corpus_list[idx]
914
+ corpus = self.corpus_dict[name][art]
915
+
916
+ if 'content_input_ids' in corpus:
917
+ content_input_ids = corpus['content_input_ids']
918
+ content_attn_mask = corpus['content_attn_mask']
919
+ else:
920
+ content = corpus['content']
921
+ content_input_ids, content_attn_mask = tokenize_to_parts(
922
+ content, self.tokenizer, self.max_len, self.max_n_parts
923
+ )
924
+ corpus['content_input_ids'] = content_input_ids
925
+ corpus['content_attn_mask'] = content_attn_mask
926
+
927
+ all_input_ids.append(content_input_ids)
928
+ all_attn_mask.append(content_attn_mask)
929
+
930
+ all_input_ids = torch.stack(all_input_ids)
931
+ all_attn_mask = torch.stack(all_attn_mask)
932
+
933
+ return all_input_ids, all_attn_mask
934
+
935
+ def __getitem__(self, idx):
936
+ ridx = self.using_idxes[idx]
937
+ data = self.all_data[ridx]
938
+
939
+ query_text = data['text']
940
+
941
+ text_input_ids, text_attn_mask = tokenize_to_parts(
942
+ query_text, self.tokenizer, self.max_len, 1
943
+ )
944
+
945
+ # ===== POS =====
946
+ gt_pos_idxes = []
947
+ hard_names = []
948
+ for law in data['relevant_law']:
949
+ name = law['doc']
950
+ art = law['art']
951
+ gt_pos_idxes.append(self.corpus_dict[name][art]['idx'])
952
+ if name not in hard_names:
953
+ hard_names.append(name)
954
+
955
+ pos_idxes = torch.tensor(gt_pos_idxes, dtype=torch.long)
956
+ pos_mask = torch.ones(len(pos_idxes))
957
+
958
+ # ===== NEG =====
959
+ hard_neg_idxes = []
960
+ for name in hard_names:
961
+ for content in self.corpus_dict[name].values():
962
+ if content['idx'] in gt_pos_idxes:
963
+ continue
964
+ hard_neg_idxes.append(content['idx'])
965
+
966
+ easy_neg_idxes = list(range(len(self.corpus_list)))
967
+ for i in gt_pos_idxes + hard_neg_idxes:
968
+ if i in easy_neg_idxes:
969
+ easy_neg_idxes.remove(i)
970
+
971
+ n_hards = min(len(hard_neg_idxes), self.n_negs // 2)
972
+ neg_idxes = random.sample(hard_neg_idxes, n_hards) + random.sample(easy_neg_idxes, self.n_negs - n_hards)
973
+ neg_idxes = torch.tensor(neg_idxes, dtype=torch.long)
974
+
975
+ return {
976
+ 'text_input_ids': text_input_ids,
977
+ 'text_attn_mask': text_attn_mask,
978
+ 'gt_pos_idxes': gt_pos_idxes,
979
+ 'pos_idxes': pos_idxes,
980
+ 'pos_mask': pos_mask,
981
+ 'neg_idxes': neg_idxes,
982
+ }
983
+
984
+ class CorpusDataset(Dataset):
985
+ def __init__(self, corpus_dict, tokenizer, max_len, max_n_parts):
986
+ super().__init__()
987
+ self.tokenizer = tokenizer
988
+ self.max_len = max_len
989
+ self.max_n_parts = max_n_parts
990
+
991
+ idx = 0
992
+ self.corpus_list = []
993
+ self.corpus_dict = {}
994
+ for doc_name, articles_dict in corpus_dict.items():
995
+ self.corpus_dict[doc_name] = {}
996
+ for article_idx, content in articles_dict.items():
997
+ self.corpus_list.append([doc_name, article_idx, content])
998
+ self.corpus_dict[doc_name][article_idx] = {'content': content, 'idx': idx}
999
+ idx += 1
1000
+
1001
+ def __len__(self):
1002
+ return len(self.corpus_list)
1003
+
1004
+ def _encode_contexts(self, idxes):
1005
+ all_input_ids, all_attn_mask = [], []
1006
+ for idx in idxes:
1007
+ name = self.corpus_list[idx][0]
1008
+ art = self.corpus_list[idx][1]
1009
+ corpus = self.corpus_dict[name][art]
1010
+ if 'content_input_ids' in corpus and 'content_attn_mask' in corpus:
1011
+ content_input_ids = corpus['content_input_ids']
1012
+ content_attn_mask = corpus['content_attn_mask']
1013
+ else:
1014
+ content = corpus['content']
1015
+ content_input_ids, content_attn_mask = tokenize_to_parts(content, self.tokenizer, self.max_len, self.max_n_parts)
1016
+ corpus['content_input_ids'] = content_input_ids
1017
+ corpus['content_attn_mask'] = content_attn_mask
1018
+
1019
+ all_input_ids.append(content_input_ids)
1020
+ all_attn_mask.append(content_attn_mask)
1021
+
1022
+ all_input_ids = torch.stack(all_input_ids)
1023
+ all_attn_mask = torch.stack(all_attn_mask)
1024
+ return all_input_ids, all_attn_mask
1025
+
1026
+ def __getitem__(self, idx):
1027
+ input_ids, attn_mask = self._encode_contexts([idx])
1028
+
1029
+ return {
1030
+ 'input_ids': input_ids,
1031
+ 'attn_mask': attn_mask,
1032
+ }
1033
+
1034
+ def _pad_batch(tensor_list, pad_value=0):
1035
+ """
1036
+ tensor_list: list of tensors, mỗi tensor shape (Nk, max_n_parts, max_len)
1037
+ return: tensor shape (B, max_Nk, max_n_parts, max_len)
1038
+ """
1039
+ max_Nk = max(t.size(0) for t in tensor_list)
1040
+
1041
+ padded = []
1042
+ for t in tensor_list:
1043
+ Nk = t.size(0)
1044
+
1045
+ if Nk < max_Nk:
1046
+ pad_shape = (max_Nk - Nk, *t.shape[1:])
1047
+ pad_tensor = t.new_full(pad_shape, pad_value)
1048
+ t = torch.cat([t, pad_tensor], dim=0)
1049
+
1050
+ padded.append(t)
1051
+
1052
+ return torch.stack(padded) # (B, max_Nk, max_n_parts, max_len)
1053
+
1054
+ def collate_fn(batch):
1055
+ text_input_ids = torch.stack([b["text_input_ids"] for b in batch])
1056
+ text_attn_mask = torch.stack([b["text_attn_mask"] for b in batch])
1057
+ gt_pos_idxes = [b["gt_pos_idxes"] for b in batch]
1058
+ neg_idxes = torch.stack([b["neg_idxes"] for b in batch])
1059
+
1060
+ pos_idxes = [b["pos_idxes"].unsqueeze(-1).unsqueeze(-1) for b in batch]
1061
+ pos_mask = [b["pos_mask"].unsqueeze(-1).unsqueeze(-1) for b in batch]
1062
+
1063
+ # pad theo Nk
1064
+ pos_idxes = _pad_batch(pos_idxes, pad_value=0).squeeze(-1).squeeze(-1)
1065
+ pos_mask = _pad_batch(pos_mask, pad_value=0).squeeze(-1).squeeze(-1)
1066
+
1067
+ return {
1068
+ 'text_input_ids': text_input_ids,
1069
+ 'text_attn_mask': text_attn_mask,
1070
+ 'gt_pos_idxes': gt_pos_idxes,
1071
+ 'pos_idxes': pos_idxes,
1072
+ 'pos_mask': pos_mask,
1073
+ 'neg_idxes': neg_idxes,
1074
+ }
1075
+
1076
+ # %% [code]
1077
+ def encode_corpus(state_dicts, network, corpus_loader, device):
1078
+ if torch.cuda.device_count() > 1:
1079
+ network = nn.DataParallel(network)
1080
+ network.to(device)
1081
+ network.eval()
1082
+
1083
+ all_model_embs = []
1084
+ for i, state_dict in enumerate(state_dicts):
1085
+ # ===== load model =====
1086
+ if torch.cuda.device_count() > 1:
1087
+ network.module.load_state_dict(state_dict)
1088
+ else:
1089
+ network.load_state_dict(state_dict)
1090
+
1091
+ encoded_docs = []
1092
+
1093
+ with torch.no_grad():
1094
+ for batch in corpus_loader:
1095
+ input_ids = batch['input_ids'].to(device)
1096
+ attn_mask = batch['attn_mask'].to(device)
1097
+
1098
+ emb = network(input_ids, attn_mask, is_query=False) # [B, 1, D] hoặc [B, D]
1099
+
1100
+ encoded_docs.append(emb)
1101
+
1102
+ encoded_docs = torch.concat(encoded_docs, dim=0).squeeze(1) # [N, D]
1103
+ all_model_embs.append(encoded_docs)
1104
+
1105
+ # ===== ensemble =====
1106
+ # stack → [M, N, D]
1107
+ all_model_embs = torch.stack(all_model_embs, dim=0)
1108
+ final_embs = all_model_embs.mean(dim=0) # [N, D]
1109
+
1110
+ return final_embs
1111
+
1112
+ def test(state_dicts, network, test_loader, device, eval_fn, encoded_docs, bm25_scores, topks=[5, 10, 15]):
1113
+ if torch.cuda.device_count() > 1:
1114
+ network = nn.DataParallel(network)
1115
+ network.to(device)
1116
+ network.eval()
1117
+
1118
+ per_model_scores = []
1119
+ max_k = max(topks)
1120
+
1121
+ all_scores = []
1122
+ all_gt_pos_idxes = []
1123
+ with torch.no_grad():
1124
+ for batch in test_loader:
1125
+ text_input_ids = batch['text_input_ids'].to(device)
1126
+ text_attn_mask = batch['text_attn_mask'].to(device)
1127
+ gt_pos_idxes = batch['gt_pos_idxes']
1128
+ all_gt_pos_idxes.extend(gt_pos_idxes)
1129
+
1130
+ list_encoded_texts = []
1131
+
1132
+ for state_dict in state_dicts:
1133
+ # ===== load model =====
1134
+ if torch.cuda.device_count() > 1:
1135
+ network.module.load_state_dict(state_dict)
1136
+ else:
1137
+ network.load_state_dict(state_dict)
1138
+
1139
+ encoded_text = network(text_input_ids, text_attn_mask, is_query=True)
1140
+ list_encoded_texts.append(encoded_text)
1141
+
1142
+ ensemble_encoded_text = torch.stack(list_encoded_texts, dim=0).mean(dim=0)
1143
+ scores = torch.matmul(ensemble_encoded_text, encoded_docs.T) # B, M
1144
+ all_scores.append(scores)
1145
+
1146
+ all_scores = torch.concat(all_scores, dim=0) # (N, M)
1147
+
1148
+ bm25_scores = torch.tensor(bm25_scores).to(all_scores.device) # (N, M)
1149
+ bm25_scores = bm25_scores.float()
1150
+
1151
+ # min-max về [0, 1]
1152
+ bm25_scores = (
1153
+ bm25_scores - bm25_scores.min(dim=-1, keepdim=True).values
1154
+ ) / (
1155
+ bm25_scores.max(dim=-1, keepdim=True).values
1156
+ - bm25_scores.min(dim=-1, keepdim=True).values
1157
+ + 1e-8
1158
+ )
1159
+ # đổi sang [-1, 1]
1160
+ bm25_scores = bm25_scores * 2 - 1
1161
+
1162
+ all_gt_pos_idxes = list_to_tuple(all_gt_pos_idxes)
1163
+
1164
+ final_score = {}
1165
+ for weight in [0, 0.25, 0.5, 0.75, 1]:
1166
+
1167
+ # score cuối
1168
+ final_scores = all_scores + weight * bm25_scores
1169
+
1170
+ # topk lớn nhất
1171
+ topk_scores, topk_indices = torch.topk(final_scores, k=max_k)
1172
+
1173
+ pred_topk_full = [
1174
+ idx[score > 0].tolist()
1175
+ for score, idx in zip(topk_scores, topk_indices)
1176
+ ]
1177
+
1178
+ pred_topk_full = list_to_tuple(pred_topk_full)
1179
+
1180
+ final_score[weight] = {}
1181
+
1182
+ for k in topks:
1183
+ pred_topk_k = [p[:k] for p in pred_topk_full]
1184
+ final_score[weight][k] = eval_fn(pred_topk_k, all_gt_pos_idxes)
1185
+
1186
+ return final_score
1187
+
1188
+ # %% [code]
1189
+ with open(f'{train_dir}/train.json', "r", encoding="utf-8") as f:
1190
+ data_train = json.load(f)
1191
+
1192
+ with open(f'{test_dir}/test.json', "r", encoding="utf-8") as f:
1193
+ data_test = json.load(f)
1194
+
1195
+ with open(f'{test_dir}/corpus.json', "r", encoding="utf-8") as f:
1196
+ data_corpus = json.load(f)
1197
+
1198
+ print('Train:', len(data_train))
1199
+ print('Test:', len(data_test))
1200
+ print('Corpus:', len(data_corpus))
1201
+
1202
+ # %% [code]
1203
+ # trigger_types = sorted(list(set([e['label'] for d in data_train + data_test for e in d['issues']]))) # NBR : Neighbor relation
1204
+ # bio_trigger_types = ['O'] + [f'{prefix}-{trg}' for trg in trigger_types for prefix in ['B', 'I']]
1205
+ # trigger_label2id = {l: i for i, l in enumerate(bio_trigger_types)}
1206
+ # trigger_id2label = {i: l for l, i in trigger_label2id.items()}
1207
+
1208
+ # argument_types = sorted(list(set([a['role'] for d in data_train + data_test for e in d['issues'] for a in e['arguments']])))
1209
+ # bio_argument_types = ['O'] + [f'{prefix}-{arg}' for arg in argument_types for prefix in ['B', 'I']]
1210
+ # argument_label2id = {l: i for i, l in enumerate(bio_argument_types)}
1211
+ # argument_id2label = {i: l for l, i in argument_label2id.items()}
1212
+
1213
+ # label2id = {
1214
+ # 'Trg': trigger_label2id,
1215
+ # 'Arg': argument_label2id,
1216
+ # }
1217
+
1218
+ # id2label = {
1219
+ # 'Trg': trigger_id2label,
1220
+ # 'Arg': argument_id2label,
1221
+ # }
1222
+
1223
+ # %% [code]
1224
+ # zero_events_idxes = []
1225
+ # for idx, d in enumerate(data_train):
1226
+ # if len(d['issues']) == 0:
1227
+ # zero_events_idxes.append(idx)
1228
+
1229
+ # n_zero_events_samples = len(zero_events_idxes)
1230
+ # n_has_events_samples = len(data_train) - n_zero_events_samples
1231
+
1232
+ # random.seed(42)
1233
+ # k = min(int(n_has_events_samples * zero_events_rate), len(zero_events_idxes))
1234
+ # sampled_zero_events_idxes = random.sample(zero_events_idxes, k)
1235
+
1236
+ # new_data_train = []
1237
+ # for idx, d in enumerate(data_train):
1238
+ # if len(d['issues']) == 0:
1239
+ # if idx in sampled_zero_events_idxes:
1240
+ # new_data_train.append(d)
1241
+ # else:
1242
+ # new_data_train.append(d)
1243
+ # data_train = new_data_train
1244
+
1245
+ # print('Train:', len(data_train))
1246
+
1247
+ # %% [code]
1248
+ if debug_only:
1249
+ data_train = data_train[:20]
1250
+ data_test = data_test[:20]
1251
+
1252
+ print('Train:', len(data_train))
1253
+ print('Test:', len(data_test))
1254
+
1255
+ # %% [code]
1256
+ tokenizer = AutoTokenizer.from_pretrained(backbone_model_name)
1257
+
1258
+ # %% [code]
1259
+ print('Experiment name:', state_dict_save_name)
1260
+
1261
+ # %% [code]
1262
+ if not test_only:
1263
+ full_idxes = np.array(range(len(data_train)))
1264
+ training_logs, best_models, last_models = [], [], []
1265
+ start_training_time = time.time()
1266
+ for seed in SEEDS:
1267
+ kf = KFold(n_splits=nfolds, shuffle=True, random_state=seed)
1268
+ generator = torch.Generator()
1269
+ generator.manual_seed(seed)
1270
+
1271
+ corpusset = CorpusDataset(data_corpus, tokenizer, **corpus_memory_params)
1272
+ corpus_loader = DataLoader(corpusset, generator=generator, **val_loader_params)
1273
+ for fold_idx, (tr_idx, va_idx) in enumerate(kf.split(full_idxes)):
1274
+ if only_fold_idx is not None and only_fold_idx >= 0 and only_fold_idx != fold_idx:
1275
+ continue
1276
+ set_seed(seed)
1277
+
1278
+ train_idxes, val_idxes = full_idxes[tr_idx], full_idxes[va_idx]
1279
+
1280
+ trainset = LawRetrievalDataset(data_train, train_idxes, data_corpus, tokenizer, **train_memory_params)
1281
+ valset = LawRetrievalDataset(data_train, val_idxes, data_corpus, tokenizer, **val_memory_params)
1282
+
1283
+ train_loader = DataLoader(trainset, generator=generator, collate_fn=collate_fn, **train_loader_params)
1284
+ val_loader = DataLoader(valset, generator=generator, collate_fn=collate_fn, **val_loader_params)
1285
+
1286
+ my_model = EncodeModel(
1287
+ **model_params
1288
+ )
1289
+ total_params = sum(p.numel() for p in my_model.parameters())
1290
+ print(f"Total params: {total_params:,}")
1291
+
1292
+ # optimizer, scheduler = configure_optimizers(my_model, optim_params, scheduler_params)
1293
+ encoder_params = set(map(id, my_model.encoder.parameters()))
1294
+ other_params = [
1295
+ p for p in my_model.parameters()
1296
+ if id(p) not in encoder_params
1297
+ ]
1298
+ optimizer = optim.AdamW([
1299
+ {"params": my_model.encoder.parameters(), "lr": 2e-5},
1300
+ {"params": other_params}
1301
+ ], lr=5e-4)
1302
+ scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=20, eta_min=1e-6)
1303
+
1304
+ loss_fn = CustomLoss(
1305
+ **loss_func_params
1306
+ )
1307
+ eval_fn = CustomEvalFn(**eval_func_params)
1308
+ trainer_params['save_name'] = f'{state_dict_save_name}_s{seed}_f{fold_idx}'
1309
+ trainer = Trainer(**trainer_params)
1310
+
1311
+ print(f'Start Training Fold {fold_idx}...')
1312
+ training_log, best_model, last_model = trainer.fit(
1313
+ my_model, optimizer, scheduler, loss_fn, epochs, train_loader, val_loader, corpus_loader, eval_fn,
1314
+ start_epoch=1, start_training_time=start_training_time, refresh_every=2,
1315
+ )
1316
+
1317
+ training_logs.append(training_log)
1318
+ best_models.append(best_model)
1319
+ last_models.append(last_model)
1320
+
1321
+ # %% [code]
1322
+ def load_all_state_dicts(folder):
1323
+ files = []
1324
+
1325
+ for file in os.listdir(folder):
1326
+ if file.endswith(".pt") or file.endswith(".pth"):
1327
+ m = re.search(r"f(\d+)", file) # tìm f<số>
1328
+ if m:
1329
+ fold = int(m.group(1))
1330
+ files.append((fold, file))
1331
+
1332
+ # sort theo fold
1333
+ files.sort(key=lambda x: x[0])
1334
+
1335
+ state_dicts = []
1336
+ for fold, file in files:
1337
+ path = os.path.join(folder, file)
1338
+ print(f"Loading fold {fold}: {file}")
1339
+ state_dict = torch.load(path, map_location="cpu")
1340
+ state_dicts.append(state_dict)
1341
+
1342
+ return state_dicts
1343
+
1344
+ if test_only:
1345
+ snapshot_download(repo_id=repo_name, local_dir="", repo_type="model", allow_patterns=[f"{state_dict_save_name}/**"])
1346
+ get_ipython().system('rm -rf .cache .gitattributes')
1347
+
1348
+ best_models = load_all_state_dicts(f"{state_dict_save_name}/r1s")
1349
+ last_models = load_all_state_dicts(f"{state_dict_save_name}/lasts")
1350
+
1351
+ # %% [code]
1352
+ os.makedirs(f'{checkpoints_dir}/results', exist_ok=True)
1353
+ testset = LawRetrievalDataset(data_test, range(len(data_test)), data_corpus, tokenizer, **val_memory_params)
1354
+ generator = torch.Generator()
1355
+ test_loader = DataLoader(testset, generator=generator, collate_fn=collate_fn, **val_loader_params)
1356
+ eval_fn = CustomEvalFn(**eval_func_params)
1357
+ my_model = EncodeModel(
1358
+ **model_params
1359
+ )
1360
+ total_params = sum(p.numel() for p in my_model.parameters())
1361
+ print(f"Total params: {total_params:,}")
1362
+
1363
+ # %% [code]
1364
+ start_time = time.time()
1365
+ encoded_docs = encode_corpus(best_models, my_model, corpus_loader, device)
1366
+ best_score = test(best_models, my_model, test_loader, device, eval_fn, encoded_docs, bm25_scores)
1367
+
1368
+ encoded_docs = encode_corpus(last_models, my_model, corpus_loader, device)
1369
+ last_score = test(last_models, my_model, test_loader, device, eval_fn, encoded_docs, bm25_scores)
1370
+
1371
+ result_test = {"Best model": best_score, "Last model": last_score}
1372
+
1373
+ with open(f"{checkpoints_dir}/results/{state_dict_save_name}_test.json", "w", encoding="utf-8") as f:
1374
+ json.dump(result_test, f, ensure_ascii=False, indent=2)
1375
+
1376
+ print('Test:', time.time() - start_time, 's --> Done!')
1377
+
1378
+ # %% [code]
1379
+ def dict_to_df(data):
1380
+ """
1381
+ data format:
1382
+ {
1383
+ model_name: {
1384
+ weight: {
1385
+ topk: {
1386
+ metric: value
1387
+ }
1388
+ }
1389
+ }
1390
+ }
1391
+ """
1392
+
1393
+ row_tuples = []
1394
+ row_values = []
1395
+
1396
+ # ===== lấy model đầu tiên =====
1397
+ first_model = next(iter(data.values()))
1398
+
1399
+ # ===== weight keys =====
1400
+ weight_keys = list(first_model.keys())
1401
+
1402
+ # ===== topk keys =====
1403
+ first_weight = next(iter(first_model.values()))
1404
+ topk_keys = list(first_weight.keys())
1405
+
1406
+ # ===== metric keys =====
1407
+ first_topk = next(iter(first_weight.values()))
1408
+ metrics = list(first_topk.keys())
1409
+
1410
+ for weight in weight_keys:
1411
+
1412
+ for topk in topk_keys:
1413
+
1414
+ # ===== multi index row =====
1415
+ row_tuples.append((weight, topk))
1416
+
1417
+ row = {}
1418
+
1419
+ for model_name, model_data in data.items():
1420
+
1421
+ for metric in metrics:
1422
+
1423
+ row[(model_name, metric)] = (
1424
+ model_data[weight][topk][metric]
1425
+ )
1426
+
1427
+ row_values.append(row)
1428
+
1429
+ # ===== dataframe =====
1430
+ df = pd.DataFrame(row_values)
1431
+
1432
+ # ===== multi columns =====
1433
+ df.columns = pd.MultiIndex.from_tuples(
1434
+ df.columns,
1435
+ names=["model", "metric"]
1436
+ )
1437
+
1438
+ # ===== multi index =====
1439
+ df.index = pd.MultiIndex.from_tuples(
1440
+ row_tuples,
1441
+ names=["weight", "topk"]
1442
+ )
1443
+
1444
+ return df
1445
+
1446
+ result_test_df = dict_to_df(result_test)
1447
+ result_test_df.to_excel(f"{checkpoints_dir}/results/{state_dict_save_name}_test_df.xlsx")
1448
+ result_test_df
1449
+
1450
+ # %% [code]
1451
+ key = ("Best model", "recall")
1452
+
1453
+ result_test_df_best = (
1454
+ result_test_df
1455
+ .sort_values(by=key, ascending=False)
1456
+ .groupby(level="weight")
1457
+ .head(1)
1458
+ )
1459
+ result_test_df_best.to_excel(f"{checkpoints_dir}/results/{state_dict_save_name}_test_df_best.xlsx")
1460
+ result_test_df_best
1461
+
1462
+ # %% [code]
1463
+ def get_avg_best_score(logs):
1464
+ return float(np.mean([list(log.values())[-1]['best_score'] for log in logs]))
1465
+
1466
+ def get_avg_log(logs, epochs):
1467
+ avg_log = {}
1468
+
1469
+ for epoch in range(1, epochs + 1):
1470
+ val_score = 0.0
1471
+ train_loss = 0.0
1472
+ n_eval = 0
1473
+
1474
+ for idx in range(len(logs)):
1475
+ log = logs[idx].get(epoch, logs[idx].get(str(epoch)))
1476
+ if log is None:
1477
+ continue
1478
+
1479
+ val_score += log.get('val_score', 0.0)
1480
+ train_loss += log.get('train_loss', 0.0)
1481
+ n_eval += 1
1482
+
1483
+ if n_eval == 0:
1484
+ continue
1485
+
1486
+ avg_log[epoch] = {
1487
+ 'train_loss': train_loss / n_eval,
1488
+ 'val_score': val_score / n_eval if val_score != 0 else float('inf')
1489
+ }
1490
+
1491
+ return avg_log
1492
+
1493
+ def parse_label_key(label: str):
1494
+ try:
1495
+ first = float(label.split('_', 1)[0]) # số đầu: trước dấu _
1496
+ last = float(re.findall(r'_(\d+(?:\.\d+)?)$', label)[0])
1497
+ return first, last
1498
+ except:
1499
+ return (0, 0)
1500
+
1501
+ def plot_training_logs(logs_dict, save_path=None, figsize=(24, 10)):
1502
+ fig, axes = plt.subplots(1, 2, figsize=figsize)
1503
+
1504
+ # ===== Plot Train Loss =====
1505
+ for name, log in logs_dict.items():
1506
+ epochs = sorted(log.keys())
1507
+ train_loss = [log[e]['train_loss'] for e in epochs]
1508
+ axes[0].plot(epochs, train_loss, label=name)
1509
+
1510
+ axes[0].set_xlabel('Epoch')
1511
+ axes[0].set_ylabel('Train Loss')
1512
+ axes[0].set_title('Training Loss')
1513
+ axes[0].grid(True)
1514
+
1515
+ # ===== Plot Validation Score =====
1516
+ for name, log in logs_dict.items():
1517
+ epochs = sorted(log.keys())
1518
+ val_score = [log[e]['val_score'] for e in epochs]
1519
+ axes[1].plot(epochs, val_score, label=name)
1520
+
1521
+ axes[1].set_xlabel('Epoch')
1522
+ axes[1].set_ylabel('Validation Score')
1523
+ axes[1].set_title('Validation Score')
1524
+ axes[1].grid(True)
1525
+
1526
+ # ===== Shared Legend =====
1527
+ handles, labels = axes[0].get_legend_handles_labels()
1528
+ pairs = list(zip(handles, labels))
1529
+ pairs_sorted = sorted(
1530
+ pairs,
1531
+ key=lambda x: parse_label_key(x[1])
1532
+ )
1533
+ handles_sorted, labels_sorted = zip(*pairs_sorted)
1534
+
1535
+ axes[0].legend(
1536
+ handles_sorted,
1537
+ labels_sorted,
1538
+ loc='center left',
1539
+ bbox_to_anchor=(1.01, 0.5),
1540
+ borderaxespad=0.
1541
+ )
1542
+
1543
+ plt.tight_layout(rect=[0, 0, 1, 1])
1544
+
1545
+ if save_path is not None:
1546
+ os.makedirs(os.path.dirname(save_path), exist_ok=True) if os.path.dirname(save_path) else None
1547
+ plt.savefig(save_path, dpi=300, bbox_inches='tight')
1548
+
1549
+ plt.show()
1550
+
1551
+ # %% [code]
1552
+ if not test_only:
1553
+ snapshot_download(repo_id=repo_name, local_dir="", repo_type="model", allow_patterns=["**/*lr*.json"], ignore_patterns=[])
1554
+ get_ipython().system('rm -rf .cache .gitattributes')
1555
+
1556
+ # %% [code]
1557
+ if not test_only:
1558
+ experiments = {}
1559
+ for experiment in os.listdir(pretrained_dir):
1560
+ experiment_logs = []
1561
+ try:
1562
+ for seed in SEEDS:
1563
+ for fold_idx in range(nfolds):
1564
+ with open(f"{pretrained_dir}/{experiment}/logs/{experiment}_s{seed}_f{fold_idx}_logging.json", "r", encoding="utf-8") as f:
1565
+ experiment_log = json.load(f)
1566
+ experiment_logs.append(experiment_log)
1567
+ except:
1568
+ pass
1569
+ experiments[experiment] = get_avg_log(experiment_logs, 1000)
1570
+ experiments[state_dict_save_name] = get_avg_log(training_logs, 1000)
1571
+
1572
+ # %% [code]
1573
+ if not test_only:
1574
+ score = get_avg_best_score(training_logs)
1575
+ state_dict_save_name, score
1576
+
1577
+ # %% [code]
1578
+ if not test_only:
1579
+ plot_training_logs(experiments, save_path=f'{checkpoints_dir}/logs/{state_dict_save_name}_log_plot.jpg', figsize=(18, 7.5))
1580
+
10_lr_stronger_proj_residual_13/lasts/10_lr_stronger_proj_residual_13_s26092004_f0_last_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b87fe15834c00fd0c6dec33b963852a30ce6e84bee384d446a8563a8ac7036bc
3
+ size 544007119
10_lr_stronger_proj_residual_13/lasts/10_lr_stronger_proj_residual_13_s26092004_f1_last_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e1a9d6d83a929d0f149e3450bc519a17bc48523616fadd8149a359387db02035
3
+ size 544007119
10_lr_stronger_proj_residual_13/lasts/10_lr_stronger_proj_residual_13_s26092004_f2_last_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c5f8be1e0d8928c25a29f29ef9f1c8a05da511482a586bdd1ffbd7f9d8f906b2
3
+ size 544007119
10_lr_stronger_proj_residual_13/lasts/10_lr_stronger_proj_residual_13_s26092004_f3_last_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:54d37254a29aaffde4e332d466ac6cc9db1db1fea76ef0219346a1654c8d610a
3
+ size 544007119
10_lr_stronger_proj_residual_13/lasts/10_lr_stronger_proj_residual_13_s26092004_f4_last_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d530dc806e8438167046cf13460bf48554c54722e2107c95b13ec9873acaccf6
3
+ size 544007119
10_lr_stronger_proj_residual_13/logs/10_lr_stronger_proj_residual_13_log_plot.jpg ADDED

Git LFS Details

  • SHA256: 9b81cb61bb3d3e49b711ac5931b8c70159e0ff88c4506554482c91fee2a786c4
  • Pointer size: 131 Bytes
  • Size of remote file: 506 kB
10_lr_stronger_proj_residual_13/logs/10_lr_stronger_proj_residual_13_s26092004_f0_logging.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"1": {"lr": [2e-05, 0.0005], "train_loss": 4.145429611206055, "total": 4.145429426212375, "contrastive_loss": 4.00333999072429, "triplet_loss": 0.27675585284280935}, "2": {"lr": [1.988303923565381e-05, 0.0004969282409784868], "train_loss": 3.859245538711548, "total": 3.859245580973035, "contrastive_loss": 3.7208215209552677, "triplet_loss": 0.26902173913043476}, "3": {"lr": [1.9535036904803962e-05, 0.0004877886008156408], "train_loss": 3.5366313457489014, "total": 3.5366313002978678, "contrastive_loss": 3.381754285117057, "triplet_loss": 0.30434782608695654}, "4": {"lr": [1.8964561979789496e-05, 0.00047280612778499774], "train_loss": 3.2698750495910645, "total": 3.2698750065321907, "contrastive_loss": 3.12320140213472, "triplet_loss": 0.28887959866220736}, "5": {"lr": [1.8185661446562005e-05, 0.00045234974009654937], "train_loss": 3.202012062072754, "total": 3.202012078020485, "contrastive_loss": 3.0586629503945444, "triplet_loss": 0.28135451505016723}, "6": {"lr": [1.7217514421272206e-05, 0.00042692314190604356], "train_loss": 3.021655321121216, "total": 3.0216552326113084, "contrastive_loss": 2.884752968880644, "triplet_loss": 0.2686036789297659}, "7": {"lr": [1.60839598967785e-05, 0.00039715242044697206], "train_loss": 2.98689341545105, "total": 2.986893363620924, "contrastive_loss": 2.842639323461016, "triplet_loss": 0.2834448160535117}, "8": {"lr": [1.4812909747525698e-05, 0.00036377062968501693], "train_loss": 2.7287185192108154, "total": 2.7287185311716136, "contrastive_loss": 2.595887455254494, "triplet_loss": 0.2625418060200669, "val_score": 0.8235714285714286, "best_score": 0.8235714285714286, "new_best_model": true, "recall": 0.8235714285714286, "mAP": 0.3108857997134038, "mRP": 0.29549702380952386}, "9": {"lr": [1.3435661446562005e-05, 0.0003275997400965494], "train_loss": 2.6041438579559326, "total": 2.6041439400867477, "contrastive_loss": 2.4747900308972617, "triplet_loss": 0.25752508361204013, "val_score": 0.8205357142857143, "best_score": 0.8235714285714286, "new_best_model": false, "recall": 0.8205357142857143, "mAP": 0.30933445353835987, "mRP": 0.2930381944444444}, "10": {"lr": [1.1986127417882198e-05, 0.00028953039902753766], "train_loss": 2.4432828426361084, "total": 2.4432828258909907, "contrastive_loss": 2.321354792668269, "triplet_loss": 0.24581939799331104, "val_score": 0.8233928571428571, "best_score": 0.8235714285714286, "new_best_model": false, "recall": 0.8233928571428571, "mAP": 0.3184810198963845, "mRP": 0.30379017857142854}, "11": {"lr": [1.0500000000000003e-05, 0.0002505], "train_loss": 2.3835103511810303, "total": 2.3835104237432065, "contrastive_loss": 2.2629333291962794, "triplet_loss": 0.2431020066889632, "val_score": 0.8140178571428571, "best_score": 0.8235714285714286, "new_best_model": false, "recall": 0.8140178571428571, "mAP": 0.30825443456317686, "mRP": 0.2948249007936507}, "12": {"lr": [9.013872582117811e-06, 0.00021146960097246246], "train_loss": 2.2508702278137207, "total": 2.2508702102712164, "contrastive_loss": 2.1369647278036163, "triplet_loss": 0.2295150501672241, "val_score": 0.8127678571428572, "best_score": 0.8235714285714286, "new_best_model": false, "recall": 0.8127678571428572, "mAP": 0.31363872767857126, "mRP": 0.3000679563492063}, "13": {"lr": [7.564338553438001e-06, 0.00017340025990345064], "train_loss": 2.235497236251831, "total": 2.2354973120035537, "contrastive_loss": 2.1211860171927257, "triplet_loss": 0.23076923076923078, "val_score": 0.79375, "best_score": 0.8235714285714286, "new_best_model": false, "recall": 0.79375, "mAP": 0.303561753196649, "mRP": 0.2928412698412698}, "14": {"lr": [6.1870902524743065e-06, 0.00013722937031498307], "train_loss": 2.1296486854553223, "total": 2.1296486742919107, "contrastive_loss": 2.021195733826296, "triplet_loss": 0.21697324414715718, "val_score": 0.7975, "best_score": 0.8235714285714286, "new_best_model": false, "recall": 0.7975, "mAP": 0.3078302124669312, "mRP": 0.29773115079365076}, "15": {"lr": [4.916040103221507e-06, 0.00010384757955302797], "train_loss": 2.1487159729003906, "total": 2.148715934625836, "contrastive_loss": 2.0385887120479724, "triplet_loss": 0.22073578595317725, "val_score": 0.7814583333333334, "best_score": 0.8235714285714286, "new_best_model": false, "recall": 0.7814583333333334, "mAP": 0.29814687362213416, "mRP": 0.28732043650793654}, "16": {"lr": [3.7824855787278e-06, 7.40768580939564e-05], "train_loss": 2.06742525100708, "total": 2.0674252717391304, "contrastive_loss": 1.9617278950668897, "triplet_loss": 0.21038879598662208, "val_score": 0.7845833333333333, "best_score": 0.8235714285714286, "new_best_model": false, "recall": 0.7845833333333333, "mAP": 0.3026944155092593, "mRP": 0.2920853174603174}, "17": {"lr": [2.814338553438001e-06, 4.865025990345063e-05], "train_loss": 2.1165573596954346, "total": 2.1165573477346364, "contrastive_loss": 2.0081932042354724, "triplet_loss": 0.2165551839464883, "val_score": 0.7635416666666667, "best_score": 0.8235714285714286, "new_best_model": false, "recall": 0.7635416666666667, "mAP": 0.2912430500440917, "mRP": 0.279702380952381}, "18": {"lr": [2.0354380202105066e-06, 2.8193872215002235e-05], "train_loss": 2.0645885467529297, "total": 2.064588463824728, "contrastive_loss": 1.9589811089046822, "triplet_loss": 0.21038879598662208, "val_score": 0.7647916666666666, "best_score": 0.8235714285714286, "new_best_model": false, "recall": 0.7647916666666666, "mAP": 0.2939198936287478, "mRP": 0.28382738095238097}}
10_lr_stronger_proj_residual_13/logs/10_lr_stronger_proj_residual_13_s26092004_f1_logging.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"1": {"lr": [2e-05, 0.0005], "train_loss": 4.158390522003174, "total": 4.158390517218854, "contrastive_loss": 4.015885471101589, "triplet_loss": 0.27842809364548493}, "2": {"lr": [1.988303923565381e-05, 0.0004969282409784868], "train_loss": 3.873318672180176, "total": 3.8733187774352005, "contrastive_loss": 3.734584846624164, "triplet_loss": 0.26985785953177255}, "3": {"lr": [1.9535036904803962e-05, 0.0004877886008156408], "train_loss": 3.558519124984741, "total": 3.558519038069607, "contrastive_loss": 3.4037077530570654, "triplet_loss": 0.3056020066889632}, "4": {"lr": [1.8964561979789496e-05, 0.00047280612778499774], "train_loss": 3.299396276473999, "total": 3.299396221454327, "contrastive_loss": 3.152362530048077, "triplet_loss": 0.2878344481605351}, "5": {"lr": [1.8185661446562005e-05, 0.00045234974009654937], "train_loss": 3.233830213546753, "total": 3.2338301744748117, "contrastive_loss": 3.0897235168661163, "triplet_loss": 0.28198160535117056}, "6": {"lr": [1.7217514421272206e-05, 0.00042692314190604356], "train_loss": 3.0507678985595703, "total": 3.050767981487772, "contrastive_loss": 2.9133376309704224, "triplet_loss": 0.26881270903010035}, "7": {"lr": [1.60839598967785e-05, 0.00039715242044697206], "train_loss": 2.995413064956665, "total": 2.9954131773881687, "contrastive_loss": 2.8508925421979514, "triplet_loss": 0.28490802675585286}, "8": {"lr": [1.4812909747525698e-05, 0.00036377062968501693], "train_loss": 2.743196725845337, "total": 2.743196723453177, "contrastive_loss": 2.610037813218541, "triplet_loss": 0.2633779264214047, "val_score": 0.825448717948718, "best_score": 0.825448717948718, "new_best_model": true, "recall": 0.825448717948718, "mAP": 0.3165253713878713, "mRP": 0.30048237179487175}, "9": {"lr": [1.3435661446562005e-05, 0.0003275997400965494], "train_loss": 2.624695062637329, "total": 2.6246950283497075, "contrastive_loss": 2.494343122909699, "triplet_loss": 0.2585702341137124, "val_score": 0.8258653846153846, "best_score": 0.8258653846153846, "new_best_model": true, "recall": 0.8258653846153846, "mAP": 0.31730821451889163, "mRP": 0.3023608440170938}, "10": {"lr": [1.1986127417882198e-05, 0.00028953039902753766], "train_loss": 2.453923225402832, "total": 2.453923152043269, "contrastive_loss": 2.3314337586878136, "triplet_loss": 0.24623745819397994, "val_score": 0.8375320512820513, "best_score": 0.8375320512820513, "new_best_model": true, "recall": 0.8375320512820513, "mAP": 0.32376615653829205, "mRP": 0.30886431623931626}, "11": {"lr": [1.0500000000000003e-05, 0.0002505], "train_loss": 2.394611358642578, "total": 2.394611269335284, "contrastive_loss": 2.2736375483382107, "triplet_loss": 0.24331103678929766, "val_score": 0.8214903846153846, "best_score": 0.8375320512820513, "new_best_model": false, "recall": 0.8214903846153846, "mAP": 0.3155502404906049, "mRP": 0.3007711004273505}, "12": {"lr": [9.013872582117811e-06, 0.00021146960097246246], "train_loss": 2.263634204864502, "total": 2.2636343149038463, "contrastive_loss": 2.149451826727111, "triplet_loss": 0.22888795986622074, "val_score": 0.8256570512820512, "best_score": 0.8375320512820513, "new_best_model": false, "recall": 0.8256570512820512, "mAP": 0.3214920319071363, "mRP": 0.3047414529914529}, "13": {"lr": [7.564338553438001e-06, 0.00017340025990345064], "train_loss": 2.239743947982788, "total": 2.2397440524404266, "contrastive_loss": 2.1259510461303304, "triplet_loss": 0.22867892976588627, "val_score": 0.809198717948718, "best_score": 0.8375320512820513, "new_best_model": false, "recall": 0.809198717948718, "mAP": 0.31089047343474424, "mRP": 0.2944220085470087}, "14": {"lr": [6.1870902524743065e-06, 0.00013722937031498307], "train_loss": 2.138727903366089, "total": 2.1387280110132734, "contrastive_loss": 2.030267721833194, "triplet_loss": 0.21697324414715718, "val_score": 0.8121153846153846, "best_score": 0.8375320512820513, "new_best_model": false, "recall": 0.8121153846153846, "mAP": 0.31304552352547144, "mRP": 0.2968699252136752}, "15": {"lr": [4.916040103221507e-06, 0.00010384757955302797], "train_loss": 2.1542277336120605, "total": 2.1542276746054556, "contrastive_loss": 2.044357657033863, "triplet_loss": 0.22052675585284282, "val_score": 0.7955448717948719, "best_score": 0.8375320512820513, "new_best_model": false, "recall": 0.7955448717948719, "mAP": 0.30363663035459915, "mRP": 0.2889011752136753}, "16": {"lr": [3.7824855787278e-06, 7.40768580939564e-05], "train_loss": 2.070699691772461, "total": 2.070699736426108, "contrastive_loss": 1.9653061066184156, "triplet_loss": 0.20944816053511706, "val_score": 0.795352564102564, "best_score": 0.8375320512820513, "new_best_model": false, "recall": 0.795352564102564, "mAP": 0.3055265545507733, "mRP": 0.2907483974358975}, "17": {"lr": [2.814338553438001e-06, 4.865025990345063e-05], "train_loss": 2.1172561645507812, "total": 2.1172560880016724, "contrastive_loss": 2.0093277640964673, "triplet_loss": 0.21467391304347827, "val_score": 0.7783814102564102, "best_score": 0.8375320512820513, "new_best_model": false, "recall": 0.7783814102564102, "mAP": 0.29267228094051023, "mRP": 0.2768838141025642}, "18": {"lr": [2.0354380202105066e-06, 2.8193872215002235e-05], "train_loss": 2.0704994201660156, "total": 2.0704994839569397, "contrastive_loss": 1.964900294275188, "triplet_loss": 0.21038879598662208, "val_score": 0.7790064102564103, "best_score": 0.8375320512820513, "new_best_model": false, "recall": 0.7790064102564103, "mAP": 0.29579151965896744, "mRP": 0.2818664529914529}}
10_lr_stronger_proj_residual_13/logs/10_lr_stronger_proj_residual_13_s26092004_f2_logging.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"1": {"lr": [2e-05, 0.0005], "train_loss": 4.154318809509277, "total": 4.154318921143394, "contrastive_loss": 4.011807751097408, "triplet_loss": 0.27738294314381273}, "2": {"lr": [1.988303923565381e-05, 0.0004969282409784868], "train_loss": 3.888183116912842, "total": 3.8881831854880855, "contrastive_loss": 3.749492938701923, "triplet_loss": 0.270066889632107}, "3": {"lr": [1.9535036904803962e-05, 0.0004877886008156408], "train_loss": 3.6018168926239014, "total": 3.6018168471728678, "contrastive_loss": 3.446857363085284, "triplet_loss": 0.30434782608695654}, "4": {"lr": [1.8964561979789496e-05, 0.00047280612778499774], "train_loss": 3.366429090499878, "total": 3.3664291534934154, "contrastive_loss": 3.218914733682588, "triplet_loss": 0.2907608695652174}, "5": {"lr": [1.8185661446562005e-05, 0.00045234974009654937], "train_loss": 3.2855963706970215, "total": 3.2855963563440636, "contrastive_loss": 3.1401312072141514, "triplet_loss": 0.2842809364548495}, "6": {"lr": [1.7217514421272206e-05, 0.00042692314190604356], "train_loss": 3.126793146133423, "total": 3.126793290460389, "contrastive_loss": 2.9868492713341346, "triplet_loss": 0.27320234113712377}, "7": {"lr": [1.60839598967785e-05, 0.00039715242044697206], "train_loss": 3.083911180496216, "total": 3.0839110919863084, "contrastive_loss": 2.93687188904421, "triplet_loss": 0.28741638795986624}, "8": {"lr": [1.4812909747525698e-05, 0.00036377062968501693], "train_loss": 2.8431122303009033, "total": 2.843112294889214, "contrastive_loss": 2.7066327863712374, "triplet_loss": 0.2686036789297659, "val_score": 0.835224358974359, "best_score": 0.835224358974359, "new_best_model": true, "recall": 0.835224358974359, "mAP": 0.30922157960673585, "mRP": 0.2940494123931623}, "9": {"lr": [1.3435661446562005e-05, 0.0003275997400965494], "train_loss": 2.729926586151123, "total": 2.7299265781772575, "contrastive_loss": 2.596061374830163, "triplet_loss": 0.2648411371237458, "val_score": 0.836474358974359, "best_score": 0.836474358974359, "new_best_model": true, "recall": 0.836474358974359, "mAP": 0.3061380852750645, "mRP": 0.29153899572649566}, "10": {"lr": [1.1986127417882198e-05, 0.00028953039902753766], "train_loss": 2.564657688140869, "total": 2.5646576642192724, "contrastive_loss": 2.438374905283236, "triplet_loss": 0.25188127090301005, "val_score": 0.8425160256410256, "best_score": 0.8425160256410256, "new_best_model": true, "recall": 0.8425160256410256, "mAP": 0.3165927196742304, "mRP": 0.30285496794871775}, "11": {"lr": [1.0500000000000003e-05, 0.0002505], "train_loss": 2.5012683868408203, "total": 2.501268469769022, "contrastive_loss": 2.376407891212897, "triplet_loss": 0.25020903010033446, "val_score": 0.8337660256410256, "best_score": 0.8425160256410256, "new_best_model": false, "recall": 0.8337660256410256, "mAP": 0.30824143560914397, "mRP": 0.2961193910256409}, "12": {"lr": [9.013872582117811e-06, 0.00021146960097246246], "train_loss": 2.36021089553833, "total": 2.3602109162703804, "contrastive_loss": 2.2422070965719065, "triplet_loss": 0.23704013377926422, "val_score": 0.8354326923076922, "best_score": 0.8425160256410256, "new_best_model": false, "recall": 0.8354326923076922, "mAP": 0.3155852586360401, "mRP": 0.302775641025641}, "13": {"lr": [7.564338553438001e-06, 0.00017340025990345064], "train_loss": 2.3421690464019775, "total": 2.3421690057352635, "contrastive_loss": 2.2239304354358276, "triplet_loss": 0.23975752508361203, "val_score": 0.8168910256410256, "best_score": 0.8425160256410256, "new_best_model": false, "recall": 0.8168910256410256, "mAP": 0.303258977538665, "mRP": 0.2909527243589744}, "14": {"lr": [6.1870902524743065e-06, 0.00013722937031498307], "train_loss": 2.2301785945892334, "total": 2.2301786799095944, "contrastive_loss": 2.1177502890494355, "triplet_loss": 0.225752508361204, "val_score": 0.8160576923076923, "best_score": 0.8425160256410256, "new_best_model": false, "recall": 0.8160576923076923, "mAP": 0.30728897558845447, "mRP": 0.2964647435897435}, "15": {"lr": [4.916040103221507e-06, 0.00010384757955302797], "train_loss": 2.2528560161590576, "total": 2.252855996224394, "contrastive_loss": 2.1388990727555393, "triplet_loss": 0.22972408026755853, "val_score": 0.7973076923076923, "best_score": 0.8425160256410256, "new_best_model": false, "recall": 0.7973076923076923, "mAP": 0.29644037973985876, "mRP": 0.28636057692307687}, "16": {"lr": [3.7824855787278e-06, 7.40768580939564e-05], "train_loss": 2.167875051498413, "total": 2.167875053890573, "contrastive_loss": 2.0583208269100126, "triplet_loss": 0.21969063545150502, "val_score": 0.7950160256410256, "best_score": 0.8425160256410256, "new_best_model": false, "recall": 0.7950160256410256, "mAP": 0.29959033956976633, "mRP": 0.2883432158119657}, "17": {"lr": [2.814338553438001e-06, 4.865025990345063e-05], "train_loss": 2.225755214691162, "total": 2.2257551620636495, "contrastive_loss": 2.1129723998615177, "triplet_loss": 0.2261705685618729, "val_score": 0.7792948717948718, "best_score": 0.8425160256410256, "new_best_model": false, "recall": 0.7792948717948718, "mAP": 0.2873165437186272, "mRP": 0.2756869658119658}, "18": {"lr": [2.0354380202105066e-06, 2.8193872215002235e-05], "train_loss": 2.1707570552825928, "total": 2.1707571788775084, "contrastive_loss": 2.0610296447141514, "triplet_loss": 0.22031772575250835, "val_score": 0.7797115384615385, "best_score": 0.8425160256410256, "new_best_model": false, "recall": 0.7797115384615385, "mAP": 0.28991634021842355, "mRP": 0.27686752136752135}}
10_lr_stronger_proj_residual_13/logs/10_lr_stronger_proj_residual_13_s26092004_f3_logging.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"1": {"lr": [2e-05, 0.0005], "train_loss": 4.15660285949707, "total": 4.156602738294314, "contrastive_loss": 4.014333667563754, "triplet_loss": 0.2778010033444816}, "2": {"lr": [1.988303923565381e-05, 0.0004969282409784868], "train_loss": 3.872333526611328, "total": 3.8723336414349916, "contrastive_loss": 3.733600527147784, "triplet_loss": 0.2709030100334448}, "3": {"lr": [1.9535036904803962e-05, 0.0004877886008156408], "train_loss": 3.6046721935272217, "total": 3.6046722310043897, "contrastive_loss": 3.44949146895903, "triplet_loss": 0.30434782608695654}, "4": {"lr": [1.8964561979789496e-05, 0.00047280612778499774], "train_loss": 3.3840694427490234, "total": 3.38406953843541, "contrastive_loss": 3.236085005029787, "triplet_loss": 0.292433110367893}, "5": {"lr": [1.8185661446562005e-05, 0.00045234974009654937], "train_loss": 3.3172504901885986, "total": 3.3172505356396322, "contrastive_loss": 3.172392267845945, "triplet_loss": 0.2834448160535117}, "6": {"lr": [1.7217514421272206e-05, 0.00042692314190604356], "train_loss": 3.162350654602051, "total": 3.162350657791597, "contrastive_loss": 3.0226813989339463, "triplet_loss": 0.2725752508361204}, "7": {"lr": [1.60839598967785e-05, 0.00039715242044697206], "train_loss": 3.126254081726074, "total": 3.1262541806020065, "contrastive_loss": 2.9782953676970108, "triplet_loss": 0.2899247491638796}, "8": {"lr": [1.4812909747525698e-05, 0.00036377062968501693], "train_loss": 2.8935835361480713, "total": 2.893583674095945, "contrastive_loss": 2.755797319188963, "triplet_loss": 0.27069397993311034, "val_score": 0.8159615384615385, "best_score": 0.8159615384615385, "new_best_model": true, "recall": 0.8159615384615385, "mAP": 0.30187092819410516, "mRP": 0.29090945512820504}, "9": {"lr": [1.3435661446562005e-05, 0.0003275997400965494], "train_loss": 2.7841227054595947, "total": 2.784122734962897, "contrastive_loss": 2.6488135092234533, "triplet_loss": 0.2665133779264214, "val_score": 0.8267948717948719, "best_score": 0.8267948717948719, "new_best_model": true, "recall": 0.8267948717948719, "mAP": 0.3082531341151133, "mRP": 0.29746287393162385}, "10": {"lr": [1.1986127417882198e-05, 0.00028953039902753766], "train_loss": 2.7226943969726562, "total": 2.7226944224890257, "contrastive_loss": 2.5909368712766514, "triplet_loss": 0.26045150501672243, "val_score": 0.8341826923076923, "best_score": 0.8341826923076923, "new_best_model": true, "recall": 0.8341826923076923, "mAP": 0.31279040591931206, "mRP": 0.3006284722222223}, "11": {"lr": [1.0500000000000003e-05, 0.0002505], "train_loss": 2.6066648960113525, "total": 2.6066649574101173, "contrastive_loss": 2.4785491024770065, "triplet_loss": 0.2554347826086957, "val_score": 0.8227243589743589, "best_score": 0.8341826923076923, "new_best_model": false, "recall": 0.8227243589743589, "mAP": 0.30624724013447974, "mRP": 0.29459962606837614}, "12": {"lr": [9.013872582117811e-06, 0.00021146960097246246], "train_loss": 2.4601757526397705, "total": 2.4601758873980977, "contrastive_loss": 2.33889188734584, "triplet_loss": 0.2435200668896321, "val_score": 0.8280288461538461, "best_score": 0.8341826923076923, "new_best_model": false, "recall": 0.8280288461538461, "mAP": 0.3144371017967372, "mRP": 0.30197489316239323}, "13": {"lr": [7.564338553438001e-06, 0.00017340025990345064], "train_loss": 2.453066349029541, "total": 2.4530664144152383, "contrastive_loss": 2.3307570645641724, "triplet_loss": 0.24581939799331104, "val_score": 0.8173076923076923, "best_score": 0.8341826923076923, "new_best_model": false, "recall": 0.8173076923076923, "mAP": 0.30715744354989144, "mRP": 0.29506196581196575}, "14": {"lr": [6.1870902524743065e-06, 0.00013722937031498307], "train_loss": 2.3466014862060547, "total": 2.346601505343332, "contrastive_loss": 2.2299310690583196, "triplet_loss": 0.23557692307692307, "val_score": 0.8189743589743589, "best_score": 0.8341826923076923, "new_best_model": false, "recall": 0.8189743589743589, "mAP": 0.3115978060134309, "mRP": 0.29943376068376065}, "15": {"lr": [4.916040103221507e-06, 0.00010384757955302797], "train_loss": 2.356600522994995, "total": 2.356600452027592, "contrastive_loss": 2.2384241416701505, "triplet_loss": 0.23808528428093645, "val_score": 0.8083493589743589, "best_score": 0.8341826923076923, "new_best_model": false, "recall": 0.8083493589743589, "mAP": 0.30094340288376736, "mRP": 0.2890694444444443}, "16": {"lr": [3.7824855787278e-06, 7.40768580939564e-05], "train_loss": 2.2753899097442627, "total": 2.275390012607128, "contrastive_loss": 2.1615265811167435, "triplet_loss": 0.23118729096989968, "val_score": 0.8084455128205128, "best_score": 0.8341826923076923, "new_best_model": false, "recall": 0.8084455128205128, "mAP": 0.3047777454509226, "mRP": 0.2926335470085468}, "17": {"lr": [2.814338553438001e-06, 4.865025990345063e-05], "train_loss": 2.3313212394714355, "total": 2.3313212825303093, "contrastive_loss": 2.2141327618755224, "triplet_loss": 0.23620401337792643, "val_score": 0.7944871794871795, "best_score": 0.8341826923076923, "new_best_model": false, "recall": 0.7944871794871795, "mAP": 0.2950905947929387, "mRP": 0.284588408119658}, "18": {"lr": [2.0354380202105066e-06, 2.8193872215002235e-05], "train_loss": 2.273970603942871, "total": 2.2739706900606187, "contrastive_loss": 2.159860055980874, "triplet_loss": 0.229933110367893, "val_score": 0.7925160256410256, "best_score": 0.8341826923076923, "new_best_model": false, "recall": 0.7925160256410256, "mAP": 0.29806496256444176, "mRP": 0.28811004273504237}}
10_lr_stronger_proj_residual_13/logs/10_lr_stronger_proj_residual_13_s26092004_f4_logging.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"1": {"lr": [2e-05, 0.0005], "train_loss": 4.155728816986084, "total": 4.155728649534908, "contrastive_loss": 4.012945168791806, "triplet_loss": 0.2786371237458194}, "2": {"lr": [1.988303923565381e-05, 0.0004969282409784868], "train_loss": 3.868417978286743, "total": 3.8684180014109533, "contrastive_loss": 3.7297775625783864, "triplet_loss": 0.270066889632107}, "3": {"lr": [1.9535036904803962e-05, 0.0004877886008156408], "train_loss": 3.563166618347168, "total": 3.563166691706731, "contrastive_loss": 3.407958371982128, "triplet_loss": 0.3060200668896321}, "4": {"lr": [1.8964561979789496e-05, 0.00047280612778499774], "train_loss": 3.3025853633880615, "total": 3.302585359401129, "contrastive_loss": 3.1554426620636495, "triplet_loss": 0.2890886287625418}, "5": {"lr": [1.8185661446562005e-05, 0.00045234974009654937], "train_loss": 3.2323150634765625, "total": 3.232315114509302, "contrastive_loss": 3.089735356461643, "triplet_loss": 0.2782190635451505}, "6": {"lr": [1.7217514421272206e-05, 0.00042692314190604356], "train_loss": 3.0665650367736816, "total": 3.0665650638848243, "contrastive_loss": 2.9295429752821907, "triplet_loss": 0.26714046822742477}, "7": {"lr": [1.60839598967785e-05, 0.00039715242044697206], "train_loss": 3.026472806930542, "total": 3.0264729273359112, "contrastive_loss": 2.8809298001802883, "triplet_loss": 0.28490802675585286}, "8": {"lr": [1.4812909747525698e-05, 0.00036377062968501693], "train_loss": 2.760653495788574, "total": 2.7606535946645065, "contrastive_loss": 2.626632027004076, "triplet_loss": 0.264005016722408, "val_score": 0.8119070512820513, "best_score": 0.8119070512820513, "new_best_model": true, "recall": 0.8119070512820513, "mAP": 0.30572950233601254, "mRP": 0.2975665064102564}, "9": {"lr": [1.3435661446562005e-05, 0.0003275997400965494], "train_loss": 2.6415860652923584, "total": 2.6415860485472407, "contrastive_loss": 2.5109791835414925, "triplet_loss": 0.2585702341137124, "val_score": 0.8131570512820513, "best_score": 0.8131570512820513, "new_best_model": true, "recall": 0.8131570512820513, "mAP": 0.3060176934947768, "mRP": 0.29690838675213665}, "10": {"lr": [1.1986127417882198e-05, 0.00028953039902753766], "train_loss": 2.474168539047241, "total": 2.474168452132107, "contrastive_loss": 2.3511334167276337, "triplet_loss": 0.24770066889632106, "val_score": 0.8162820512820513, "best_score": 0.8162820512820513, "new_best_model": true, "recall": 0.8162820512820513, "mAP": 0.31235471230158723, "mRP": 0.3014326923076922}, "11": {"lr": [1.0500000000000003e-05, 0.0002505], "train_loss": 2.4156785011291504, "total": 2.4156786047894023, "contrastive_loss": 2.2940324764187916, "triplet_loss": 0.24456521739130435, "val_score": 0.8030608974358974, "best_score": 0.8162820512820513, "new_best_model": false, "recall": 0.8030608974358974, "mAP": 0.30254342471764334, "mRP": 0.29227350427350435}, "12": {"lr": [9.013872582117811e-06, 0.00021146960097246246], "train_loss": 2.281367540359497, "total": 2.2813675794314383, "contrastive_loss": 2.1666302633126047, "triplet_loss": 0.23056020066889632, "val_score": 0.806073717948718, "best_score": 0.8162820512820513, "new_best_model": false, "recall": 0.806073717948718, "mAP": 0.3082999107566816, "mRP": 0.29824839743589737}, "13": {"lr": [7.564338553438001e-06, 0.00017340025990345064], "train_loss": 2.266057014465332, "total": 2.2660571452367266, "contrastive_loss": 2.1509960774195234, "triplet_loss": 0.23056020066889632, "val_score": 0.7911858974358974, "best_score": 0.8162820512820513, "new_best_model": false, "recall": 0.7911858974358974, "mAP": 0.29814420808743725, "mRP": 0.2879949252136751}, "14": {"lr": [6.1870902524743065e-06, 0.00013722937031498307], "train_loss": 2.156344175338745, "total": 2.156344104371342, "contrastive_loss": 2.047168744447638, "triplet_loss": 0.21760033444816054, "val_score": 0.7934775641025641, "best_score": 0.8162820512820513, "new_best_model": false, "recall": 0.7934775641025641, "mAP": 0.3014215338191899, "mRP": 0.29143242521367524}, "15": {"lr": [4.916040103221507e-06, 0.00010384757955302797], "train_loss": 2.1817023754119873, "total": 2.1817024766800794, "contrastive_loss": 2.0707942490593645, "triplet_loss": 0.2221989966555184, "val_score": 0.7693108974358974, "best_score": 0.8162820512820513, "new_best_model": false, "recall": 0.7693108974358974, "mAP": 0.2882290863264824, "mRP": 0.27708440170940174}, "16": {"lr": [3.7824855787278e-06, 7.40768580939564e-05], "train_loss": 2.098397731781006, "total": 2.098397653637124, "contrastive_loss": 1.9921381003083194, "triplet_loss": 0.2125836120401338, "val_score": 0.7707692307692308, "best_score": 0.8162820512820513, "new_best_model": false, "recall": 0.7707692307692308, "mAP": 0.2923930383852259, "mRP": 0.28147329059829057}, "17": {"lr": [2.814338553438001e-06, 4.865025990345063e-05], "train_loss": 2.155325412750244, "total": 2.155325490894126, "contrastive_loss": 2.0453946422972407, "triplet_loss": 0.22010869565217392, "val_score": 0.7562980769230769, "best_score": 0.8162820512820513, "new_best_model": false, "recall": 0.7562980769230769, "mAP": 0.28127208220984246, "mRP": 0.26910416666666664}, "18": {"lr": [2.0354380202105066e-06, 2.8193872215002235e-05], "train_loss": 2.1031365394592285, "total": 2.1031365538121864, "contrastive_loss": 1.9963376864940428, "triplet_loss": 0.2130016722408027, "val_score": 0.7567147435897436, "best_score": 0.8162820512820513, "new_best_model": false, "recall": 0.7567147435897436, "mAP": 0.2855126345009157, "mRP": 0.27448584401709397}}
10_lr_stronger_proj_residual_13/r1s/10_lr_stronger_proj_residual_13_s26092004_f0_r1_vs0.82357_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b45edd337cf99aa89c963c312795334df36858e8d5f0069bd81426d8b2793cca
3
+ size 544008935
10_lr_stronger_proj_residual_13/r1s/10_lr_stronger_proj_residual_13_s26092004_f1_r1_vs0.83753_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:683339742c21c662783a3ac2987290df7421378145525dfe7acf32690ff31ccb
3
+ size 544008935
10_lr_stronger_proj_residual_13/r1s/10_lr_stronger_proj_residual_13_s26092004_f2_r1_vs0.84252_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1912ad6dd00e02667caa38f1a312c906dd58bf0b639fee43863b9e0fb85b69b4
3
+ size 544008935
10_lr_stronger_proj_residual_13/r1s/10_lr_stronger_proj_residual_13_s26092004_f3_r1_vs0.83418_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2cfa87d1ba3e4701574a29c00867d6d6473bc67549483e81d7ed014a22df3cc9
3
+ size 544008935
10_lr_stronger_proj_residual_13/r1s/10_lr_stronger_proj_residual_13_s26092004_f4_r1_vs0.81628_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:55b18072d780a5c51afacaa1f5f17beda0d142ee187a3bffff18cc9ea931b53f
3
+ size 544008935
10_lr_stronger_proj_residual_13/results/10_lr_stronger_proj_residual_13_test.json ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "Best model": {
3
+ "0": {
4
+ "5": {
5
+ "recall": 0.7443524096385542,
6
+ "mAP": 0.2924065010040172,
7
+ "mRP": 0.2976091867469895
8
+ },
9
+ "10": {
10
+ "recall": 0.8298192771084337,
11
+ "mAP": 0.30692378392538494,
12
+ "mRP": 0.2976091867469895
13
+ },
14
+ "15": {
15
+ "recall": 0.8723644578313253,
16
+ "mAP": 0.31227810862929556,
17
+ "mRP": 0.2976091867469895
18
+ }
19
+ },
20
+ "0.25": {
21
+ "5": {
22
+ "recall": 0.7846385542168675,
23
+ "mAP": 0.3201090821619829,
24
+ "mRP": 0.32419678714859645
25
+ },
26
+ "10": {
27
+ "recall": 0.8648343373493976,
28
+ "mAP": 0.3358617331428901,
29
+ "mRP": 0.32419678714859645
30
+ },
31
+ "15": {
32
+ "recall": 0.9002259036144579,
33
+ "mAP": 0.342011814027534,
34
+ "mRP": 0.32419678714859645
35
+ }
36
+ },
37
+ "0.5": {
38
+ "5": {
39
+ "recall": 0.7624246987951807,
40
+ "mAP": 0.3036522130187432,
41
+ "mRP": 0.3079442771084354
42
+ },
43
+ "10": {
44
+ "recall": 0.8354668674698795,
45
+ "mAP": 0.3181926490684975,
46
+ "mRP": 0.3079442771084354
47
+ },
48
+ "15": {
49
+ "recall": 0.8765060240963856,
50
+ "mAP": 0.32437696613195593,
51
+ "mRP": 0.3079442771084354
52
+ }
53
+ },
54
+ "0.75": {
55
+ "5": {
56
+ "recall": 0.7466114457831325,
57
+ "mAP": 0.29441275518741733,
58
+ "mRP": 0.29779116465863603
59
+ },
60
+ "10": {
61
+ "recall": 0.8200301204819277,
62
+ "mAP": 0.30801281763960703,
63
+ "mRP": 0.29779116465863603
64
+ },
65
+ "15": {
66
+ "recall": 0.860316265060241,
67
+ "mAP": 0.31387464960366007,
68
+ "mRP": 0.29779116465863603
69
+ }
70
+ },
71
+ "1": {
72
+ "5": {
73
+ "recall": 0.733433734939759,
74
+ "mAP": 0.28731467536814015,
75
+ "mRP": 0.29214984939759164
76
+ },
77
+ "10": {
78
+ "recall": 0.8121234939759037,
79
+ "mAP": 0.3006136824082051,
80
+ "mRP": 0.29214984939759164
81
+ },
82
+ "15": {
83
+ "recall": 0.8490210843373494,
84
+ "mAP": 0.306475996654367,
85
+ "mRP": 0.29214984939759164
86
+ }
87
+ }
88
+ },
89
+ "Last model": {
90
+ "0": {
91
+ "5": {
92
+ "recall": 0.7164909638554217,
93
+ "mAP": 0.2858075008366813,
94
+ "mRP": 0.2840863453815275
95
+ },
96
+ "10": {
97
+ "recall": 0.8019578313253012,
98
+ "mAP": 0.3002852680563535,
99
+ "mRP": 0.2840863453815275
100
+ },
101
+ "15": {
102
+ "recall": 0.8471385542168675,
103
+ "mAP": 0.3057258786296823,
104
+ "mRP": 0.2840863453815275
105
+ }
106
+ },
107
+ "0.25": {
108
+ "5": {
109
+ "recall": 0.7835090361445783,
110
+ "mAP": 0.32134590445113953,
111
+ "mRP": 0.3215612449799215
112
+ },
113
+ "10": {
114
+ "recall": 0.8595632530120482,
115
+ "mAP": 0.33752068044001493,
116
+ "mRP": 0.3215612449799215
117
+ },
118
+ "15": {
119
+ "recall": 0.8972138554216867,
120
+ "mAP": 0.3438879046649201,
121
+ "mRP": 0.3215612449799215
122
+ }
123
+ },
124
+ "0.5": {
125
+ "5": {
126
+ "recall": 0.7522590361445783,
127
+ "mAP": 0.30210508701472716,
128
+ "mRP": 0.30480672690763194
129
+ },
130
+ "10": {
131
+ "recall": 0.8309487951807228,
132
+ "mAP": 0.31700036754159644,
133
+ "mRP": 0.30480672690763194
134
+ },
135
+ "15": {
136
+ "recall": 0.8685993975903614,
137
+ "mAP": 0.323069974704012,
138
+ "mRP": 0.30480672690763194
139
+ }
140
+ },
141
+ "0.75": {
142
+ "5": {
143
+ "recall": 0.7341867469879518,
144
+ "mAP": 0.28936673778447247,
145
+ "mRP": 0.29249497991968
146
+ },
147
+ "10": {
148
+ "recall": 0.8162650602409639,
149
+ "mAP": 0.30331314593692305,
150
+ "mRP": 0.29249497991968
151
+ },
152
+ "15": {
153
+ "recall": 0.853539156626506,
154
+ "mAP": 0.3095065883295372,
155
+ "mRP": 0.29249497991968
156
+ }
157
+ },
158
+ "1": {
159
+ "5": {
160
+ "recall": 0.7277861445783133,
161
+ "mAP": 0.2823612156961189,
162
+ "mRP": 0.2867093373493987
163
+ },
164
+ "10": {
165
+ "recall": 0.8091114457831325,
166
+ "mAP": 0.2956084680985856,
167
+ "mRP": 0.2867093373493987
168
+ },
169
+ "15": {
170
+ "recall": 0.8433734939759037,
171
+ "mAP": 0.3014933022863186,
172
+ "mRP": 0.2867093373493987
173
+ }
174
+ }
175
+ }
176
+ }
10_lr_stronger_proj_residual_13/results/10_lr_stronger_proj_residual_13_test_df.xlsx ADDED
Binary file (6.27 kB). View file
 
10_lr_stronger_proj_residual_13/results/10_lr_stronger_proj_residual_13_test_df_best.xlsx ADDED
Binary file (5.55 kB). View file