Sentence Similarity
Transformers
Safetensors
sentence-transformers
PEFT
English
feature-extraction
lora
retrieval
embedding
finance
regulatory
compliance
Instructions to use sugiv/modernbert-us-stablecoin-encoder with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use sugiv/modernbert-us-stablecoin-encoder with Transformers:
# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("sugiv/modernbert-us-stablecoin-encoder", device_map="auto") - sentence-transformers
How to use sugiv/modernbert-us-stablecoin-encoder with sentence-transformers:
from sentence_transformers import SentenceTransformer model = SentenceTransformer("sugiv/modernbert-us-stablecoin-encoder") sentences = [ "That is a happy person", "That is a happy dog", "That is a very happy person", "Today is a sunny day" ] embeddings = model.encode(sentences) similarities = model.similarity(embeddings, embeddings) print(similarities.shape) # [4, 4] - PEFT
How to use sugiv/modernbert-us-stablecoin-encoder with PEFT:
Task type is invalid.
- Notebooks
- Google Colab
- Kaggle
Upload train_encoder_lora.py with huggingface_hub
Browse files- train_encoder_lora.py +610 -0
train_encoder_lora.py
ADDED
|
@@ -0,0 +1,610 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Production Encoder LoRA Training for Stablebridge
|
| 4 |
+
|
| 5 |
+
Trains LoRA adapters on BAAI/bge-m3 for US regulatory domain.
|
| 6 |
+
Implements tech spec requirements:
|
| 7 |
+
- LoRA rank 16, alpha 32
|
| 8 |
+
- 8192 token context window
|
| 9 |
+
- MultipleNegativesRankingLoss (in-batch negatives)
|
| 10 |
+
- WandB logging, checkpointing, evaluation
|
| 11 |
+
- Model Hub push
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import torch
|
| 18 |
+
import wandb
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from datetime import datetime
|
| 21 |
+
from typing import Dict, List, Optional
|
| 22 |
+
from dataclasses import dataclass, field
|
| 23 |
+
|
| 24 |
+
from transformers import (
|
| 25 |
+
AutoTokenizer,
|
| 26 |
+
AutoModel,
|
| 27 |
+
get_cosine_schedule_with_warmup,
|
| 28 |
+
TrainingArguments,
|
| 29 |
+
)
|
| 30 |
+
from peft import LoraConfig, get_peft_model, TaskType
|
| 31 |
+
from torch.utils.data import Dataset, DataLoader
|
| 32 |
+
from torch.nn import functional as F
|
| 33 |
+
from torch.cuda.amp import autocast, GradScaler
|
| 34 |
+
import numpy as np
|
| 35 |
+
from tqdm import tqdm
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@dataclass
|
| 39 |
+
class EncoderTrainingConfig:
|
| 40 |
+
"""Complete training configuration matching tech spec."""
|
| 41 |
+
|
| 42 |
+
# Model
|
| 43 |
+
base_model: str = "BAAI/bge-m3"
|
| 44 |
+
max_length: int = 8192 # Full context per tech spec
|
| 45 |
+
|
| 46 |
+
# LoRA
|
| 47 |
+
lora_rank: int = 16
|
| 48 |
+
lora_alpha: int = 32
|
| 49 |
+
lora_dropout: float = 0.1
|
| 50 |
+
target_modules: List[str] = field(default_factory=lambda: ["query", "key", "value"])
|
| 51 |
+
|
| 52 |
+
# Training
|
| 53 |
+
epochs: int = 3
|
| 54 |
+
per_device_batch_size: int = 4 # RTX 6000 Ada - will adjust based on memory
|
| 55 |
+
gradient_accumulation_steps: int = 16 # Effective batch size = 64
|
| 56 |
+
learning_rate: float = 5e-5
|
| 57 |
+
weight_decay: float = 0.01
|
| 58 |
+
warmup_ratio: float = 0.1
|
| 59 |
+
max_grad_norm: float = 1.0
|
| 60 |
+
|
| 61 |
+
# Precision
|
| 62 |
+
mixed_precision: str = "bf16" # Will fall back to fp16 if needed
|
| 63 |
+
|
| 64 |
+
# Checkpointing
|
| 65 |
+
save_steps: int = 500
|
| 66 |
+
eval_steps: int = 500
|
| 67 |
+
logging_steps: int = 50
|
| 68 |
+
|
| 69 |
+
# Paths
|
| 70 |
+
data_path: str = "/workspace/data/labels/encoder_triplets.jsonl"
|
| 71 |
+
corpus_dir: str = "/workspace/data/raw"
|
| 72 |
+
output_dir: str = "/workspace/checkpoints/bge-m3-us-regulatory-lora"
|
| 73 |
+
|
| 74 |
+
# Monitoring
|
| 75 |
+
wandb_project: str = "stablebridge-encoder"
|
| 76 |
+
wandb_run_name: Optional[str] = None
|
| 77 |
+
|
| 78 |
+
# Hub
|
| 79 |
+
push_to_hub: bool = True
|
| 80 |
+
hub_model_id: str = "cognilogue/bge-m3-us-regulatory-lora"
|
| 81 |
+
hub_token: Optional[str] = None
|
| 82 |
+
|
| 83 |
+
# Evaluation
|
| 84 |
+
eval_split: float = 0.1 # Hold out 10% for validation
|
| 85 |
+
eval_metrics: List[str] = field(default_factory=lambda: ["ndcg@10", "mrr@10", "recall@100"])
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class TripletDataset(Dataset):
|
| 89 |
+
"""Dataset for encoder triplet training with in-batch negatives."""
|
| 90 |
+
|
| 91 |
+
def __init__(
|
| 92 |
+
self,
|
| 93 |
+
triplets: List[Dict],
|
| 94 |
+
corpus: Dict[str, str],
|
| 95 |
+
tokenizer,
|
| 96 |
+
max_length: int = 8192
|
| 97 |
+
):
|
| 98 |
+
self.triplets = triplets
|
| 99 |
+
self.corpus = corpus
|
| 100 |
+
self.tokenizer = tokenizer
|
| 101 |
+
self.max_length = max_length
|
| 102 |
+
|
| 103 |
+
def __len__(self):
|
| 104 |
+
return len(self.triplets)
|
| 105 |
+
|
| 106 |
+
def __getitem__(self, idx):
|
| 107 |
+
triplet = self.triplets[idx]
|
| 108 |
+
query = triplet["query"]
|
| 109 |
+
pos_id = triplet["positive"]
|
| 110 |
+
|
| 111 |
+
# Get positive document
|
| 112 |
+
positive_text = self.corpus.get(pos_id, "")
|
| 113 |
+
|
| 114 |
+
# Tokenize
|
| 115 |
+
query_enc = self.tokenizer(
|
| 116 |
+
query,
|
| 117 |
+
max_length=self.max_length,
|
| 118 |
+
truncation=True,
|
| 119 |
+
padding="max_length",
|
| 120 |
+
return_tensors="pt"
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
pos_enc = self.tokenizer(
|
| 124 |
+
positive_text,
|
| 125 |
+
max_length=self.max_length,
|
| 126 |
+
truncation=True,
|
| 127 |
+
padding="max_length",
|
| 128 |
+
return_tensors="pt"
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
return {
|
| 132 |
+
"query_input_ids": query_enc["input_ids"].squeeze(0),
|
| 133 |
+
"query_attention_mask": query_enc["attention_mask"].squeeze(0),
|
| 134 |
+
"pos_input_ids": pos_enc["input_ids"].squeeze(0),
|
| 135 |
+
"pos_attention_mask": pos_enc["attention_mask"].squeeze(0),
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def mean_pooling(model_output, attention_mask):
|
| 140 |
+
"""Mean pooling over token embeddings (ignore padding)."""
|
| 141 |
+
token_embeddings = model_output[0]
|
| 142 |
+
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
|
| 143 |
+
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(
|
| 144 |
+
input_mask_expanded.sum(1), min=1e-9
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def compute_loss(query_emb, pos_emb, temperature=0.05):
|
| 149 |
+
"""
|
| 150 |
+
Multiple Negatives Ranking Loss (InfoNCE).
|
| 151 |
+
|
| 152 |
+
Uses in-batch negatives: all other positives in the batch serve as negatives.
|
| 153 |
+
Standard approach in sentence-transformers contrastive learning.
|
| 154 |
+
|
| 155 |
+
Args:
|
| 156 |
+
query_emb: (batch_size, hidden_dim) - normalized query embeddings
|
| 157 |
+
pos_emb: (batch_size, hidden_dim) - normalized positive embeddings
|
| 158 |
+
temperature: Temperature for softmax (default 0.05)
|
| 159 |
+
|
| 160 |
+
Returns:
|
| 161 |
+
loss: Scalar loss value
|
| 162 |
+
"""
|
| 163 |
+
# Normalize embeddings
|
| 164 |
+
query_emb = F.normalize(query_emb, p=2, dim=1)
|
| 165 |
+
pos_emb = F.normalize(pos_emb, p=2, dim=1)
|
| 166 |
+
|
| 167 |
+
# Compute similarity matrix: (batch_size, batch_size)
|
| 168 |
+
# query_emb[i] @ pos_emb[j].T gives similarity between query i and doc j
|
| 169 |
+
sim_matrix = torch.matmul(query_emb, pos_emb.T) / temperature
|
| 170 |
+
|
| 171 |
+
# Labels: diagonal elements are positive pairs
|
| 172 |
+
labels = torch.arange(sim_matrix.size(0)).to(sim_matrix.device)
|
| 173 |
+
|
| 174 |
+
# Cross-entropy: pulls positives closer, pushes negatives away
|
| 175 |
+
loss = F.cross_entropy(sim_matrix, labels)
|
| 176 |
+
|
| 177 |
+
return loss
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def evaluate_retrieval(model, tokenizer, eval_data, corpus, device, config):
|
| 181 |
+
"""
|
| 182 |
+
Evaluate retrieval quality on validation set.
|
| 183 |
+
|
| 184 |
+
Metrics:
|
| 185 |
+
- NDCG@10: Ranking quality
|
| 186 |
+
- MRR@10: Mean Reciprocal Rank
|
| 187 |
+
- Recall@100: Coverage
|
| 188 |
+
"""
|
| 189 |
+
model.eval()
|
| 190 |
+
|
| 191 |
+
# Encode all documents
|
| 192 |
+
print("\nEncoding corpus for evaluation...")
|
| 193 |
+
doc_ids = list(corpus.keys())
|
| 194 |
+
doc_embeddings = []
|
| 195 |
+
|
| 196 |
+
with torch.no_grad():
|
| 197 |
+
for doc_id in tqdm(doc_ids, desc="Encoding docs"):
|
| 198 |
+
doc_text = corpus[doc_id]
|
| 199 |
+
doc_enc = tokenizer(
|
| 200 |
+
doc_text,
|
| 201 |
+
max_length=config.max_length,
|
| 202 |
+
truncation=True,
|
| 203 |
+
padding="max_length",
|
| 204 |
+
return_tensors="pt"
|
| 205 |
+
).to(device)
|
| 206 |
+
|
| 207 |
+
doc_output = model(**doc_enc)
|
| 208 |
+
doc_emb = mean_pooling(doc_output, doc_enc["attention_mask"])
|
| 209 |
+
doc_emb = F.normalize(doc_emb, p=2, dim=1)
|
| 210 |
+
doc_embeddings.append(doc_emb.cpu())
|
| 211 |
+
|
| 212 |
+
doc_embeddings = torch.cat(doc_embeddings, dim=0) # (num_docs, hidden_dim)
|
| 213 |
+
|
| 214 |
+
# Evaluate queries
|
| 215 |
+
ndcg_scores = []
|
| 216 |
+
mrr_scores = []
|
| 217 |
+
recall_scores = []
|
| 218 |
+
|
| 219 |
+
with torch.no_grad():
|
| 220 |
+
for triplet in tqdm(eval_data, desc="Evaluating"):
|
| 221 |
+
query = triplet["query"]
|
| 222 |
+
pos_id = triplet["positive"]
|
| 223 |
+
|
| 224 |
+
# Encode query
|
| 225 |
+
query_enc = tokenizer(
|
| 226 |
+
query,
|
| 227 |
+
max_length=config.max_length,
|
| 228 |
+
truncation=True,
|
| 229 |
+
padding="max_length",
|
| 230 |
+
return_tensors="pt"
|
| 231 |
+
).to(device)
|
| 232 |
+
|
| 233 |
+
query_output = model(**query_enc)
|
| 234 |
+
query_emb = mean_pooling(query_output, query_enc["attention_mask"])
|
| 235 |
+
query_emb = F.normalize(query_emb, p=2, dim=1)
|
| 236 |
+
|
| 237 |
+
# Compute similarities
|
| 238 |
+
similarities = torch.matmul(query_emb.cpu(), doc_embeddings.T).squeeze(0)
|
| 239 |
+
|
| 240 |
+
# Rank documents
|
| 241 |
+
ranks = torch.argsort(similarities, descending=True)
|
| 242 |
+
|
| 243 |
+
# Find position of positive document
|
| 244 |
+
try:
|
| 245 |
+
pos_idx = doc_ids.index(pos_id)
|
| 246 |
+
pos_rank = (ranks == pos_idx).nonzero(as_tuple=True)[0].item() + 1
|
| 247 |
+
except (ValueError, IndexError):
|
| 248 |
+
pos_rank = len(doc_ids) + 1 # Not found
|
| 249 |
+
|
| 250 |
+
# NDCG@10
|
| 251 |
+
if pos_rank <= 10:
|
| 252 |
+
ndcg = 1.0 / np.log2(pos_rank + 1)
|
| 253 |
+
else:
|
| 254 |
+
ndcg = 0.0
|
| 255 |
+
ndcg_scores.append(ndcg)
|
| 256 |
+
|
| 257 |
+
# MRR@10
|
| 258 |
+
if pos_rank <= 10:
|
| 259 |
+
mrr = 1.0 / pos_rank
|
| 260 |
+
else:
|
| 261 |
+
mrr = 0.0
|
| 262 |
+
mrr_scores.append(mrr)
|
| 263 |
+
|
| 264 |
+
# Recall@100
|
| 265 |
+
recall = 1.0 if pos_rank <= 100 else 0.0
|
| 266 |
+
recall_scores.append(recall)
|
| 267 |
+
|
| 268 |
+
metrics = {
|
| 269 |
+
"eval/ndcg@10": np.mean(ndcg_scores),
|
| 270 |
+
"eval/mrr@10": np.mean(mrr_scores),
|
| 271 |
+
"eval/recall@100": np.mean(recall_scores),
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
return metrics
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def load_data(config: EncoderTrainingConfig):
|
| 278 |
+
"""Load triplets and corpus, split train/eval."""
|
| 279 |
+
|
| 280 |
+
# Load triplets
|
| 281 |
+
print(f"Loading triplets from {config.data_path}...")
|
| 282 |
+
triplets = []
|
| 283 |
+
with open(config.data_path) as f:
|
| 284 |
+
for line in f:
|
| 285 |
+
if line.strip():
|
| 286 |
+
triplets.append(json.loads(line))
|
| 287 |
+
print(f"✅ {len(triplets)} triplets")
|
| 288 |
+
|
| 289 |
+
# Load corpus
|
| 290 |
+
print(f"Loading corpus from {config.corpus_dir}...")
|
| 291 |
+
corpus = {}
|
| 292 |
+
corpus_dir = Path(config.corpus_dir)
|
| 293 |
+
for json_file in corpus_dir.glob("*.json"):
|
| 294 |
+
with open(json_file) as f:
|
| 295 |
+
doc = json.load(f)
|
| 296 |
+
doc_id = doc.get("doc_id")
|
| 297 |
+
content = doc.get("content", "")
|
| 298 |
+
if doc_id and content:
|
| 299 |
+
corpus[doc_id] = content
|
| 300 |
+
print(f"✅ {len(corpus)} documents")
|
| 301 |
+
|
| 302 |
+
# Train/eval split
|
| 303 |
+
num_eval = int(len(triplets) * config.eval_split)
|
| 304 |
+
eval_triplets = triplets[:num_eval]
|
| 305 |
+
train_triplets = triplets[num_eval:]
|
| 306 |
+
|
| 307 |
+
print(f"\nSplit: {len(train_triplets)} train, {len(eval_triplets)} eval")
|
| 308 |
+
|
| 309 |
+
return train_triplets, eval_triplets, corpus
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def main():
|
| 313 |
+
parser = argparse.ArgumentParser()
|
| 314 |
+
parser.add_argument("--config", type=str, help="Path to YAML config file (optional)")
|
| 315 |
+
parser.add_argument("--data-path", type=str, help="Override triplets path")
|
| 316 |
+
parser.add_argument("--output-dir", type=str, help="Override output directory")
|
| 317 |
+
parser.add_argument("--batch-size", type=int, help="Override batch size")
|
| 318 |
+
parser.add_argument("--epochs", type=int, help="Override number of epochs")
|
| 319 |
+
parser.add_argument("--no-wandb", action="store_true", help="Disable WandB logging")
|
| 320 |
+
parser.add_argument("--no-push", action="store_true", help="Disable Hub push")
|
| 321 |
+
args = parser.parse_args()
|
| 322 |
+
|
| 323 |
+
# Load config
|
| 324 |
+
config = EncoderTrainingConfig()
|
| 325 |
+
|
| 326 |
+
# Override from args
|
| 327 |
+
if args.data_path:
|
| 328 |
+
config.data_path = args.data_path
|
| 329 |
+
if args.output_dir:
|
| 330 |
+
config.output_dir = args.output_dir
|
| 331 |
+
if args.batch_size:
|
| 332 |
+
config.per_device_batch_size = args.batch_size
|
| 333 |
+
if args.epochs:
|
| 334 |
+
config.epochs = args.epochs
|
| 335 |
+
if args.no_push:
|
| 336 |
+
config.push_to_hub = False
|
| 337 |
+
|
| 338 |
+
# Setup
|
| 339 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 340 |
+
print("=" * 80)
|
| 341 |
+
print("STABLEBRIDGE ENCODER LORA TRAINING")
|
| 342 |
+
print("=" * 80)
|
| 343 |
+
print(f"Device: {device}")
|
| 344 |
+
print(f"Base model: {config.base_model}")
|
| 345 |
+
print(f"LoRA rank: {config.lora_rank}, alpha: {config.lora_alpha}")
|
| 346 |
+
print(f"Max length: {config.max_length}")
|
| 347 |
+
print(f"Batch size: {config.per_device_batch_size} × {config.gradient_accumulation_steps} = {config.per_device_batch_size * config.gradient_accumulation_steps}")
|
| 348 |
+
print(f"Epochs: {config.epochs}")
|
| 349 |
+
print(f"Output: {config.output_dir}")
|
| 350 |
+
|
| 351 |
+
# Initialize WandB
|
| 352 |
+
use_wandb = not args.no_wandb and os.getenv("WANDB_API_KEY")
|
| 353 |
+
if use_wandb:
|
| 354 |
+
wandb.init(
|
| 355 |
+
project=config.wandb_project,
|
| 356 |
+
name=config.wandb_run_name or f"encoder-lora-{datetime.now().strftime('%Y%m%d-%H%M%S')}",
|
| 357 |
+
config=vars(config)
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
# Load data
|
| 361 |
+
train_triplets, eval_triplets, corpus = load_data(config)
|
| 362 |
+
|
| 363 |
+
# Load model
|
| 364 |
+
print("\n" + "=" * 80)
|
| 365 |
+
print("MODEL SETUP")
|
| 366 |
+
print("=" * 80)
|
| 367 |
+
|
| 368 |
+
print("\nLoading tokenizer and model...")
|
| 369 |
+
tokenizer = AutoTokenizer.from_pretrained(config.base_model, trust_remote_code=True, local_files_only=True)
|
| 370 |
+
|
| 371 |
+
# Determine dtype
|
| 372 |
+
if config.mixed_precision == "bf16" and torch.cuda.is_bf16_supported():
|
| 373 |
+
dtype = torch.bfloat16
|
| 374 |
+
print("Using bfloat16 precision")
|
| 375 |
+
else:
|
| 376 |
+
dtype = torch.float16
|
| 377 |
+
print("Using float16 precision")
|
| 378 |
+
|
| 379 |
+
model = AutoModel.from_pretrained(
|
| 380 |
+
config.base_model,
|
| 381 |
+
torch_dtype=dtype,
|
| 382 |
+
trust_remote_code=True,
|
| 383 |
+
local_files_only=True
|
| 384 |
+
).to(device)
|
| 385 |
+
|
| 386 |
+
# Apply LoRA
|
| 387 |
+
print(f"\nApplying LoRA (rank={config.lora_rank}, alpha={config.lora_alpha})...")
|
| 388 |
+
lora_config = LoraConfig(
|
| 389 |
+
r=config.lora_rank,
|
| 390 |
+
lora_alpha=config.lora_alpha,
|
| 391 |
+
target_modules=config.target_modules,
|
| 392 |
+
lora_dropout=config.lora_dropout,
|
| 393 |
+
bias="none",
|
| 394 |
+
task_type=TaskType.FEATURE_EXTRACTION,
|
| 395 |
+
)
|
| 396 |
+
model = get_peft_model(model, lora_config)
|
| 397 |
+
model.print_trainable_parameters()
|
| 398 |
+
|
| 399 |
+
# Create datasets
|
| 400 |
+
train_dataset = TripletDataset(train_triplets, corpus, tokenizer, config.max_length)
|
| 401 |
+
eval_dataset = eval_triplets # Will process differently in evaluation
|
| 402 |
+
|
| 403 |
+
# Create dataloader
|
| 404 |
+
train_loader = DataLoader(
|
| 405 |
+
train_dataset,
|
| 406 |
+
batch_size=config.per_device_batch_size,
|
| 407 |
+
shuffle=True,
|
| 408 |
+
num_workers=4,
|
| 409 |
+
pin_memory=True
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
# Optimizer
|
| 413 |
+
optimizer = torch.optim.AdamW(
|
| 414 |
+
model.parameters(),
|
| 415 |
+
lr=config.learning_rate,
|
| 416 |
+
weight_decay=config.weight_decay
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
# Learning rate scheduler
|
| 420 |
+
num_training_steps = len(train_loader) * config.epochs // config.gradient_accumulation_steps
|
| 421 |
+
num_warmup_steps = int(num_training_steps * config.warmup_ratio)
|
| 422 |
+
|
| 423 |
+
scheduler = get_cosine_schedule_with_warmup(
|
| 424 |
+
optimizer,
|
| 425 |
+
num_warmup_steps=num_warmup_steps,
|
| 426 |
+
num_training_steps=num_training_steps
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
# Gradient scaler for mixed precision
|
| 430 |
+
scaler = GradScaler() if dtype == torch.float16 else None
|
| 431 |
+
|
| 432 |
+
# Training
|
| 433 |
+
print("\n" + "=" * 80)
|
| 434 |
+
print("TRAINING")
|
| 435 |
+
print("=" * 80)
|
| 436 |
+
print(f"Total steps: {num_training_steps}")
|
| 437 |
+
print(f"Warmup steps: {num_warmup_steps}")
|
| 438 |
+
|
| 439 |
+
global_step = 0
|
| 440 |
+
best_ndcg = 0.0
|
| 441 |
+
|
| 442 |
+
for epoch in range(config.epochs):
|
| 443 |
+
print(f"\n{'='*80}")
|
| 444 |
+
print(f"EPOCH {epoch + 1}/{config.epochs}")
|
| 445 |
+
print(f"{'='*80}")
|
| 446 |
+
|
| 447 |
+
model.train()
|
| 448 |
+
epoch_loss = 0.0
|
| 449 |
+
optimizer.zero_grad()
|
| 450 |
+
|
| 451 |
+
pbar = tqdm(train_loader, desc=f"Epoch {epoch + 1}")
|
| 452 |
+
for step, batch in enumerate(pbar):
|
| 453 |
+
# Move to device
|
| 454 |
+
query_ids = batch["query_input_ids"].to(device)
|
| 455 |
+
query_mask = batch["query_attention_mask"].to(device)
|
| 456 |
+
pos_ids = batch["pos_input_ids"].to(device)
|
| 457 |
+
pos_mask = batch["pos_attention_mask"].to(device)
|
| 458 |
+
|
| 459 |
+
# Forward pass with mixed precision
|
| 460 |
+
with autocast(dtype=dtype):
|
| 461 |
+
query_output = model(input_ids=query_ids, attention_mask=query_mask)
|
| 462 |
+
query_emb = mean_pooling(query_output, query_mask)
|
| 463 |
+
|
| 464 |
+
pos_output = model(input_ids=pos_ids, attention_mask=pos_mask)
|
| 465 |
+
pos_emb = mean_pooling(pos_output, pos_mask)
|
| 466 |
+
|
| 467 |
+
# Compute loss
|
| 468 |
+
loss = compute_loss(query_emb, pos_emb)
|
| 469 |
+
loss = loss / config.gradient_accumulation_steps
|
| 470 |
+
|
| 471 |
+
# Backward pass
|
| 472 |
+
if scaler:
|
| 473 |
+
scaler.scale(loss).backward()
|
| 474 |
+
else:
|
| 475 |
+
loss.backward()
|
| 476 |
+
|
| 477 |
+
epoch_loss += loss.item() * config.gradient_accumulation_steps
|
| 478 |
+
|
| 479 |
+
# Update weights
|
| 480 |
+
if (step + 1) % config.gradient_accumulation_steps == 0:
|
| 481 |
+
# Gradient clipping
|
| 482 |
+
if scaler:
|
| 483 |
+
scaler.unscale_(optimizer)
|
| 484 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), config.max_grad_norm)
|
| 485 |
+
|
| 486 |
+
# Optimizer step
|
| 487 |
+
if scaler:
|
| 488 |
+
scaler.step(optimizer)
|
| 489 |
+
scaler.update()
|
| 490 |
+
else:
|
| 491 |
+
optimizer.step()
|
| 492 |
+
|
| 493 |
+
scheduler.step()
|
| 494 |
+
optimizer.zero_grad()
|
| 495 |
+
global_step += 1
|
| 496 |
+
|
| 497 |
+
# Logging
|
| 498 |
+
if global_step % config.logging_steps == 0:
|
| 499 |
+
lr = scheduler.get_last_lr()[0]
|
| 500 |
+
pbar.set_postfix({
|
| 501 |
+
"loss": f"{loss.item() * config.gradient_accumulation_steps:.4f}",
|
| 502 |
+
"lr": f"{lr:.2e}"
|
| 503 |
+
})
|
| 504 |
+
|
| 505 |
+
if use_wandb:
|
| 506 |
+
wandb.log({
|
| 507 |
+
"train/loss": loss.item() * config.gradient_accumulation_steps,
|
| 508 |
+
"train/learning_rate": lr,
|
| 509 |
+
"train/epoch": epoch,
|
| 510 |
+
"train/step": global_step,
|
| 511 |
+
})
|
| 512 |
+
|
| 513 |
+
# Evaluation
|
| 514 |
+
if global_step % config.eval_steps == 0:
|
| 515 |
+
print("\n" + "-" * 80)
|
| 516 |
+
print(f"EVALUATION at step {global_step}")
|
| 517 |
+
print("-" * 80)
|
| 518 |
+
|
| 519 |
+
eval_metrics = evaluate_retrieval(
|
| 520 |
+
model, tokenizer, eval_dataset, corpus, device, config
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
print("\nEvaluation Results:")
|
| 524 |
+
for metric, value in eval_metrics.items():
|
| 525 |
+
print(f" {metric}: {value:.4f}")
|
| 526 |
+
|
| 527 |
+
if use_wandb:
|
| 528 |
+
wandb.log(eval_metrics)
|
| 529 |
+
|
| 530 |
+
# Save best model
|
| 531 |
+
if eval_metrics["eval/ndcg@10"] > best_ndcg:
|
| 532 |
+
best_ndcg = eval_metrics["eval/ndcg@10"]
|
| 533 |
+
print(f"\n✅ New best NDCG@10: {best_ndcg:.4f}")
|
| 534 |
+
best_model_dir = Path(config.output_dir) / "best"
|
| 535 |
+
best_model_dir.mkdir(parents=True, exist_ok=True)
|
| 536 |
+
model.save_pretrained(best_model_dir)
|
| 537 |
+
tokenizer.save_pretrained(best_model_dir)
|
| 538 |
+
|
| 539 |
+
model.train()
|
| 540 |
+
print("-" * 80)
|
| 541 |
+
|
| 542 |
+
# Checkpointing
|
| 543 |
+
if global_step % config.save_steps == 0:
|
| 544 |
+
checkpoint_dir = Path(config.output_dir) / f"checkpoint-{global_step}"
|
| 545 |
+
checkpoint_dir.mkdir(parents=True, exist_ok=True)
|
| 546 |
+
model.save_pretrained(checkpoint_dir)
|
| 547 |
+
tokenizer.save_pretrained(checkpoint_dir)
|
| 548 |
+
print(f"\n💾 Checkpoint saved: {checkpoint_dir}")
|
| 549 |
+
|
| 550 |
+
avg_loss = epoch_loss / len(train_loader)
|
| 551 |
+
print(f"\nEpoch {epoch + 1} - Average Loss: {avg_loss:.4f}")
|
| 552 |
+
|
| 553 |
+
# Final save
|
| 554 |
+
print("\n" + "=" * 80)
|
| 555 |
+
print("SAVING FINAL MODEL")
|
| 556 |
+
print("=" * 80)
|
| 557 |
+
|
| 558 |
+
output_dir = Path(config.output_dir)
|
| 559 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 560 |
+
model.save_pretrained(output_dir)
|
| 561 |
+
tokenizer.save_pretrained(output_dir)
|
| 562 |
+
print(f"✅ Model saved to: {output_dir}")
|
| 563 |
+
|
| 564 |
+
# Push to Hub
|
| 565 |
+
if config.push_to_hub:
|
| 566 |
+
print("\n" + "=" * 80)
|
| 567 |
+
print("PUSHING TO HUGGING FACE HUB")
|
| 568 |
+
print("=" * 80)
|
| 569 |
+
|
| 570 |
+
try:
|
| 571 |
+
model.push_to_hub(
|
| 572 |
+
config.hub_model_id,
|
| 573 |
+
token=config.hub_token or os.getenv("HF_TOKEN")
|
| 574 |
+
)
|
| 575 |
+
tokenizer.push_to_hub(
|
| 576 |
+
config.hub_model_id,
|
| 577 |
+
token=config.hub_token or os.getenv("HF_TOKEN")
|
| 578 |
+
)
|
| 579 |
+
print(f"✅ Model pushed to: {config.hub_model_id}")
|
| 580 |
+
except Exception as e:
|
| 581 |
+
print(f"❌ Failed to push to Hub: {e}")
|
| 582 |
+
|
| 583 |
+
# Final evaluation
|
| 584 |
+
print("\n" + "=" * 80)
|
| 585 |
+
print("FINAL EVALUATION")
|
| 586 |
+
print("=" * 80)
|
| 587 |
+
|
| 588 |
+
final_metrics = evaluate_retrieval(
|
| 589 |
+
model, tokenizer, eval_dataset, corpus, device, config
|
| 590 |
+
)
|
| 591 |
+
|
| 592 |
+
print("\nFinal Results:")
|
| 593 |
+
for metric, value in final_metrics.items():
|
| 594 |
+
print(f" {metric}: {value:.4f}")
|
| 595 |
+
|
| 596 |
+
if use_wandb:
|
| 597 |
+
wandb.log({"final/" + k.split("/")[1]: v for k, v in final_metrics.items()})
|
| 598 |
+
wandb.finish()
|
| 599 |
+
|
| 600 |
+
print("\n" + "=" * 80)
|
| 601 |
+
print("TRAINING COMPLETE!")
|
| 602 |
+
print("=" * 80)
|
| 603 |
+
print(f"Best NDCG@10: {best_ndcg:.4f}")
|
| 604 |
+
print(f"Model saved to: {output_dir}")
|
| 605 |
+
if config.push_to_hub:
|
| 606 |
+
print(f"Hub: https://huggingface.co/{config.hub_model_id}")
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
if __name__ == "__main__":
|
| 610 |
+
main()
|