File size: 6,619 Bytes
4646a6d c1ebd09 4646a6d c1ebd09 4646a6d c1ebd09 4646a6d f023a57 4646a6d f023a57 4646a6d f023a57 4646a6d f023a57 4646a6d f023a57 4646a6d f023a57 4646a6d f023a57 4646a6d f023a57 4646a6d f023a57 |
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 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 |
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):
if use_gpu and config.m > 48:
return gen_faiss_index_f16_lookup(config, dim, use_gpu)
# quantizer = faiss.IndexFlatL2(dim)
if not config.quantization:
faiss_index = faiss.IndexFlatL2(dim)
else:
# faiss_index = faiss.IndexHNSWSQ(dim, faiss.ScalarQuantizer.QT_8bit, 16)
# faiss_index.hnsw.efConstruction = 512
# index.hnsw.efSearch = 128
# quantizer = faiss.IndexHNSWFlat(dim, 32)
quantizer = faiss.IndexFlatL2(dim)
faiss_index = faiss.IndexIVFPQ(
quantizer,
dim,
config.nlist,
config.m,
config.mbit,
)
# faiss_index = faiss.IndexIVFFlat(quantizer, dim, 16384)
# faiss_index.cp.min_points_per_centroid = 5 # quiet warning
# faiss_index.quantizer_trains_alone = 2
if use_gpu and getattr(faiss, "StandardGpuResources", None):
gpu_res = faiss.StandardGpuResources()
faiss_index = faiss.index_cpu_to_gpu(gpu_res, 0, faiss_index)
return faiss_index
else:
return faiss_index
def gen_faiss_index_f16_lookup(config: FaissConfig, dim: str, use_gpu: bool):
# use float16 lookup tables
gpu_resource = faiss.StandardGpuResources() # GPUリソースの初期化
gpu_index_config = faiss.GpuIndexIVFPQConfig() # IVFPQインデックスの設定用オブジェクト
gpu_index_config.useFloat16LookupTables = True # Float16ルックアップテーブルを使用する
quantizer = faiss.IndexFlatL2(dim) # 量子化器の定義
index = faiss.GpuIndexIVFPQ(
gpu_resource,
# quantizer,
dim,
config.nlist,
config.m,
config.mbit,
faiss.METRIC_L2,
gpu_index_config, # IVFPQインデックスの設定用オブジェクト
) # GPU上のIVFPQインデックスの作成
return 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
all_embs = []
for idx, npz_file in enumerate(tqdm(input_embs_npz)):
with np.load(npz_file) as data:
e = data["embs"].astype("float16")
all_embs.append(e)
embs: np.ndarray = np.concatenate(all_embs, axis=0, dtype="float32")
del all_embs
# 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)
print(f"start training faiss index, shape: {embs.shape}")
faiss_index.train(embs) # type: ignore
print(f"start adding embs to faiss index")
faiss_index.add(embs) # type: ignore
# pbar.update(1)
print(f"added embs: {embs.shape[0]}")
# 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)
# output_faiss_path のファイルサイズを MB で表示
print(
"output faiss index file size (MB):",
int(output_faiss_path.stat().st_size / 1024 / 1024),
)
|