wikipedia-ja-20231030 / embs_to_faiss.py
hotchpotch's picture
add/change faiss indexes
c1ebd09
raw
history blame
4.97 kB
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
from tqdm import tqdm
import argparse
from pathlib import Path
import faiss
parser = argparse.ArgumentParser(description="Convert datasets to embeddings")
parser.add_argument(
"-t",
"--target",
type=str,
required=True,
choices=["data", "chunked"],
help="target dataset, data or chunked",
)
parser.add_argument(
"-i",
"--input_name",
type=str,
required=True,
help="input dir name",
)
# m
parser.add_argument(
"-m",
"--m",
type=int,
required=False,
default=8,
help="faiss param: m, subvector",
)
# mbit
parser.add_argument(
"-b",
"--mbit",
type=int,
required=False,
default=8,
help="faiss param: mbit, bits_per_idx",
)
# nlist
parser.add_argument(
"-n",
"--nlist",
type=int,
required=False,
default=None,
help="faiss param: nlist, None is auto calc, sqrt(len(ds)))",
)
# use_gpu
parser.add_argument(
"-g",
"--use_gpu",
action="store_true",
help="use gpu",
)
# no quantization
parser.add_argument(
"--no_quantization",
action="store_true",
help="no quantization",
)
# force override
parser.add_argument(
"--force",
action="store_true",
help="force override existing index file",
)
args = parser.parse_args()
@dataclass
class FaissConfig:
m: int = 8 # subvector
mbit: int = 8 # bits_per_idx
nlist: int | None = None # nlist, None is auto calc, sqrt(len(ds)))
quantization: bool = True
args = parser.parse_args()
target_local_ds = args.target
faiss_config = FaissConfig(
m=args.m,
mbit=args.mbit,
nlist=args.nlist,
quantization=not args.no_quantization,
)
embs_dir = "embs"
input_embs_path = Path("/".join(["embs", args.input_name, target_local_ds]))
input_embs_npz = list(input_embs_path.glob("*.npz"))
input_embs_npz.sort(key=lambda x: int(x.stem))
if len(input_embs_npz) == 0:
print(f"input embs not found: {input_embs_path}")
exit(1)
else:
print(f"input {len(input_embs_npz)} embs(*.npz) found: {input_embs_path}")
def gen_index_filename(config: FaissConfig, target_local_ds: str) -> str:
default_faiss_config = FaissConfig()
if (
config.m == default_faiss_config.m
and config.mbit == default_faiss_config.mbit
and config.nlist == default_faiss_config.nlist
and config.quantization == default_faiss_config.quantization
):
return f"{target_local_ds}.faiss"
elif not config.quantization:
return f"{target_local_ds}_no_quantization.faiss"
else:
return f"{target_local_ds}_m{config.m}_mbit{config.mbit}_nlist_{config.nlist}.faiss"
def gen_faiss_index(config: FaissConfig, dim: str, use_gpu: bool):
flat_l2 = faiss.IndexFlatL2(dim)
if not config.quantization:
faiss_index = flat_l2
else:
faiss_index = faiss.IndexIVFPQ(
flat_l2,
dim,
config.nlist,
config.m,
config.mbit,
)
if use_gpu:
gpu_res = faiss.StandardGpuResources() # use a single GPU
faiss_index = faiss.index_cpu_to_gpu(gpu_res, 0, faiss_index)
return faiss_index
else:
return faiss_index
output_faiss_path = Path(
"/".join(
[
"faiss_indexes",
args.input_name,
gen_index_filename(faiss_config, target_local_ds),
]
)
)
output_faiss_path.parent.mkdir(parents=True, exist_ok=True)
# output_faiss_path がすでにある場合
if output_faiss_path.exists():
if args.force:
print("force override existing index file")
print(f"[found] -> {output_faiss_path}")
else:
print("index file already exists, skip")
print(f"[found] -> {output_faiss_path}")
exit(0)
pbar = tqdm(total=len(input_embs_npz))
emb_total = 0
for idx, npz_file in enumerate(input_embs_npz):
with np.load(npz_file) as data:
embs = data["embs"].astype("float32")
if idx == 0:
dim = embs.shape[1]
if faiss_config.nlist is None:
faiss_config.nlist = int(np.sqrt(len(embs) * (len(input_embs_npz)-1)))
if faiss_config.nlist < 1:
faiss_config.nlist = 100
print(f"faiss_config: {faiss_config}")
if args.use_gpu:
print("use gpu for faiss index")
faiss_index = gen_faiss_index(faiss_config, dim, args.use_gpu)
faiss_index.train(embs) # type: ignore
faiss_index.add(embs) # type: ignore
pbar.update(1)
emb_total += len(embs)
pbar.set_description(f"added embs: {emb_total}")
pbar.close()
faiss_index.nprobe = 10 # type: ignore
if args.use_gpu:
faiss_index = faiss.index_gpu_to_cpu(faiss_index) # type: ignore
faiss.write_index(faiss_index, str(output_faiss_path)) # type: ignore
print("output faiss index file:", output_faiss_path)