| | import os |
| | import random |
| | import json |
| | import shutil |
| | import faiss |
| | import numpy as np |
| |
|
| | from tqdm import tqdm |
| | from FlagEmbedding import FlagLLMModel |
| |
|
| | def create_index(embeddings: np.ndarray, use_gpu: bool = True): |
| | index = faiss.IndexFlatIP(len(embeddings[0])) |
| | embeddings = np.asarray(embeddings, dtype=np.float32) |
| | |
| | |
| | |
| | |
| | |
| | index.add(embeddings) |
| | return index |
| |
|
| |
|
| | if __name__ == '__main__': |
| | model = FlagLLMModel('/share/chaofan/models/bge-multilingual-gemma2', |
| | query_instruction_for_retrieval="Given a question, retrieve passages that answer the question.", |
| | query_instruction_format="<instruct>{}\n<query>{}", |
| | use_fp16=True) |
| |
|
| | avaliable_languages = ['zh', 'en', 'ar', 'bn', 'es', 'fa', 'fi', 'fr', 'hi', 'id', 'ja', 'ko', 'ru', 'sw', 'te', 'th', 'de', 'yo'] |
| |
|
| | new_dir = '/share/chaofan/code/bge_demo/data' |
| | new_emb_dir = '/share/chaofan/code/bge_demo/emb' |
| |
|
| | for lang in tqdm(avaliable_languages[::-1], desc='language'): |
| | new_qrels_path = os.path.join(new_dir, lang, 'dev_qrels.jsonl') |
| | new_queries_path = os.path.join(new_dir, lang, 'dev_queries.jsonl') |
| | new_corpus_path = os.path.join(new_dir, lang, 'corpus.jsonl') |
| |
|
| | os.makedirs(os.path.join(new_emb_dir, lang), exist_ok=True) |
| |
|
| | if not os.path.exists(os.path.join(new_emb_dir, lang, 'corpus.npy')): |
| | data = [] |
| | with open(new_corpus_path) as f: |
| | for line in f: |
| | tmp = json.loads(line) |
| | data.append(tmp['title'] + ' ' + tmp['text']) |
| | |
| | doc_emb = model.encode_corpus(data, batch_size=256) |
| | np.save(os.path.join(new_emb_dir, lang, 'corpus.npy'), doc_emb) |
| | else: |
| | doc_emb = np.load(os.path.join(new_emb_dir, lang, 'corpus.npy')) |
| | faiss_index = create_index(doc_emb) |
| | faiss.write_index(faiss_index, os.path.join(new_emb_dir, lang, 'faiss.index')) |
| |
|