WebFAQHardNegatives / mining_hardnegatives_bge3.py
IrvinTopi's picture
Upload mining_hardnegatives_bge3.py
546cc1f verified
import json
import random
import os
import argparse
import torch
import numpy as np
from pathlib import Path
from datasets import load_dataset
from tqdm import tqdm
from pyserini.search.lucene import LuceneSearcher
from sentence_transformers import CrossEncoder
# ==========================================
# CONFIGURATION
# ==========================================
# OPTION A: The Modern SOTA (Recommended) - ~2.2GB VRAM
CROSS_ENCODER_MODEL = "BAAI/bge-reranker-v2-m3"
# Target samples per language
MARGINMSE_SAMPLES = {
"ara": 32_000, "dan": 32_000, "deu": 96_000, "eng": 128_000,
"fas": 64_000, "fra": 96_000, "hin": 32_000, "ind": 32_000,
"ita": 96_000, "jpn": 96_000, "kor": 32_000, "nld": 96_000,
"pol": 64_000, "por": 64_000, "rus": 96_000, "spa": 96_000,
"swe": 32_000, "tur": 32_000, "vie": 32_000, "zho": 32_000,
}
# Pyserini Language Codes
LANG_MAP = {
"ara": "ar", "dan": "da", "deu": "de", "eng": "en", "fas": "fa",
"fra": "fr", "hin": "hi", "ind": "id", "ita": "it", "jpn": "ja",
"kor": "ko", "nld": "nl", "pol": "pl", "por": "pt", "rus": "ru",
"spa": "es", "swe": "sv", "tur": "tr", "vie": "vi", "zho": "zh"
}
def build_index(language: str, corpus: dict, temp_dir: Path):
"""
Builds a temporary Lucene index for BM25 retrieval.
"""
iso_lang = LANG_MAP.get(language, "en")
input_dir = temp_dir / language / "corpus_jsonl"
index_dir = temp_dir / language / "index"
if index_dir.exists():
return index_dir
print(f" [{language}] Preparing docs for indexing...")
input_dir.mkdir(parents=True, exist_ok=True)
jsonl_file = input_dir / "docs.jsonl"
with open(jsonl_file, "w", encoding="utf-8") as f:
for cid, text in corpus.items():
f.write(json.dumps({"id": str(cid), "contents": text}, ensure_ascii=False) + "\n")
print(f" [{language}] Building BM25 Index (Analyzer: {iso_lang})...")
# Using os.system to call the Pyserini JVM wrapper
cmd = (f"python -m pyserini.index.lucene "
f"--collection JsonCollection "
f"--input {input_dir} "
f"--index {index_dir} "
f"--generator DefaultLuceneDocumentGenerator "
f"--threads 8 "
f"--language {iso_lang} "
f"--storeRaw")
os.system(cmd)
return index_dir
def process_language_mining_and_scoring(lang, n_samples, output_path, repo_id, k_negatives, scorer_model, batch_size):
print(f"\n{'='*60}\nProcessing {lang} (Samples: {n_samples})\n{'='*60}")
# 1. Load Data
try:
q_ds = load_dataset(repo_id, f"{lang}-queries", split='train')
c_ds = load_dataset(repo_id, f"{lang}-corpus", split='corpus')
qr_ds = load_dataset(repo_id, f"{lang}-qrels", split='train')
except Exception as e:
print(f" [ERROR] Could not load {lang}: {e}")
return
queries = {item['_id']: item['text'] for item in q_ds}
corpus = {item['_id']: item['text'] for item in c_ds}
qrels_all = [(item['query-id'], item['corpus-id']) for item in qr_ds]
# 2. Sample Subset
random.seed(42)
if len(qrels_all) > n_samples:
sampled_qrels = random.sample(qrels_all, n_samples)
else:
sampled_qrels = qrels_all
# 3. Build/Load Index
idx_path = build_index(lang, corpus, Path("./temp_indices"))
searcher = LuceneSearcher(str(idx_path))
searcher.set_language(LANG_MAP.get(lang, "en"))
# 4. Mine AND Score
final_output = []
print(f" [{lang}] Mining {k_negatives} negatives & Reranking with {CROSS_ENCODER_MODEL}...")
for qid, pos_doc_id in tqdm(sampled_qrels, desc=f" Distilling {lang}"):
query_text = queries.get(qid)
pos_text = corpus.get(pos_doc_id)
if not query_text or not pos_text:
continue
# A. BM25 Retrieval
hits = searcher.search(query_text, k=k_negatives + 20)
neg_candidates = []
for hit in hits:
if hit.docid != str(pos_doc_id) and len(neg_candidates) < k_negatives:
neg_text = corpus.get(hit.docid)
if neg_text:
neg_candidates.append(neg_text)
# B. Cross-Encoder Scoring
# We score [Positive, Neg1, Neg2, ..., Neg200]
texts_to_score = [pos_text] + neg_candidates
pairs = [[query_text, doc] for doc in texts_to_score]
# Predict returns raw logits
scores = scorer_model.predict(pairs, batch_size=batch_size, show_progress_bar=False)
pos_score = float(scores[0])
neg_scores = [float(s) for s in scores[1:]]
final_output.append({
"query": query_text,
"positive": pos_text,
"positive_score": pos_score,
"negatives": neg_candidates,
"negative_scores": neg_scores
})
# 5. Save
save_dir = Path(output_path) / lang
save_dir.mkdir(parents=True, exist_ok=True)
outfile = save_dir / "train_marginmse.jsonl"
with open(outfile, "w", encoding="utf-8") as f:
for item in final_output:
f.write(json.dumps(item, ensure_ascii=False) + "\n")
print(f" [{lang}] Saved {len(final_output)} examples to {outfile}")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--repo-id", default="PaDaS-Lab/webfaq-retrieval")
parser.add_argument("--output-dir", default="./data/distilled_data")
parser.add_argument("--k-negatives", type=int, default=200)
parser.add_argument("--batch-size", type=int, default=16, help="Lower this if OOM")
args = parser.parse_args()
# Initialize Teacher
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Loading Teacher: {CROSS_ENCODER_MODEL}")
print(f"Device: {device}")
scorer_model = CrossEncoder(
CROSS_ENCODER_MODEL,
device=device,
automodel_args={"torch_dtype": torch.float16} if device == "cuda" else {}
)
for lang, n_samples in MARGINMSE_SAMPLES.items():
# === RESUME LOGIC ===
# If the output file already exists, we assume this language is done.
output_file = Path(args.output_dir) / lang / "train_marginmse.jsonl"
if output_file.exists():
# Optional: Check file size to ensure it's not empty/corrupted
if output_file.stat().st_size > 1000:
print(f" [RESUME] Output found for {lang}. Skipping...")
continue
else:
print(f" [RESUME] Found empty file for {lang}. Re-processing...")
process_language_mining_and_scoring(
lang, n_samples, args.output_dir, args.repo_id, args.k_negatives, scorer_model, args.batch_size
)
if __name__ == "__main__":
main()