File size: 4,967 Bytes
4646a6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1ebd09
4646a6d
c1ebd09
4646a6d
c1ebd09
4646a6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0fb0a80
 
 
4646a6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)