File size: 6,833 Bytes
546cc1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
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()