| 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 |
|
|
| |
| |
| |
|
|
| |
| CROSS_ENCODER_MODEL = "BAAI/bge-reranker-v2-m3" |
|
|
| |
| 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, |
| } |
|
|
| |
| 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})...") |
| |
| 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}") |
| |
| |
| 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] |
| |
| |
| random.seed(42) |
| if len(qrels_all) > n_samples: |
| sampled_qrels = random.sample(qrels_all, n_samples) |
| else: |
| sampled_qrels = qrels_all |
| |
| |
| idx_path = build_index(lang, corpus, Path("./temp_indices")) |
| searcher = LuceneSearcher(str(idx_path)) |
| searcher.set_language(LANG_MAP.get(lang, "en")) |
|
|
| |
| 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 |
|
|
| |
| 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) |
| |
| |
| |
| texts_to_score = [pos_text] + neg_candidates |
| pairs = [[query_text, doc] for doc in texts_to_score] |
| |
| |
| 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 |
| }) |
|
|
| |
| 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() |
|
|
| |
| 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(): |
| |
| |
| output_file = Path(args.output_dir) / lang / "train_marginmse.jsonl" |
| |
| if output_file.exists(): |
| |
| 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() |