Files
faiss/benchs/bench_flat_l2_panorama.py
T
Tia Lim 0f0f728166 Format faiss Python files with black (line length 80) (#5349)
Summary:
Pull Request resolved: https://github.com/facebookresearch/faiss/pull/5349

# this is a no-op change

Ran `black -l 80` over all tracked Python files under `fbcode/faiss/`, using line length 80 to match faiss's documented coding style (`CONTRIBUTING.md`: "80 character line length (both for C++ and Python)"). 172 files were reformatted; 28 were already compliant.

This is a pure-formatting change. `black` runs its AST-equivalence safety check on every file, so no identifiers, string/numeric values, operators, or control flow were altered — only whitespace, indentation, line wrapping, blank lines, trailing commas, and string-quote normalization (single to double quotes).

`fbcode/faiss/` is intentionally excluded from Meta's standard Python autoformatter (`arc f` / `arc lint -a` report no formatter for these paths) because it mirrors to public GitHub, so the Python had drifted out of any consistent style. The C++ is already clang-format-clean (0 of 807 files change), so this effort is Python-only. This diff brings the Python to canonical `black` formatting.

Excluded `demos/index_pq_flat_separate_codes_from_codebook.py`: it contains a Jupyter `!rm` shell-magic line and is not valid Python, so `black` cannot parse it.

This is the base of a 3-diff stack: (1) this black reformat; (2) `.flake8` alignment (max-line-length 80 + black-compatible ignores E203/W503); (3) genuine lint fixes (F401/F403/F841/B011).

Reviewed By: mnorris11

Differential Revision: D109736099

fbshipit-source-id: 9a054635766ed11aa3760a788395babd3d198abf
2026-06-29 17:29:05 -07:00

109 lines
2.4 KiB
Python

# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import multiprocessing as mp
import time
import faiss
import matplotlib.pyplot as plt
import numpy as np
try:
from faiss.contrib.datasets_fb import DatasetSIFT1M, DatasetGIST1M
except ImportError:
from faiss.contrib.datasets import DatasetSIFT1M, DatasetGIST1M
parser = argparse.ArgumentParser()
parser.add_argument("--dataset", default="gist1m", choices=["sift1m", "gist1m"])
args = parser.parse_args()
if args.dataset == "sift1m":
ds = DatasetSIFT1M()
else:
ds = DatasetGIST1M()
nq = 10
xq = ds.get_queries()[:nq]
xb = ds.get_database()
gt = ds.get_groundtruth()[:nq]
xt = ds.get_train()
nb, d = xb.shape
nt, d = xt.shape
k = 10
gt = gt[:, :k]
def eval_qps(index):
faiss.cvar.indexPanorama_stats.reset()
t0 = time.time()
_, I = index.search(xq, k=k)
t = time.time() - t0
speed = t * 1000 / nq # ms/query
qps = 1000 / speed
corrects = (gt == I).sum()
recall = corrects / (nq * k)
ratio_dims_scanned = faiss.cvar.indexPanorama_stats.ratio_dims_scanned
print(
f"\tRecall@{k}: {recall:.6f}, speed: {speed:.6f} ms/query, "
f"dims scanned: {ratio_dims_scanned * 100:.2f}%"
)
return recall, qps
def build_index(name):
index = faiss.index_factory(d, name)
faiss.omp_set_num_threads(mp.cpu_count())
index.train(xt)
index.add(xb)
faiss.omp_set_num_threads(1)
return index
nlevels = 16 if args.dataset == "gist1m" else 8
batch_size = 512
plt.figure(figsize=(8, 6), dpi=80)
names = [
"Flat",
f"PCA{d},FlatL2Panorama{nlevels}_{batch_size}",
]
labels = []
qps_values = []
for name in names:
print(f"======{name}")
index = build_index(name)
recall, qps = eval_qps(index)
labels.append(f"{name}\n(r@{recall:.3f})")
qps_values.append(qps)
x = np.arange(len(names))
plt.bar(x, qps_values, color=["#1f77b4", "#ff7f0e"])
speedup = qps_values[1] / qps_values[0]
ax = plt.gca()
ax.text(
x[1],
qps_values[1] * 1.01,
f"{speedup:.2f}x",
ha="center",
va="bottom",
)
plt.xticks(x, labels, rotation=0)
plt.ylabel("QPS")
dataset_label = args.dataset.upper()
plt.title(f"Flat Indexes on {dataset_label}")
plt.tight_layout()
plt.savefig(f"bench_flat_l2_panorama_{args.dataset}.png", bbox_inches="tight")